blob: df3ecbe09c9e8eb271ebec0e0ffcb6739871e45c [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_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900648 * arg1 = unused
649 * arg2 = netId
650 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800651 */
lucaslin444d43a2020-02-20 16:56:59 +0800652 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800653
654 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900655 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
656 * arg1 = unused
657 * arg2 = netId
658 * obj = captive portal data
659 */
lucaslin444d43a2020-02-20 16:56:59 +0800660 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900661
662 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900663 * Used by setRequireVpnForUids.
664 * arg1 = whether the specified UID ranges are required to use a VPN.
665 * obj = Array of UidRange objects.
666 */
667 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
668
669 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900670 * Used internally when setting the default networks for OemNetworkPreferences.
671 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800672 */
673 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
674
675 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800676 * Used to indicate the system default network becomes active.
677 */
678 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
679
680 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900681 * Used internally when setting a network preference for a user profile.
682 * obj = Pair<ProfileNetworkPreference, Listener>
683 */
684 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
685
686 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000687 * Event to specify that reasons for why an uid is blocked changed.
688 * arg1 = uid
689 * arg2 = blockedReasons
690 */
691 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
692
693 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900694 * Event to register a new network offer
695 * obj = NetworkOffer
696 */
697 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
698
699 /**
700 * Event to unregister an existing network offer
701 * obj = INetworkOfferCallback
702 */
703 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
704
705 /**
paulhu51f77dc2021-06-07 02:34:20 +0000706 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
707 */
708 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
709
710 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800711 * Event to set temporary allow bad wifi within a limited time to override
712 * {@code config_networkAvoidBadWifi}.
713 */
714 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
715
716 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100717 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
718 */
719 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
720
721 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900722 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
723 * should be shown.
724 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900725 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900726
727 /**
728 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
729 * should be hidden.
730 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900731 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900732
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800733 /**
734 * The maximum alive time to allow bad wifi configuration for testing.
735 */
736 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
737
Patrick Rohr2857ac42022-01-21 14:58:16 +0100738 /**
739 * The priority of the tc police rate limiter -- smaller value is higher priority.
740 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
741 */
742 private static final short TC_PRIO_POLICE = 1;
743
744 /**
745 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
746 */
747 private static final String TC_POLICE_BPF_PROG_PATH =
748 "/sys/fs/bpf/prog_netd_schedact_ingress_account";
749
Hugo Benichi47011212017-03-30 10:46:05 +0900750 private static String eventName(int what) {
751 return sMagicDecoderRing.get(what, Integer.toString(what));
752 }
753
paulhua10d8212020-11-10 15:32:56 +0800754 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900755 final DnsResolverServiceManager dsm = context.getSystemService(
756 DnsResolverServiceManager.class);
757 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800758 }
759
Cody Kesting73708bf2019-12-18 10:57:50 -0800760 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900761 @VisibleForTesting
762 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700763 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700764 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700765 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700766 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800767 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
768 @VisibleForTesting
769 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
770
Erik Kline32120082017-12-13 19:40:49 +0900771 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900772 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700773
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400774 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800775 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400776
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700777 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800778 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700779
Chalard Jean5d70ba42018-06-07 16:44:04 +0900780 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
781 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000782 @VisibleForTesting
783 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400784
Erik Kline05f2b402015-04-30 12:58:40 +0900785 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700786
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400787 private UserManager mUserManager;
788
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700789 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900790 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700791
Valentin Iftime9fa35092019-09-24 13:32:13 +0200792 private Set<String> mWolSupportedInterfaces;
793
Roshan Pius08c94fb2020-01-16 12:17:17 -0800794 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800795 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800796 private final AppOpsManager mAppOpsManager;
797
798 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400799
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900800 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700801 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900802 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900803 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900804
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700805 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800806 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700807
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900808 // Sequence number for NetworkProvider IDs.
809 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
810 NetworkProvider.FIRST_PROVIDER_ID);
811
Erik Klineedf878b2015-07-09 18:24:03 +0900812 // NetworkRequest activity String log entries.
813 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
814 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
815
Hugo Benichid159fdd2016-07-11 11:05:12 +0900816 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900817 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900818 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
819
Hugo Benichi47011212017-03-30 10:46:05 +0900820 private static final int MAX_WAKELOCK_LOGS = 20;
821 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900822 private int mTotalWakelockAcquisitions = 0;
823 private int mTotalWakelockReleases = 0;
824 private long mTotalWakelockDurationMs = 0;
825 private long mMaxWakelockDurationMs = 0;
826 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900827
Hugo Benichi208c0102016-07-28 17:53:06 +0900828 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900829
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700830 @GuardedBy("mBandwidthRequests")
831 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
832
Erik Kline95ecfee2016-10-02 18:02:14 +0900833 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900834 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900835
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900836 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800837 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
838 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800839
Patrick Rohr2857ac42022-01-21 14:58:16 +0100840 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
841 // configured via {@link
842 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
843 // Only the handler thread is allowed to access this field.
844 private long mIngressRateLimit = -1;
845
Robert Greenwalt802c1102014-06-02 15:32:02 -0700846 /**
847 * Implements support for the legacy "one network per network type" model.
848 *
849 * We used to have a static array of NetworkStateTrackers, one for each
850 * network type, but that doesn't work any more now that we can have,
851 * for example, more that one wifi network. This class stores all the
852 * NetworkAgentInfo objects that support a given type, but the legacy
853 * API will only see the first one.
854 *
855 * It serves two main purposes:
856 *
857 * 1. Provide information about "the network for a given type" (since this
858 * API only supports one).
859 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
860 * the first network for a given type changes, or if the default network
861 * changes.
862 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900863 @VisibleForTesting
864 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900865
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900866 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900867 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900868
Robert Greenwalt802c1102014-06-02 15:32:02 -0700869 /**
870 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
871 * Each list holds references to all NetworkAgentInfos that are used to
872 * satisfy requests for that network type.
873 *
874 * This array is built out at startup such that an unsupported network
875 * doesn't get an ArrayList instance, making this a tristate:
876 * unsupported, supported but not active and active.
877 *
878 * The actual lists are populated when we scan the network types that
879 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900880 *
881 * Threading model:
882 * - addSupportedType() is only called in the constructor
883 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
884 * They are therefore not thread-safe with respect to each other.
885 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
886 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900887 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900888 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700889 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900890 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900891 @NonNull
892 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700893
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900894 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
895 // an entry have no timer (equivalent to -1). Lazily loaded.
896 @NonNull
897 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
898
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900899 LegacyTypeTracker(@NonNull ConnectivityService service) {
900 mService = service;
901 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700902 }
903
Chiachang Wang3bc52762021-11-25 14:17:57 +0800904 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
905 // addressed.
906 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900907 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
908 final PackageManager pm = ctx.getPackageManager();
909 if (pm.hasSystemFeature(FEATURE_WIFI)) {
910 addSupportedType(TYPE_WIFI);
911 }
912 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
913 addSupportedType(TYPE_WIFI_P2P);
914 }
915 if (tm.isDataCapable()) {
916 // Telephony does not have granular support for these types: they are either all
917 // supported, or none is supported
918 addSupportedType(TYPE_MOBILE);
919 addSupportedType(TYPE_MOBILE_MMS);
920 addSupportedType(TYPE_MOBILE_SUPL);
921 addSupportedType(TYPE_MOBILE_DUN);
922 addSupportedType(TYPE_MOBILE_HIPRI);
923 addSupportedType(TYPE_MOBILE_FOTA);
924 addSupportedType(TYPE_MOBILE_IMS);
925 addSupportedType(TYPE_MOBILE_CBS);
926 addSupportedType(TYPE_MOBILE_IA);
927 addSupportedType(TYPE_MOBILE_EMERGENCY);
928 }
929 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
930 addSupportedType(TYPE_BLUETOOTH);
931 }
932 if (pm.hasSystemFeature(FEATURE_WATCH)) {
933 // TYPE_PROXY is only used on Wear
934 addSupportedType(TYPE_PROXY);
935 }
936 // Ethernet is often not specified in the configs, although many devices can use it via
937 // USB host adapters. Add it as long as the ethernet service is here.
938 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
939 addSupportedType(TYPE_ETHERNET);
940 }
941
942 // Always add TYPE_VPN as a supported type
943 addSupportedType(TYPE_VPN);
944 }
945
946 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700947 if (mTypeLists[type] != null) {
948 throw new IllegalStateException(
949 "legacy list for type " + type + "already initialized");
950 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900951 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700952 }
953
Robert Greenwalt802c1102014-06-02 15:32:02 -0700954 public boolean isTypeSupported(int type) {
955 return isNetworkTypeValid(type) && mTypeLists[type] != null;
956 }
957
958 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900959 synchronized (mTypeLists) {
960 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
961 return mTypeLists[type].get(0);
962 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700963 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900964 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700965 }
966
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900967 public int getRestoreTimerForType(int type) {
968 synchronized (mTypeLists) {
969 if (mRestoreTimers == null) {
970 mRestoreTimers = loadRestoreTimers();
971 }
972 return mRestoreTimers.getOrDefault(type, -1);
973 }
974 }
975
976 private ArrayMap<Integer, Integer> loadRestoreTimers() {
977 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900978 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900979 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
980 for (final String config : configs) {
981 final String[] splits = TextUtils.split(config, ",");
982 if (splits.length != 2) {
983 logwtf("Invalid restore timer token count: " + config);
984 continue;
985 }
986 try {
987 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
988 } catch (NumberFormatException e) {
989 logwtf("Invalid restore timer number format: " + config, e);
990 }
991 }
992 return ret;
993 }
994
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700995 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900996 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900997 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900998 log("Sending " + state
999 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001000 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001001 }
1002 }
1003
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001004 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1005 // network type, to preserve previous behaviour.
1006 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1007 if (vpnNai != mService.getLegacyLockdownNai()) return;
1008
1009 if (vpnNai.declaredUnderlyingNetworks == null
1010 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1011 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1012 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1013 return;
1014 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001015 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001016 vpnNai.declaredUnderlyingNetworks[0]);
1017 if (underlyingNai == null) return;
1018
1019 final int type = underlyingNai.networkInfo.getType();
1020 final DetailedState state = DetailedState.CONNECTED;
1021 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1022 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1023 }
1024
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001025 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001026 public void add(int type, NetworkAgentInfo nai) {
1027 if (!isTypeSupported(type)) {
1028 return; // Invalid network type.
1029 }
1030 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1031
1032 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1033 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001034 return;
1035 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001036 synchronized (mTypeLists) {
1037 list.add(nai);
1038 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001039
Chalard Jean5b409c72021-02-04 13:12:59 +09001040 // Send a broadcast if this is the first network of its type or if it's the default.
1041 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001042
1043 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1044 // to preserve previous behaviour.
1045 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001046 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001047 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1048 mService.sendLegacyNetworkBroadcast(nai, state, type);
1049 }
1050
1051 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1052 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001053 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001054 }
1055
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001056 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001057 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001058 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1059 if (list == null || list.isEmpty()) {
1060 return;
1061 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001062 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001063
Hugo Benichi389633f2016-06-21 09:48:07 +09001064 synchronized (mTypeLists) {
1065 if (!list.remove(nai)) {
1066 return;
1067 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001068 }
1069
Lorenzo Colitti49767722015-05-01 00:30:10 +09001070 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001071 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1072 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001073 }
1074
1075 if (!list.isEmpty() && wasFirstNetwork) {
1076 if (DBG) log("Other network available for type " + type +
1077 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001078 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001079 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001080 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001081 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001082 }
1083 }
1084
1085 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001086 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1087 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001088 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001089 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001090 }
1091 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001092
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001093 // send out another legacy broadcast - currently only used for suspend/unsuspend
1094 // toggle
1095 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001096 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001097 final DetailedState state = nai.networkInfo.getDetailedState();
1098 for (int type = 0; type < mTypeLists.length; type++) {
1099 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001100 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001101 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001102 if (isFirst || contains && isDefault) {
1103 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001104 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001105 }
1106 }
1107 }
1108
Robert Greenwalt94e22142014-07-30 16:31:24 -07001109 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001110 pw.println("mLegacyTypeTracker:");
1111 pw.increaseIndent();
1112 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001113 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001114 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001115 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001116 pw.println();
1117 pw.println("Current state:");
1118 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001119 synchronized (mTypeLists) {
1120 for (int type = 0; type < mTypeLists.length; type++) {
1121 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1122 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001123 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001124 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001125 }
1126 }
1127 pw.decreaseIndent();
1128 pw.decreaseIndent();
1129 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001130 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001131 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001132 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001133
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001134 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001135 /**
1136 * Helper class which parses out priority arguments and dumps sections according to their
1137 * priority. If priority arguments are omitted, function calls the legacy dump command.
1138 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001139 private class LocalPriorityDump {
1140 private static final String PRIORITY_ARG = "--dump-priority";
1141 private static final String PRIORITY_ARG_HIGH = "HIGH";
1142 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1143
1144 LocalPriorityDump() {}
1145
1146 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1147 doDump(fd, pw, new String[] {DIAG_ARG});
1148 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001149 }
1150
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001151 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1152 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001153 }
1154
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001155 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1156 if (args == null) {
1157 dumpNormal(fd, pw, args);
1158 return;
1159 }
1160
1161 String priority = null;
1162 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1163 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1164 argIndex++;
1165 priority = args[argIndex];
1166 }
1167 }
1168
1169 if (PRIORITY_ARG_HIGH.equals(priority)) {
1170 dumpHigh(fd, pw);
1171 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1172 dumpNormal(fd, pw, args);
1173 } else {
1174 // ConnectivityService publishes binder service using publishBinderService() with
1175 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001176 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1177 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001178 // TODO: Integrate into signal dump.
1179 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001180 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001181 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001182 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001183
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001184 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001185 * Keeps track of the number of requests made under different uids.
1186 */
1187 public static class PerUidCounter {
1188 private final int mMaxCountPerUid;
1189
1190 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001191 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001192 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001193 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001194
1195 /**
1196 * Constructor
1197 *
1198 * @param maxCountPerUid the maximum count per uid allowed
1199 */
1200 public PerUidCounter(final int maxCountPerUid) {
1201 mMaxCountPerUid = maxCountPerUid;
1202 }
1203
1204 /**
1205 * Increments the request count of the given uid. Throws an exception if the number
1206 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1207 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1208 *
1209 * @throws ServiceSpecificException with
1210 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1211 * the uid exceed the allowed number.
1212 *
1213 * @param uid the uid that the request was made under
1214 */
1215 public void incrementCountOrThrow(final int uid) {
1216 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001217 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001218 }
1219 }
1220
James Mattis20a4a8b2021-03-28 17:41:09 -07001221 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1222 final int newRequestCount =
1223 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001224 if (newRequestCount >= mMaxCountPerUid
1225 // HACK : the system server is allowed to go over the request count limit
1226 // when it is creating requests on behalf of another app (but not itself,
1227 // so it can still detect its own request leaks). This only happens in the
1228 // per-app API flows in which case the old requests for that particular
1229 // UID will be removed soon.
1230 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1231 // users of transact() should unregister the requests to decrease the count
1232 // before they increase it again by creating a new NRI. Then remove the
1233 // transact() method.
1234 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001235 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001236 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1237 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001238 }
1239 mUidToNetworkRequestCount.put(uid, newRequestCount);
1240 }
1241
Daniel Brightf9e945b2020-06-15 16:10:01 -07001242 /**
1243 * Decrements the request count of the given uid.
1244 *
1245 * @param uid the uid that the request was made under
1246 */
1247 public void decrementCount(final int uid) {
1248 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001249 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001250 }
1251 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001252
1253 private void decrementCount(final int uid, final int numToDecrement) {
1254 final int newRequestCount =
1255 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1256 if (newRequestCount < 0) {
1257 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1258 } else if (newRequestCount == 0) {
1259 mUidToNetworkRequestCount.delete(uid);
1260 } else {
1261 mUidToNetworkRequestCount.put(uid, newRequestCount);
1262 }
1263 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001264 }
1265
1266 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001267 * Dependencies of ConnectivityService, for injection in tests.
1268 */
1269 @VisibleForTesting
1270 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001271 public int getCallingUid() {
1272 return Binder.getCallingUid();
1273 }
1274
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001275 /**
1276 * Get system properties to use in ConnectivityService.
1277 */
1278 public MockableSystemProperties getSystemProperties() {
1279 return new MockableSystemProperties();
1280 }
1281
1282 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001283 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1284 */
1285 public ConnectivityResources getResources(@NonNull Context ctx) {
1286 return new ConnectivityResources(ctx);
1287 }
1288
1289 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001290 * Create a HandlerThread to use in ConnectivityService.
1291 */
1292 public HandlerThread makeHandlerThread() {
1293 return new HandlerThread("ConnectivityServiceThread");
1294 }
1295
1296 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001297 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001298 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001299 public NetworkStackClientBase getNetworkStack() {
1300 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001301 }
1302
1303 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001304 * @see ProxyTracker
1305 */
1306 public ProxyTracker makeProxyTracker(@NonNull Context context,
1307 @NonNull Handler connServiceHandler) {
1308 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1309 }
1310
1311 /**
1312 * @see NetIdManager
1313 */
1314 public NetIdManager makeNetIdManager() {
1315 return new NetIdManager();
1316 }
1317
1318 /**
1319 * @see NetworkUtils#queryUserAccess(int, int)
1320 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001321 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1322 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001323 }
1324
1325 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001326 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1327 * requires CAP_NET_ADMIN, which the unit tests do not have.
1328 */
1329 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1330 InetSocketAddress remote) {
1331 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1332 }
1333
1334 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001335 * @see MultinetworkPolicyTracker
1336 */
1337 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1338 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1339 return new MultinetworkPolicyTracker(c, h, r);
1340 }
1341
Aaron Huang330a4c02020-10-27 03:36:19 +08001342 /**
1343 * @see BatteryStatsManager
1344 */
1345 public void reportNetworkInterfaceForTransports(Context context, String iface,
1346 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001347 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001348 context.getSystemService(BatteryStatsManager.class);
1349 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1350 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001351
1352 public boolean getCellular464XlatEnabled() {
1353 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1354 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001355
1356 /**
1357 * @see PendingIntent#intentFilterEquals
1358 */
1359 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1360 return a.intentFilterEquals(b);
1361 }
1362
1363 /**
1364 * @see LocationPermissionChecker
1365 */
1366 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1367 return new LocationPermissionChecker(context);
1368 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001369
1370 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001371 * @see CarrierPrivilegeAuthenticator
1372 */
1373 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1374 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1375 if (SdkLevel.isAtLeastT()) {
1376 return new CarrierPrivilegeAuthenticator(context, tm);
1377 } else {
1378 return null;
1379 }
1380 }
1381
1382 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001383 * @see DeviceConfigUtils#isFeatureEnabled
1384 */
1385 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1386 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1387 TETHERING_MODULE_NAME, defaultEnabled);
1388 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001389
1390 /**
1391 * Get the BpfNetMaps implementation to use in ConnectivityService.
1392 * @param netd
1393 * @return BpfNetMaps implementation.
1394 */
1395 public BpfNetMaps getBpfNetMaps(INetd netd) {
1396 return new BpfNetMaps(netd);
1397 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001398
1399 /**
1400 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1401 */
1402 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1403 final InterfaceParams params = InterfaceParams.getByName(iface);
1404 if (params == null) {
1405 // the interface might have disappeared.
1406 logw("Failed to get interface params for interface " + iface);
1407 return;
1408 }
1409 try {
1410 // converting rateInBytesPerSecond from long to int is safe here because the
1411 // setting's range is limited to INT_MAX.
1412 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001413 Log.i(TAG,
1414 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001415 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1416 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1417 } catch (IOException e) {
1418 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1419 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1420 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1421 + ") failure: ", e);
1422 }
1423 }
1424
1425 /**
1426 * Wraps {@link TcUtils#tcFilterDelDev}
1427 */
1428 public void disableIngressRateLimit(String iface) {
1429 final InterfaceParams params = InterfaceParams.getByName(iface);
1430 if (params == null) {
1431 // the interface might have disappeared.
1432 logw("Failed to get interface params for interface " + iface);
1433 return;
1434 }
1435 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001436 Log.i(TAG,
1437 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001438 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1439 } catch (IOException e) {
1440 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1441 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1442 }
1443 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001444 }
1445
junyulaie7c7d2a2021-01-26 15:29:15 +08001446 public ConnectivityService(Context context) {
1447 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001448 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1449 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001450 }
1451
1452 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001453 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1454 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001455 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001456
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001457 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001458 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001459 mSystemProperties = mDeps.getSystemProperties();
1460 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001461 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001462 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001463 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001464 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001465
Hugo Benichi208c0102016-07-28 17:53:06 +09001466 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001467 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001468 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1469 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001470 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001471 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001472 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001473 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1474 mDefaultNetworkRequests.add(mDefaultRequest);
1475 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001476
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001477 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001478 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001479
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001480 // The default WiFi request is a background request so that apps using WiFi are
1481 // migrated to a better network (typically ethernet) when one comes up, instead
1482 // of staying on WiFi forever.
1483 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1484 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1485
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001486 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1487 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1488 NetworkRequest.Type.BACKGROUND_REQUEST);
1489
Chalard Jean0702f982021-09-16 21:50:07 +09001490 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1491 // TODO: Consider making the timer customizable.
1492 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1493 mCellularRadioTimesharingCapable =
1494 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1495
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001496 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001497 mHandlerThread.start();
1498 mHandler = new InternalHandler(mHandlerThread.getLooper());
1499 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001500 mConnectivityDiagnosticsHandler =
1501 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001502
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001503 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001504 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001505
junyulaie7c7d2a2021-01-26 15:29:15 +08001506 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001507 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001508 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001509 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001510
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001511 mNetd = netd;
Wayne Ma2fde98c2022-01-17 18:04:05 +08001512 mBpfNetMaps = mDeps.getBpfNetMaps(netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001513 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001514 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001515 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001516 mCarrierPrivilegeAuthenticator =
1517 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001518
Sudheer Shanka9967d462021-03-18 19:09:25 +00001519 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001520 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1521 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001522 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001523
1524 final PowerManager powerManager = (PowerManager) context.getSystemService(
1525 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001526 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001527 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001528
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001529 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1530 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001531 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001532 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001533 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001534 mProtectedNetworks.add(p);
1535 } else {
1536 if (DBG) loge("Ignoring protectedNetwork " + p);
1537 }
1538 }
1539
soma, kawata29444ae2019-05-23 09:30:40 +09001540 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1541
Wayne Ma2fde98c2022-01-17 18:04:05 +08001542 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001543
James Mattis02220e22021-03-13 19:27:21 -08001544 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001545 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001546 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001547 final IntentFilter userIntentFilter = new IntentFilter();
1548 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1549 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1550 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1551 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001552
James Mattis02220e22021-03-13 19:27:21 -08001553 // Listen to package add/removes for netd
1554 final IntentFilter packageIntentFilter = new IntentFilter();
1555 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1556 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1557 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1558 packageIntentFilter.addDataScheme("package");
1559 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001560 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001561
lucaslind5c2d072021-02-20 18:59:47 +08001562 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001563
lucaslin66f44212021-02-23 01:12:55 +08001564 mNetdCallback = new NetdCallback();
1565 try {
1566 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1567 } catch (RemoteException | ServiceSpecificException e) {
1568 loge("Error registering event listener :" + e);
1569 }
1570
Erik Kline05f2b402015-04-30 12:58:40 +09001571 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1572 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001573
junyulai7e06ad42019-03-04 22:45:36 +08001574 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001575 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001576 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001577
1578 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001579 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001580 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1581 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001582 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001583 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1584 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001585
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001586 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001587 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001588 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001589
Chiachang Wangc1215d32020-10-20 15:38:58 +08001590 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001591 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001592
Chalard Jean28018572020-12-21 18:36:52 +09001593 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1594 // request that doesn't allow fallback to the default network. It should never be visible
1595 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1596 // arguments like the handler or the DnsResolver.
1597 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001598 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001599 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001600 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001601 new LinkProperties(), new NetworkCapabilities(),
1602 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001603 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1604 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001605
1606 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001607 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1608 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1609 // Even if it could, running on S would at least require mocking out the BPF map,
1610 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1611 // the bpf syscall. http://aosp/1907693
1612 if (SdkLevel.isAtLeastT()) {
1613 mDscpPolicyTracker = new DscpPolicyTracker();
1614 }
Tyler Wear72388212021-09-09 14:49:02 -07001615 } catch (ErrnoException e) {
1616 loge("Unable to create DscpPolicyTracker");
1617 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001618
1619 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1620 mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001621 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001622
Chalard Jean46adcf32018-04-18 20:18:38 +09001623 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001624 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1625 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001626 }
1627
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001628 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1629 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001630 final NetworkCapabilities netCap = new NetworkCapabilities();
1631 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001632 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001633 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001634 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001635 return netCap;
1636 }
1637
James Mattis45d81842021-01-10 14:24:24 -08001638 private NetworkRequest createDefaultRequest() {
1639 return createDefaultInternetRequestForTransport(
1640 TYPE_NONE, NetworkRequest.Type.REQUEST);
1641 }
1642
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001643 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001644 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001645 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001646 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001647 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001648 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001649 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001650 netCap.addTransportType(transportType);
1651 }
James Mattis45d81842021-01-10 14:24:24 -08001652 return createNetworkRequest(type, netCap);
1653 }
1654
1655 private NetworkRequest createNetworkRequest(
1656 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001657 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001658 }
1659
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001660 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1661 NetworkRequest.Type type) {
1662 final NetworkCapabilities netCap = new NetworkCapabilities();
1663 netCap.clearAll();
1664 netCap.addCapability(capability);
1665 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1666 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1667 }
1668
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001669 // Used only for testing.
1670 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001671 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001672 // changing ContentResolver to make registerContentObserver non-final).
1673 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1674 // by subclassing SettingsObserver.
1675 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001676 void updateAlwaysOnNetworks() {
1677 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001678 }
1679
Erik Kline9a62f012018-03-21 07:18:33 -07001680 // See FakeSettingsProvider comment above.
1681 @VisibleForTesting
1682 void updatePrivateDnsSettings() {
1683 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1684 }
1685
paulhu51f77dc2021-06-07 02:34:20 +00001686 @VisibleForTesting
1687 void updateMobileDataPreferredUids() {
1688 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1689 }
1690
Patrick Rohr2857ac42022-01-21 14:58:16 +01001691 @VisibleForTesting
1692 void updateIngressRateLimit() {
1693 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1694 }
1695
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001696 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001697 final boolean enable = mContext.getResources().getBoolean(id);
1698 handleAlwaysOnNetworkRequest(networkRequest, enable);
1699 }
1700
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001701 private void handleAlwaysOnNetworkRequest(
1702 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001703 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001704 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001705 handleAlwaysOnNetworkRequest(networkRequest, enable);
1706 }
1707
1708 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001709 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001710 if (enable == isEnabled) {
1711 return; // Nothing to do.
1712 }
1713
1714 if (enable) {
1715 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001716 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001717 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001718 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001719 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001720 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1721 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001722 }
1723 }
1724
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001725 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001726 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1727 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1728 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1729 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001730 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1731 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001732 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001733 }
1734
paulhu51f77dc2021-06-07 02:34:20 +00001735 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001736 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001737 private void registerSettingsCallbacks() {
1738 // Watch for global HTTP proxy changes.
1739 mSettingsObserver.observe(
1740 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1741 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1742
1743 // Watch for whether or not to keep mobile data always on.
1744 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001745 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001746 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1747
1748 // Watch for whether or not to keep wifi always on.
1749 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001750 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001751 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001752
1753 // Watch for mobile data preferred uids changes.
1754 mSettingsObserver.observe(
1755 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1756 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001757
1758 // Watch for ingress rate limit changes.
1759 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001760 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001761 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1762 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001763 }
1764
Erik Kline31b4a9e2018-01-11 21:07:29 +09001765 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001766 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1767 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001768 }
1769 }
1770
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001771 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001772 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1773 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001774 return mNextNetworkRequestId++;
1775 }
1776
junyulai74f9a8b2018-06-13 15:00:37 +08001777 @VisibleForTesting
1778 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001779 if (network == null) {
1780 return null;
1781 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001782 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001783 }
1784
1785 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001786 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001787 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001788 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001789 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001790
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001791 // TODO: determine what to do when more than one VPN applies to |uid|.
1792 private NetworkAgentInfo getVpnForUid(int uid) {
1793 synchronized (mNetworkForNetId) {
1794 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1795 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1796 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1797 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001798 }
1799 }
1800 }
1801 return null;
1802 }
1803
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001804 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001805 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001806 final NetworkAgentInfo nai = getVpnForUid(uid);
1807 if (nai != null) return nai.declaredUnderlyingNetworks;
1808 return null;
1809 }
1810
Lorenzo Colittia7574052021-01-19 01:33:05 +09001811 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001812 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001813
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001814 final Network[] networks = getVpnUnderlyingNetworks(uid);
1815 if (networks != null) {
1816 // getUnderlyingNetworks() returns:
1817 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1818 // empty array => the VPN explicitly said "no default network".
1819 // non-empty array => the VPN specified one or more default networks; we use the
1820 // first one.
1821 if (networks.length > 0) {
1822 nai = getNetworkAgentInfoForNetwork(networks[0]);
1823 } else {
1824 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001825 }
1826 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001827 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001828 }
1829
1830 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001831 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001832 */
paulhu7aeba372020-12-30 00:42:19 +08001833 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1834 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001835 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001836 if (ignoreBlocked) {
1837 return false;
1838 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001839 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001840 final long ident = Binder.clearCallingIdentity();
1841 try {
1842 final boolean metered = nc == null ? true : nc.isMetered();
1843 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1844 } finally {
1845 Binder.restoreCallingIdentity(ident);
1846 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001847 }
1848
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001849 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001850 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1851 return;
1852 }
Hugo Benichi47011212017-03-30 10:46:05 +09001853 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001854 synchronized (mBlockedAppUids) {
1855 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001856 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001857 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001858 blocked = false;
1859 } else {
1860 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001861 }
1862 }
Hugo Benichi47011212017-03-30 10:46:05 +09001863 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1864 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1865 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001866 }
1867
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001868 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001869 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1870 return;
1871 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001872 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001873 final int requestId = nri.getActiveRequest() != null
1874 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001875 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001876 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001877 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001878 }
1879
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001880 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001881 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001882 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001883 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001884 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001885 @NonNull
1886 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1887 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001888 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1889 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1890 // but only exists if an app asks about them or requests them. Ensure the requesting app
1891 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001892 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001893 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1894 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1895 null /* extraInfo */);
1896 }
1897 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001898 return filtered;
1899 }
1900
1901 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1902 boolean ignoreBlocked) {
1903 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1904 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001905 }
1906
1907 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 * Return NetworkInfo for the active (i.e., connected) network interface.
1909 * It is assumed that at most one network is active at a time. If more
1910 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001911 * @return the info for the active network, or {@code null} if none is
1912 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001913 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001914 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001915 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001916 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001917 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001918 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1919 if (nai == null) return null;
1920 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1921 maybeLogBlockedNetworkInfo(networkInfo, uid);
1922 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001923 }
1924
Paul Jensen1f567382015-02-13 14:18:39 -05001925 @Override
1926 public Network getActiveNetwork() {
1927 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001928 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001929 }
1930
1931 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001932 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001933 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001934 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001935 }
1936
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001937 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001938 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1939 if (vpnNai != null) {
1940 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1941 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1942 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001943 }
Paul Jensen1f567382015-02-13 14:18:39 -05001944 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001945
James Mattis2516da32021-01-31 17:06:19 -08001946 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001947 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1948 ignoreBlocked)) {
1949 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001950 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001951 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001952 }
1953
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001954 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001955 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001956 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001957 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1958 if (nai == null) return null;
1959 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001960 }
1961
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001962 /** Returns a NetworkInfo object for a network that doesn't exist. */
1963 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1964 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1965 getNetworkTypeName(networkType), "" /* subtypeName */);
1966 info.setIsAvailable(true);
1967 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1968 // background data is restricted.
1969 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1970 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1971 ? DetailedState.BLOCKED
1972 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001973 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1974 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001975 return info;
1976 }
1977
Lorenzo Colittia7574052021-01-19 01:33:05 +09001978 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001979 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1980 return null;
1981 }
1982 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001983 if (nai == null) {
1984 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001985 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001986 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1987 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001988 }
1989
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001990 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001991 public NetworkInfo getNetworkInfo(int networkType) {
1992 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001993 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001994 if (getVpnUnderlyingNetworks(uid) != null) {
1995 // A VPN is active, so we may need to return one of its underlying networks. This
1996 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001997 // getNetworkAgentInfoForUid.
1998 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1999 if (nai == null) return null;
2000 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2001 if (networkInfo.getType() == networkType) {
2002 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002003 }
2004 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002005 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002006 }
2007
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002008 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002009 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002010 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002011 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002012 if (nai == null) return null;
2013 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002014 }
2015
2016 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002017 public NetworkInfo[] getAllNetworkInfo() {
2018 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002019 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002020 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2021 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002022 NetworkInfo info = getNetworkInfo(networkType);
2023 if (info != null) {
2024 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002025 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002026 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002027 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002028 }
2029
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002030 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002031 public Network getNetworkForType(int networkType) {
2032 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002033 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2034 return null;
2035 }
2036 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2037 if (nai == null) {
2038 return null;
2039 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002040 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002041 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2042 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002043 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002044 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002045 }
2046
2047 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002048 public Network[] getAllNetworks() {
2049 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002050 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002051 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002052 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002053 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002054 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002055 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002056 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002057 }
2058
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002059 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002060 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002061 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002062 // The basic principle is: if an app's traffic could possibly go over a
2063 // network, without the app doing anything multinetwork-specific,
2064 // (hence, by "default"), then include that network's capabilities in
2065 // the array.
2066 //
2067 // In the normal case, app traffic only goes over the system's default
2068 // network connection, so that's the only network returned.
2069 //
2070 // With a VPN in force, some app traffic may go into the VPN, and thus
2071 // over whatever underlying networks the VPN specifies, while other app
2072 // traffic may go over the system default network (e.g.: a split-tunnel
2073 // VPN, or an app disallowed by the VPN), so the set of networks
2074 // returned includes the VPN's underlying networks and the system
2075 // default.
2076 enforceAccessPermission();
2077
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002078 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002079
James Mattis2516da32021-01-31 17:06:19 -08002080 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2081 if (!nri.isBeingSatisfied()) {
2082 continue;
2083 }
2084 final NetworkAgentInfo nai = nri.getSatisfier();
2085 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2086 if (null != nc
2087 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2088 && !result.containsKey(nai.network)) {
2089 result.put(
2090 nai.network,
2091 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002092 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002093 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2094 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002095 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002096 }
2097
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002098 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002099 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002100 if (null != networks) {
2101 for (final Network network : networks) {
2102 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2103 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002104 result.put(
2105 network,
2106 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002107 nc,
2108 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002109 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002110 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002111 }
2112 }
2113 }
2114
2115 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2116 out = result.values().toArray(out);
2117 return out;
2118 }
2119
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002120 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002121 public boolean isNetworkSupported(int networkType) {
2122 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002123 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002124 }
2125
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002126 /**
2127 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002128 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002129 * @return the ip properties for the active network, or {@code null} if
2130 * none is active
2131 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002132 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002133 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002134 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002135 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002136 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2137 if (nai == null) return null;
2138 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002139 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002140 }
2141
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002142 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002143 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002144 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002145 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002146 final LinkProperties lp = getLinkProperties(nai);
2147 if (lp == null) return null;
2148 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002149 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002150 }
2151
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002152 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002153 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002154 public LinkProperties getLinkProperties(Network network) {
2155 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002156 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2157 if (lp == null) return null;
2158 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002159 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002160 }
2161
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002162 @Nullable
2163 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002164 if (nai == null) {
2165 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002166 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002167 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002168 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002169 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002170 }
2171
lucaslinc582d502022-01-27 09:07:00 +08002172 @Override
2173 @Nullable
2174 public LinkProperties redactLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
2175 @NonNull String packageName, @Nullable String callingAttributionTag) {
2176 Objects.requireNonNull(packageName);
2177 Objects.requireNonNull(lp);
2178 enforceNetworkStackOrSettingsPermission();
2179 if (!checkAccessPermission(-1 /* pid */, uid)) {
2180 return null;
2181 }
2182 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2183 }
2184
Qingxi Lib2748102020-01-08 12:51:49 -08002185 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2186 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2187 }
2188
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002189 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002190 if (nai == null) return null;
2191 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002192 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002193 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002194 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002195 }
2196
2197 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002198 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2199 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002200 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002201 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002202 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002203 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002204 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002205 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002206 }
2207
lucaslinc582d502022-01-27 09:07:00 +08002208 @Override
2209 public NetworkCapabilities redactNetworkCapabilitiesForPackage(@NonNull NetworkCapabilities nc,
2210 int uid, @NonNull String packageName, @Nullable String callingAttributionTag) {
2211 Objects.requireNonNull(nc);
2212 Objects.requireNonNull(packageName);
2213 enforceNetworkStackOrSettingsPermission();
2214 if (!checkAccessPermission(-1 /* pid */, uid)) {
2215 return null;
2216 }
2217 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2218 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2219 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2220 callingAttributionTag);
2221 }
2222
Qingxi Libb8da982020-01-17 17:54:27 -08002223 @VisibleForTesting
2224 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002225 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002226 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2227 // this would be expensive (one more permission check every time any NC callback is
2228 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2229 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2230 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002231 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002232 if (!checkSettingsPermission(callerPid, callerUid)) {
2233 newNc.setUids(null);
2234 newNc.setSSID(null);
lucaslinc582d502022-01-27 09:07:00 +08002235 // TODO: Processes holding NETWORK_FACTORY should be able to see the underlying networks
lucaslin6adf5ac2021-10-19 15:04:56 +08002236 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002237 }
Etan Cohen107ae952018-12-30 17:59:59 -08002238 if (newNc.getNetworkSpecifier() != null) {
2239 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2240 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002241 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002242 if (!checkAnyPermissionOf(
2243 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09002244 newNc.setAccessUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002245 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002246 }
Qingxi Libb8da982020-01-17 17:54:27 -08002247
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002248 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002249 }
2250
Roshan Pius98f59ec2021-02-23 08:47:39 -08002251 /**
2252 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002253 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002254 * NetworkCapabilities.
2255 * Note: This wrapper does not support any sort of invalidation and thus must not be
2256 * persistent or long-lived. It may only be used for the time necessary to
2257 * compute the redactions required by one particular NetworkCallback or
2258 * synchronous call.
2259 */
2260 private class RedactionPermissionChecker {
2261 private final int mCallingPid;
2262 private final int mCallingUid;
2263 @NonNull private final String mCallingPackageName;
2264 @Nullable private final String mCallingAttributionTag;
2265
2266 private Boolean mHasLocationPermission = null;
2267 private Boolean mHasLocalMacAddressPermission = null;
2268 private Boolean mHasSettingsPermission = null;
2269
2270 RedactionPermissionChecker(int callingPid, int callingUid,
2271 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2272 mCallingPid = callingPid;
2273 mCallingUid = callingUid;
2274 mCallingPackageName = callingPackageName;
2275 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002276 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002277
2278 private boolean hasLocationPermissionInternal() {
2279 final long token = Binder.clearCallingIdentity();
2280 try {
2281 return mLocationPermissionChecker.checkLocationPermission(
2282 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2283 null /* message */);
2284 } finally {
2285 Binder.restoreCallingIdentity(token);
2286 }
2287 }
2288
2289 /**
2290 * Returns whether the app holds location permission or not (might return cached result
2291 * if the permission was already checked before).
2292 */
2293 public boolean hasLocationPermission() {
2294 if (mHasLocationPermission == null) {
2295 // If there is no cached result, perform the check now.
2296 mHasLocationPermission = hasLocationPermissionInternal();
2297 }
2298 return mHasLocationPermission;
2299 }
2300
2301 /**
2302 * Returns whether the app holds local mac address permission or not (might return cached
2303 * result if the permission was already checked before).
2304 */
2305 public boolean hasLocalMacAddressPermission() {
2306 if (mHasLocalMacAddressPermission == null) {
2307 // If there is no cached result, perform the check now.
2308 mHasLocalMacAddressPermission =
2309 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2310 }
2311 return mHasLocalMacAddressPermission;
2312 }
2313
2314 /**
2315 * Returns whether the app holds settings permission or not (might return cached
2316 * result if the permission was already checked before).
2317 */
2318 public boolean hasSettingsPermission() {
2319 if (mHasSettingsPermission == null) {
2320 // If there is no cached result, perform the check now.
2321 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2322 }
2323 return mHasSettingsPermission;
2324 }
2325 }
2326
2327 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2328 @NetworkCapabilities.NetCapability long redaction) {
2329 return (redactions & redaction) != 0;
2330 }
2331
2332 /**
2333 * Use the provided |applicableRedactions| to check the receiving app's
2334 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2335 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2336 * before being sent to the corresponding app.
2337 */
2338 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2339 @NetworkCapabilities.RedactionType long applicableRedactions,
2340 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2341 boolean includeLocationSensitiveInfo) {
2342 long redactions = applicableRedactions;
2343 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2344 if (includeLocationSensitiveInfo
2345 && redactionPermissionChecker.hasLocationPermission()) {
2346 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2347 }
2348 }
2349 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2350 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2351 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2352 }
2353 }
2354 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2355 if (redactionPermissionChecker.hasSettingsPermission()) {
2356 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2357 }
2358 }
2359 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002360 }
2361
Qingxi Lib2748102020-01-08 12:51:49 -08002362 @VisibleForTesting
2363 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002364 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002365 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002366 int callingPid, int callingUid, @NonNull String callingPkgName,
2367 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002368 if (nc == null) {
2369 return null;
2370 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002371 // Avoid doing location permission check if the transport info has no location sensitive
2372 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002373 final RedactionPermissionChecker redactionPermissionChecker =
2374 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2375 callingAttributionTag);
2376 final long redactions = retrieveRequiredRedactions(
2377 nc.getApplicableRedactions(), redactionPermissionChecker,
2378 includeLocationSensitiveInfo);
2379 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002380 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002381 // TODO : calling UID is redacted because apps should generally not know what UID is
2382 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002383 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002384 newNc.setOwnerUid(INVALID_UID);
2385 return newNc;
2386 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002387 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2388 if (nc.hasTransport(TRANSPORT_VPN)) {
2389 // Owner UIDs already checked above. No need to re-check.
2390 return newNc;
2391 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002392 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2393 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002394 // compatibility for older apps.
2395 if (!includeLocationSensitiveInfo
2396 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002397 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002398 newNc.setOwnerUid(INVALID_UID);
2399 return newNc;
2400 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002401 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002402 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002403 newNc.setOwnerUid(INVALID_UID);
2404 }
Qingxi Lib2748102020-01-08 12:51:49 -08002405 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002406 }
2407
lucaslinc582d502022-01-27 09:07:00 +08002408 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002409 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2410 LinkProperties lp, int callerPid, int callerUid) {
2411 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002412 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2413 // this would be expensive (one more permission check every time any LP callback is
2414 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2415 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2416 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002417
2418 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2419 final boolean needsSanitization =
2420 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2421 if (!needsSanitization) {
2422 return new LinkProperties(lp);
2423 }
2424
2425 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002426 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002427 }
2428
2429 final LinkProperties newLp = new LinkProperties(lp);
2430 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2431 // object gets parceled.
2432 newLp.setCaptivePortalApiUrl(null);
2433 newLp.setCaptivePortalData(null);
2434 return newLp;
2435 }
2436
Roshan Pius08c94fb2020-01-16 12:17:17 -08002437 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2438 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002439 // There is no need to track the effective UID of the request here. If the caller
2440 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002441 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002442 // Unprivileged apps can only pass in null or their own UID.
2443 if (nc.getUids() == null) {
2444 // If the caller passes in null, the callback will also match networks that do not
2445 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2446 // In this case, redact everything in the request immediately. This ensures that the
2447 // app is not able to get any redacted information by filing an unredacted request
2448 // and observing whether the request matches something.
2449 if (nc.getNetworkSpecifier() != null) {
2450 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2451 }
2452 } else {
2453 nc.setSingleUid(callerUid);
2454 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002455 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002456 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002457 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002458
2459 // Clear owner UID; this can never come from an app.
2460 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002461 }
2462
Chalard Jean38354d12018-03-20 19:13:57 +09002463 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002464 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002465 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2466 }
2467 }
2468
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002469 @Override
2470 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2471 enforceAccessPermission();
2472 final int callerUid = Binder.getCallingUid();
2473 final long token = Binder.clearCallingIdentity();
2474 try {
2475 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2476 } finally {
2477 Binder.restoreCallingIdentity(token);
2478 }
2479 }
2480
junyulaiebd15162021-03-03 12:09:05 +08002481 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002482 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002483 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002484 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002485 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002486
Serik Beketayev05130302021-01-15 16:47:25 -08002487 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002488 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002489 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2490 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002491 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002492 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002493 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002494 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2495 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002496 }
2497 }
2498 return result.toArray(new NetworkState[result.size()]);
2499 }
2500
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002501 @Override
junyulaiebd15162021-03-03 12:09:05 +08002502 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002503 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002504 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002505 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002506
2507 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2508 for (Network network : getAllNetworks()) {
2509 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002510 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002511 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2512 // NetworkCapabilities, which may contain UIDs of apps to which the
2513 // network applies. Should the UIDs be cleared so as not to leak or
2514 // interfere ?
2515 result.add(nai.getNetworkStateSnapshot());
2516 }
2517 }
2518 return result;
2519 }
2520
2521 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002522 public boolean isActiveNetworkMetered() {
2523 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002524
Qingxi Lib2748102020-01-08 12:51:49 -08002525 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002526 if (caps != null) {
2527 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2528 } else {
2529 // Always return the most conservative value
2530 return true;
2531 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002532 }
2533
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002534 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002535 * Ensures that the system cannot call a particular method.
2536 */
2537 private boolean disallowedBecauseSystemCaller() {
2538 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002539 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2540 // for devices launched with Q and above. However, existing devices upgrading to Q and
2541 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002542 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002543 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002544 log("This method exists only for app backwards compatibility"
2545 + " and must not be called by system services.");
2546 return true;
2547 }
2548 return false;
2549 }
2550
paulhub2c28682021-08-18 18:35:54 +08002551 private int getAppUid(final String app, final UserHandle user) {
2552 final PackageManager pm =
2553 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2554 final long token = Binder.clearCallingIdentity();
2555 try {
2556 return pm.getPackageUid(app, 0 /* flags */);
2557 } catch (PackageManager.NameNotFoundException e) {
2558 return -1;
2559 } finally {
2560 Binder.restoreCallingIdentity(token);
2561 }
2562 }
2563
2564 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2565 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2566 if (getAppUid(packageName, user) != callingUid) {
2567 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2568 }
2569 }
2570
Lorenzo Colitti23862912018-09-28 11:31:55 +09002571 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002572 * Ensure that a network route exists to deliver traffic to the specified
2573 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002574 * @param networkType the type of the network over which traffic to the
2575 * specified host is to be routed
2576 * @param hostAddress the IP address of the host to which the route is
2577 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002578 * @return {@code true} on success, {@code false} on failure
2579 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002580 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002581 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2582 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002583 if (disallowedBecauseSystemCaller()) {
2584 return false;
2585 }
paulhub2c28682021-08-18 18:35:54 +08002586 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002587 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002588 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002589 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002590 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002591
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002592 InetAddress addr;
2593 try {
2594 addr = InetAddress.getByAddress(hostAddress);
2595 } catch (UnknownHostException e) {
2596 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2597 return false;
2598 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002599
The Android Open Source Project28527d22009-03-03 19:31:44 -08002600 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002601 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002602 return false;
2603 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002604
2605 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2606 if (nai == null) {
2607 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2608 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2609 } else {
2610 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2611 }
2612 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002613 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002614
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002615 DetailedState netState;
2616 synchronized (nai) {
2617 netState = nai.networkInfo.getDetailedState();
2618 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002619
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002620 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002621 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002622 log("requestRouteToHostAddress on down network "
2623 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002624 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002625 }
2626 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002627 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002628
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002629 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002630 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002631 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002632 LinkProperties lp;
2633 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002634 synchronized (nai) {
2635 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002636 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002637 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002638 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002639 if (DBG) {
2640 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2641 }
Wink Saville32506bc2013-06-29 21:10:57 -07002642 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002643 } finally {
2644 Binder.restoreCallingIdentity(token);
2645 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002646 }
2647
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002648 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002649 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002650 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002651 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002652 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002653 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002654 if (bestRoute.getGateway().equals(addr)) {
2655 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002656 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002657 } else {
2658 // if we will connect to this through another route, add a direct route
2659 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002660 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002661 }
2662 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002663 if (DBG) log("Adding legacy route " + bestRoute +
2664 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002665
2666 final String dst = bestRoute.getDestinationLinkAddress().toString();
2667 final String nextHop = bestRoute.hasGateway()
2668 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002669 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002670 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2671 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002672 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002673 return false;
2674 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002675 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002676 }
2677
paulhu7c0a2e62021-01-08 00:51:49 +08002678 class DnsResolverUnsolicitedEventCallback extends
2679 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002680 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002681 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002682 try {
2683 mHandler.sendMessage(mHandler.obtainMessage(
2684 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002685 new PrivateDnsValidationUpdate(event.netId,
2686 InetAddresses.parseNumericAddress(event.ipAddress),
2687 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002688 } catch (IllegalArgumentException e) {
2689 loge("Error parsing ip address in validation event");
2690 }
2691 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002692
2693 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002694 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2695 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002696 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2697 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2698 // event callback for certain nai. e.g. cellular. Register here to pass to
2699 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002700 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2701 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2702 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002703 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002704 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002705 }
2706 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002707
2708 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002709 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2710 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2711 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002712 }
dalyk1720e542018-03-05 12:42:22 -05002713
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002714 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002715 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002716 return this.VERSION;
2717 }
2718
2719 @Override
2720 public String getInterfaceHash() {
2721 return this.HASH;
2722 }
paulhu7c0a2e62021-01-08 00:51:49 +08002723 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002724
2725 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002726 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2727 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002728
paulhu7c0a2e62021-01-08 00:51:49 +08002729 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002730 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002731 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002732 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002733 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002734 }
2735 }
2736
Sudheer Shanka9967d462021-03-18 19:09:25 +00002737 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002738 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002739 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2741 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002742 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002743 };
2744
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002745 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002746 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002747 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002748 }
2749
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002750 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002751 for (String permission : permissions) {
2752 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002753 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002754 }
2755 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002756 return false;
2757 }
2758
paulhu1a407652019-03-22 16:35:06 +08002759 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2760 for (String permission : permissions) {
2761 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2762 return true;
2763 }
2764 }
2765 return false;
2766 }
2767
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002768 private void enforceAnyPermissionOf(String... permissions) {
2769 if (!checkAnyPermissionOf(permissions)) {
2770 throw new SecurityException("Requires one of the following permissions: "
2771 + String.join(", ", permissions) + ".");
2772 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002773 }
2774
Paul Jensen83f5d572014-08-29 09:54:01 -04002775 private void enforceInternetPermission() {
2776 mContext.enforceCallingOrSelfPermission(
2777 android.Manifest.permission.INTERNET,
2778 "ConnectivityService");
2779 }
2780
The Android Open Source Project28527d22009-03-03 19:31:44 -08002781 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002782 mContext.enforceCallingOrSelfPermission(
2783 android.Manifest.permission.ACCESS_NETWORK_STATE,
2784 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002785 }
2786
lucaslinc582d502022-01-27 09:07:00 +08002787 private boolean checkAccessPermission(int pid, int uid) {
2788 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2789 == PERMISSION_GRANTED;
2790 }
2791
paulhua6ee2122021-02-22 15:40:43 +08002792 /**
2793 * Performs a strict and comprehensive check of whether a calling package is allowed to
2794 * change the state of network, as the condition differs for pre-M, M+, and
2795 * privileged/preinstalled apps. The caller is expected to have either the
2796 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2797 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2798 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2799 * permission and cannot be revoked. See http://b/23597341
2800 *
2801 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2802 * of this app will be updated to the current time.
2803 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002804 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002805 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2806 == PackageManager.PERMISSION_GRANTED) {
2807 return;
2808 }
2809
2810 if (callingPkg == null) {
2811 throw new SecurityException("Calling package name is null.");
2812 }
2813
2814 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2815 final int uid = mDeps.getCallingUid();
2816 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2817 callingPkg, callingAttributionTag, null /* message */);
2818
2819 if (mode == AppOpsManager.MODE_ALLOWED) {
2820 return;
2821 }
2822
2823 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2824 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2825 return;
2826 }
2827
2828 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2829 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2830 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002831 }
2832
Charles He9369e612017-05-15 17:07:18 +01002833 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002834 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002835 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002836 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002837 }
2838
paulhu8e96a752019-08-12 16:25:11 +08002839 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002840 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002841 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002842 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002843 }
2844
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002845 private void enforceNetworkFactoryOrSettingsPermission() {
2846 enforceAnyPermissionOf(
2847 android.Manifest.permission.NETWORK_SETTINGS,
2848 android.Manifest.permission.NETWORK_FACTORY,
2849 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2850 }
2851
2852 private void enforceNetworkFactoryOrTestNetworksPermission() {
2853 enforceAnyPermissionOf(
2854 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2855 android.Manifest.permission.NETWORK_FACTORY,
2856 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2857 }
2858
Chalard Jean9a396cc2018-02-21 18:43:54 +09002859 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002860 return checkAnyPermissionOf(
2861 android.Manifest.permission.NETWORK_SETTINGS,
2862 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002863 }
2864
2865 private boolean checkSettingsPermission(int pid, int uid) {
2866 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002867 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2868 || PERMISSION_GRANTED == mContext.checkPermission(
2869 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002870 }
2871
paulhu8e96a752019-08-12 16:25:11 +08002872 private void enforceNetworkStackOrSettingsPermission() {
2873 enforceAnyPermissionOf(
2874 android.Manifest.permission.NETWORK_SETTINGS,
2875 android.Manifest.permission.NETWORK_STACK,
2876 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2877 }
2878
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002879 private void enforceNetworkStackSettingsOrSetup() {
2880 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002881 android.Manifest.permission.NETWORK_SETTINGS,
2882 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002883 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002884 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002885 }
2886
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002887 private void enforceAirplaneModePermission() {
2888 enforceAnyPermissionOf(
2889 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2890 android.Manifest.permission.NETWORK_SETTINGS,
2891 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2892 android.Manifest.permission.NETWORK_STACK,
2893 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2894 }
2895
James Mattis8378aec2021-01-26 14:05:36 -08002896 private void enforceOemNetworkPreferencesPermission() {
2897 mContext.enforceCallingOrSelfPermission(
2898 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2899 "ConnectivityService");
2900 }
2901
James Mattisfa270db2021-05-31 17:11:10 -07002902 private void enforceManageTestNetworksPermission() {
2903 mContext.enforceCallingOrSelfPermission(
2904 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2905 "ConnectivityService");
2906 }
2907
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002908 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002909 return checkAnyPermissionOf(
2910 android.Manifest.permission.NETWORK_STACK,
2911 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002912 }
2913
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002914 private boolean checkNetworkStackPermission(int pid, int uid) {
2915 return checkAnyPermissionOf(pid, uid,
2916 android.Manifest.permission.NETWORK_STACK,
2917 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2918 }
2919
paulhu1a407652019-03-22 16:35:06 +08002920 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2921 return checkAnyPermissionOf(pid, uid,
2922 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002923 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2924 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002925 }
2926
Hugo Benichibd0cc762016-07-19 15:59:27 +09002927 private void enforceConnectivityRestrictedNetworksPermission() {
2928 try {
2929 mContext.enforceCallingOrSelfPermission(
2930 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2931 "ConnectivityService");
2932 return;
2933 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002934 // TODO: Remove this fallback check after all apps have declared
2935 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2936 mContext.enforceCallingOrSelfPermission(
2937 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2938 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002939 }
2940
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002941 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002942 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002943 }
2944
Roshan Pius98f59ec2021-02-23 08:47:39 -08002945 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2946 return PERMISSION_GRANTED == mContext.checkPermission(
2947 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2948 }
2949
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002950 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002951 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002952 }
2953
2954 private void sendInetConditionBroadcast(NetworkInfo info) {
2955 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2956 }
2957
Wink Saville4f0de1e2011-08-04 15:01:58 -07002958 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002959 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002960 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002961 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002962 if (info.isFailover()) {
2963 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2964 info.setFailover(false);
2965 }
2966 if (info.getReason() != null) {
2967 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2968 }
2969 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002970 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2971 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002972 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002973 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002974 return intent;
2975 }
2976
2977 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2978 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2979 }
2980
Chiachang Wang3bc52762021-11-25 14:17:57 +08002981 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2982 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002983 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002984 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002985 if (!mSystemReady
2986 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002987 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002988 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002989 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002990 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002991 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002992 }
2993
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002994 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002995 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002996 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002997 final NetworkInfo ni = intent.getParcelableExtra(
2998 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002999 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3000 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
3001 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003002 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003003 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003004 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003005 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003006 } finally {
3007 Binder.restoreCallingIdentity(ident);
3008 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003009 }
3010 }
3011
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003012 /**
Aaron Huang96011892020-06-27 07:18:23 +08003013 * Called by SystemServer through ConnectivityManager when the system is ready.
3014 */
3015 @Override
3016 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003017 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003018 throw new SecurityException("Calling Uid is not system uid.");
3019 }
3020 systemReadyInternal();
3021 }
3022
3023 /**
3024 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003025 */
3026 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003027 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003028 // Load flags after PackageManager is ready to query module version
3029 mFlags.loadFlags(mDeps, mContext);
3030
Aaron Huang9a57acf2020-12-08 10:03:29 +08003031 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3032 // listening network request which is sent by MultipathPolicyTracker won't be added
3033 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3034 // be called after PermissionMonitor#startMonitoring().
3035 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3036 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3037 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003038 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003039 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003040 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003041
Hugo Benichie5220992017-04-26 14:53:28 +09003042 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003043 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003044 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003045 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003046 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003047 }
3048 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003049
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003050 // Create network requests for always-on networks.
3051 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003052
3053 // Update mobile data preference if necessary.
3054 // Note that empty uid list can be skip here only because no uid rules applied before system
3055 // ready. Normally, the empty uid list means to clear the uids rules on netd.
3056 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3057 updateMobileDataPreferredUids();
3058 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003059 }
3060
The Android Open Source Project28527d22009-03-03 19:31:44 -08003061 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003062 * Start listening for default data network activity state changes.
3063 */
3064 @Override
3065 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003066 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003067 }
3068
3069 /**
3070 * Stop listening for default data network activity state changes.
3071 */
3072 @Override
3073 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003074 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003075 }
3076
3077 /**
3078 * Check whether the default network radio is currently active.
3079 */
3080 @Override
3081 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003082 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003083 }
3084
3085 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003086 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003087 * and set it on it's iface.
3088 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003089 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3090 final String iface = newLp.getInterfaceName();
3091 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003092 if (oldLp == null && mtu == 0) {
3093 // Silently ignore unset MTU value.
3094 return;
3095 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003096 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3097 if (VDBG) log("identical MTU - not setting");
3098 return;
3099 }
paulhucbbc3db2019-03-08 16:35:20 +08003100 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003101 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003102 return;
3103 }
sy.yun4aa73922013-09-02 05:24:09 +09003104
w19976e714f1d2014-08-05 15:18:11 -07003105 // Cannot set MTU without interface name
3106 if (TextUtils.isEmpty(iface)) {
3107 loge("Setting MTU size with null iface.");
3108 return;
3109 }
3110
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003111 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003112 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003113 mNetd.interfaceSetMtu(iface, mtu);
3114 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003115 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003116 }
3117 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003118
Chenbo Feng15416292018-11-08 17:36:21 -08003119 @VisibleForTesting
3120 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003121
lucaslin821c9782018-11-28 19:27:52 +08003122 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003123 String[] values = null;
3124 if (tcpBufferSizes != null) {
3125 values = tcpBufferSizes.split(",");
3126 }
3127
3128 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003129 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003130 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3131 values = tcpBufferSizes.split(",");
3132 }
3133
3134 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3135
3136 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003137 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003138
Chenbo Feng15416292018-11-08 17:36:21 -08003139 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3140 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3141 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003142 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003143 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003144 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003145 }
3146 }
3147
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003148 @Override
3149 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003150 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003151 NETWORK_RESTORE_DELAY_PROP_NAME);
3152 if(restoreDefaultNetworkDelayStr != null &&
3153 restoreDefaultNetworkDelayStr.length() != 0) {
3154 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003155 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003156 } catch (NumberFormatException e) {
3157 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003158 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003159 // if the system property isn't set, use the value for the apn type
3160 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3161
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003162 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3163 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003164 }
3165 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003166 }
3167
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003168 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
3169 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
3170 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003171 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003172 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003173 // Start gathering diagnostic information.
3174 netDiags.add(new NetworkDiagnostics(
3175 nai.network,
3176 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003177 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003178 DIAG_TIME_MS));
3179 }
3180
3181 for (NetworkDiagnostics netDiag : netDiags) {
3182 pw.println();
3183 netDiag.waitForMeasurements();
3184 netDiag.dump(pw);
3185 }
3186 }
3187
The Android Open Source Project28527d22009-03-03 19:31:44 -08003188 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003189 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3190 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003191 if (!checkDumpPermission(mContext, TAG, writer)) return;
3192
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003193 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003194 }
3195
lucaslin99473f62020-12-10 15:10:54 +08003196 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3197 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3198 != PackageManager.PERMISSION_GRANTED) {
3199 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003200 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003201 + " due to missing android.permission.DUMP permission");
3202 return false;
3203 } else {
3204 return true;
3205 }
3206 }
3207
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003208 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003209 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003210
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003211 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003212 dumpNetworkDiagnostics(pw);
3213 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003214 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003215 dumpNetworks(pw);
3216 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003217 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003218 dumpNetworkRequests(pw);
3219 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003220 }
Erik Kline9647f382015-06-05 17:47:34 +09003221
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003222 pw.print("NetworkProviders for:");
3223 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3224 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003225 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003226 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003227 pw.println();
3228
Chalard Jean5b409c72021-02-04 13:12:59 +09003229 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003230 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003231 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003232 pw.println("none");
3233 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003234 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003235 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003236 pw.println();
3237
James Mattis8b298a02021-06-01 22:34:04 -07003238 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003239 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003240 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003241 pw.decreaseIndent();
3242 pw.println();
3243
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003244 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003245 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003246 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003247 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003248 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003249
junyulaif2c67e42018-08-07 19:50:45 +08003250 pw.println("Status for known UIDs:");
3251 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003252 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003253 for (int i = 0; i < size; i++) {
3254 // Don't crash if the array is modified while dumping in bugreports.
3255 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003256 final int uid = mUidBlockedReasons.keyAt(i);
3257 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3258 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003259 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003260 } catch (ArrayIndexOutOfBoundsException e) {
3261 pw.println(" ArrayIndexOutOfBoundsException");
3262 } catch (ConcurrentModificationException e) {
3263 pw.println(" ConcurrentModificationException");
3264 }
3265 }
3266 pw.println();
3267 pw.decreaseIndent();
3268
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003269 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003270 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003271 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003272 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003273 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003274
Robert Greenwalt94e22142014-07-30 16:31:24 -07003275 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003276
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003277 pw.println();
markchien5e866652019-09-30 14:40:57 +08003278 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003279
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003280 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003281 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003282
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003283 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003284
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003285 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003286 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003287 pw.println("mNetworkRequestInfoLogs (most recent first):");
3288 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003289 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003290 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003291
3292 pw.println();
3293 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3294 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003295 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003296 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003297
3298 pw.println();
3299 pw.println("NetTransition WakeLock activity (most recent first):");
3300 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003301 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3302 pw.println("total releases: " + mTotalWakelockReleases);
3303 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3304 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3305 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3306 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3307 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3308 }
James Mattiscb1e0362021-04-06 17:07:42 -07003309 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003310
3311 pw.println();
3312 pw.println("bandwidth update requests (by uid):");
3313 pw.increaseIndent();
3314 synchronized (mBandwidthRequests) {
3315 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3316 pw.println("[" + mBandwidthRequests.keyAt(i)
3317 + "]: " + mBandwidthRequests.valueAt(i));
3318 }
3319 }
3320 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003321 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003322
James Mattiscb1e0362021-04-06 17:07:42 -07003323 pw.println();
3324 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3325 pw.increaseIndent();
3326 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003327 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003328 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003329
3330 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003331
3332 pw.println();
3333 pw.println("Permission Monitor:");
3334 pw.increaseIndent();
3335 mPermissionMonitor.dump(pw);
3336 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003337
3338 pw.println();
3339 pw.println("Legacy network activity:");
3340 pw.increaseIndent();
3341 mNetworkActivityTracker.dump(pw);
3342 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003343 }
3344
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003345 private void dumpNetworks(IndentingPrintWriter pw) {
3346 for (NetworkAgentInfo nai : networksSortedById()) {
3347 pw.println(nai.toString());
3348 pw.increaseIndent();
3349 pw.println(String.format(
3350 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3351 nai.numForegroundNetworkRequests(),
3352 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3353 nai.numBackgroundNetworkRequests(),
3354 nai.numNetworkRequests()));
3355 pw.increaseIndent();
3356 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3357 pw.println(nai.requestAt(i).toString());
3358 }
3359 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003360 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003361 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003362 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003363 pw.decreaseIndent();
3364 pw.decreaseIndent();
3365 }
3366 }
3367
James Mattis8b298a02021-06-01 22:34:04 -07003368 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3369 if (!mProfileNetworkPreferences.isEmpty()) {
3370 pw.println("Profile preferences:");
3371 pw.increaseIndent();
3372 pw.println(mProfileNetworkPreferences.preferences);
3373 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003374 }
James Mattis8b298a02021-06-01 22:34:04 -07003375 if (!mOemNetworkPreferences.isEmpty()) {
3376 pw.println("OEM preferences:");
3377 pw.increaseIndent();
3378 pw.println(mOemNetworkPreferences);
3379 pw.decreaseIndent();
3380 }
3381 if (!mMobileDataPreferredUids.isEmpty()) {
3382 pw.println("Mobile data preferred UIDs:");
3383 pw.increaseIndent();
3384 pw.println(mMobileDataPreferredUids);
3385 pw.decreaseIndent();
3386 }
James Mattis45d81842021-01-10 14:24:24 -08003387
James Mattis8b298a02021-06-01 22:34:04 -07003388 pw.println("Default requests:");
3389 pw.increaseIndent();
3390 dumpPerAppDefaultRequests(pw);
3391 pw.decreaseIndent();
3392 }
3393
3394 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003395 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3396 if (mDefaultRequest == defaultRequest) {
3397 continue;
3398 }
3399
James Mattis8b298a02021-06-01 22:34:04 -07003400 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3401 final String networkOutput;
3402 if (null == satisfier) {
3403 networkOutput = "null";
3404 } else if (mNoServiceNetwork.equals(satisfier)) {
3405 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003406 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003407 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003408 }
James Mattis8b298a02021-06-01 22:34:04 -07003409 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3410 ? "" : " asUid: " + defaultRequest.mAsUid;
3411 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3412 + defaultRequest.mPid + asUidString + "]";
3413 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3414 + " Preference order: " + defaultRequest.mPreferenceOrder
3415 + " Tracked UIDs: " + defaultRequest.getUids();
3416 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003417 }
3418 }
3419
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003420 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003421 NetworkRequestInfo[] infos = null;
3422 while (infos == null) {
3423 try {
3424 infos = requestsSortedById();
3425 } catch (ConcurrentModificationException e) {
3426 // mNetworkRequests should only be accessed from handler thread, except dump().
3427 // As dump() is never called in normal usage, it would be needlessly expensive
3428 // to lock the collection only for its benefit. Instead, retry getting the
3429 // requests if ConcurrentModificationException is thrown during dump().
3430 }
3431 }
3432 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003433 pw.println(nri.toString());
3434 }
3435 }
3436
Chalard Jean524f0b12021-10-25 21:11:56 +09003437 private void dumpAllRequestInfoLogsToLogcat() {
3438 try (PrintWriter logPw = new PrintWriter(new Writer() {
3439 @Override
3440 public void write(final char[] cbuf, final int off, final int len) {
3441 // This method is called with 0-length and 1-length arrays for empty strings
3442 // or strings containing only the DEL character.
3443 if (len <= 1) return;
3444 Log.e(TAG, new String(cbuf, off, len));
3445 }
3446 @Override public void flush() {}
3447 @Override public void close() {}
3448 })) {
3449 mNetworkRequestInfoLogs.dump(logPw);
3450 }
3451 }
3452
Hugo Benichia480ba52018-09-03 08:19:02 +09003453 /**
3454 * Return an array of all current NetworkAgentInfos sorted by network id.
3455 */
3456 private NetworkAgentInfo[] networksSortedById() {
3457 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003458 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003459 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003460 return networks;
3461 }
3462
3463 /**
3464 * Return an array of all current NetworkRequest sorted by request id.
3465 */
James Mattis258ea3c2020-11-15 15:04:40 -08003466 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003467 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003468 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003469 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003470 // Sort the array based off the NRI containing the min requestId in its requests.
3471 Arrays.sort(requests,
3472 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3473 Comparator.comparingInt(req -> req.requestId)).requestId
3474 )
3475 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003476 return requests;
3477 }
3478
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003479 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003480 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003481 if (officialNai != null && officialNai.equals(nai)) return true;
3482 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003483 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003484 " - " + nai);
3485 }
3486 return false;
3487 }
3488
Robert Greenwalt2034b912009-08-12 16:08:25 -07003489 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003490 private class NetworkStateTrackerHandler extends Handler {
3491 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003492 super(looper);
3493 }
3494
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003495 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003496 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3497 final NetworkAgentInfo nai = arg.first;
3498 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003499 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003500 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003501 }
3502 return;
3503 }
3504
3505 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003506 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean15228572022-01-28 19:29:12 +09003507 final NetworkCapabilities networkCapabilities = new NetworkCapabilities(
3508 (NetworkCapabilities) arg.second);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003509 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003510 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003511 break;
3512 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003513 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003514 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003515 processLinkPropertiesFromAgent(nai, newLp);
3516 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003517 break;
3518 }
3519 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003520 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003521 updateNetworkInfo(nai, info);
3522 break;
3523 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003524 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003525 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003526 break;
3527 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003528 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003529 if (nai.everConnected) {
3530 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003531 // Note that if the NAI had been connected, this would affect the
3532 // score, and therefore would require re-mixing the score and performing
3533 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003534 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003535 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3536 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003537 // Mark the network as temporarily accepting partial connectivity so that it
3538 // will be validated (and possibly become default) even if it only provides
3539 // partial internet access. Note that if user connects to partial connectivity
3540 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3541 // out of wifi coverage) and if the same wifi is available again, the device
3542 // will auto connect to this wifi even though the wifi has "no internet".
3543 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003544 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003545 break;
3546 }
junyulai011b1f12019-01-03 18:50:15 +08003547 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003548 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003549 break;
3550 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003551 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003552 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003553 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003554
3555 if (isLegacyLockdownNai(nai)
3556 && (underlying == null || underlying.size() != 1)) {
3557 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3558 + " must have exactly one underlying network: " + underlying);
3559 }
3560
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003561 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3562 nai.declaredUnderlyingNetworks = (underlying != null)
3563 ? underlying.toArray(new Network[0]) : null;
3564
3565 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3566 if (DBG) {
3567 log(nai.toShortString() + " changed underlying networks to "
3568 + Arrays.toString(nai.declaredUnderlyingNetworks));
3569 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003570 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003571 notifyIfacesChangedForNetworkStats();
3572 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003573 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003574 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003575 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3576 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3577 nai.teardownDelayMs = msg.arg1;
3578 } else {
3579 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3580 }
Chalard Jean550b5212021-03-05 23:07:53 +09003581 break;
3582 }
3583 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3584 nai.setLingerDuration((int) arg.second);
3585 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003586 }
Tyler Wear72388212021-09-09 14:49:02 -07003587 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3588 DscpPolicy policy = (DscpPolicy) arg.second;
3589 if (mDscpPolicyTracker != null) {
3590 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3591 }
3592 break;
3593 }
3594 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3595 if (mDscpPolicyTracker != null) {
3596 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3597 }
3598 break;
3599 }
3600 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3601 if (mDscpPolicyTracker != null) {
3602 mDscpPolicyTracker.removeAllDscpPolicies(nai);
3603 }
3604 break;
3605 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003606 }
3607 }
3608
3609 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003610 final int netId = msg.arg2;
3611 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003612 switch (msg.what) {
3613 default:
3614 return false;
lucasline117e2e2019-10-22 18:27:33 +08003615 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003616 if (nai == null) {
3617 break;
3618 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003619 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3620 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003621 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003622 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003623 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003624 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003625 if (probePrivateDnsCompleted) {
3626 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3627 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003628 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003629 }
3630 // Only show the notification when the private DNS is broken and the
3631 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003632 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003633 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3634 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003635 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003636 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3637 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3638 // private DNS is broken, it means this network is being reevaluated.
3639 // Either probing private DNS is not necessary any more or it hasn't been
3640 // done yet. In either case, the networkCapabilities should be updated to
3641 // reflect the new status.
3642 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003643 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003644 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003645 }
3646 break;
3647 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003648 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003649 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3650
Erik Kline31b4a9e2018-01-11 21:07:29 +09003651 if (nai == null) break;
3652
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003653 handleNetworkTested(nai, results.mTestResult,
3654 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003655 break;
3656 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003657 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003658 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003659 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003660 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3661 nai.lastCaptivePortalDetected = visible;
3662 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003663 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003664 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3665 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003666 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003667 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003668 teardownUnneededNetwork(nai);
3669 break;
3670 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003671 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003672 }
3673 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003674 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003675 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003676 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3677 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003678 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003679 if (nai == null) {
3680 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3681 break;
3682 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003683 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003684 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003685 (PendingIntent) msg.obj,
3686 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003687 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003688 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003689 break;
3690 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003691 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003692 if (nai == null) break;
3693
Erik Kline9a62f012018-03-21 07:18:33 -07003694 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003695 break;
3696 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003697 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003698 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003699 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003700 break;
3701 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003702 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003703 return true;
3704 }
3705
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003706 private void handleNetworkTested(
3707 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3708 final boolean wasPartial = nai.partialConnectivity;
3709 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3710 final boolean partialConnectivityChanged =
3711 (wasPartial != nai.partialConnectivity);
3712
3713 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3714 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003715 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003716
3717 if (DBG) {
3718 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3719 ? " with redirect to " + redirectUrl
3720 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003721 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003722 }
3723 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003724 final int oldScore = nai.getCurrentScore();
3725 nai.lastValidated = valid;
3726 nai.everValidated |= valid;
3727 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003728 if (valid) {
3729 handleFreshlyValidatedNetwork(nai);
3730 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3731 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003732 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003733 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003734 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003735 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003736 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003737 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003738 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003739 NotificationType.PRIVATE_DNS_BROKEN);
3740 // If network becomes valid, the hasShownBroken should be reset for
3741 // that network so that the notification will be fired when the private
3742 // DNS is broken again.
3743 nai.networkAgentConfig.hasShownBroken = false;
3744 }
3745 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003746 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003747 }
3748 updateInetCondition(nai);
3749 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003750 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003751 nai.onValidationStatusChanged(
3752 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3753 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003754
3755 // If NetworkMonitor detects partial connectivity before
3756 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3757 // immediately. Re-notify partial connectivity silently if no internet
3758 // notification already there.
3759 if (!wasPartial && nai.partialConnectivity) {
3760 // Remove delayed message if there is a pending message.
3761 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3762 handlePromptUnvalidated(nai.network);
3763 }
3764
3765 if (wasValidated && !nai.lastValidated) {
3766 handleNetworkUnvalidated(nai);
3767 }
3768 }
3769
Calvin Ondada1452016-10-11 15:10:46 -07003770 private int getCaptivePortalMode() {
3771 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003772 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3773 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003774 }
3775
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003776 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3777 switch (msg.what) {
3778 default:
3779 return false;
3780 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3781 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3782 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3783 handleLingerComplete(nai);
3784 }
3785 break;
3786 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003787 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3788 handleNetworkAgentRegistered(msg);
3789 break;
3790 }
3791 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3792 handleNetworkAgentDisconnected(msg);
3793 break;
3794 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003795 }
3796 return true;
3797 }
3798
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003799 @Override
3800 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003801 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003802 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003803 maybeHandleNetworkAgentMessage(msg);
3804 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003805 }
3806 }
3807
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003808 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003809 private final int mNetId;
3810 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003811
3812 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003813 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003814 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003815 }
3816
3817 @Override
3818 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3819 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003820 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003821 }
3822
3823 @Override
3824 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003825 // Legacy version of notifyNetworkTestedWithExtras.
3826 // Would only be called if the system has a NetworkStack module older than the
3827 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003828 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003829 }
3830
3831 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003832 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003833 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3834 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003835 final Message msg = mTrackerHandler.obtainMessage(
3836 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003837 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003838 new NetworkTestedResults(
3839 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003840 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003841
3842 // Invoke ConnectivityReport generation for this Network test event.
3843 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3844 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003845
Cody Kestingf1120be2020-08-03 18:01:40 -07003846 // NetworkMonitor reports the network validation result as a bitmask while
3847 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3848 // logical value for ConnectivityDiagnostics.
3849 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3850 p.result);
3851
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003852 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003853 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003854 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3855 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3856
Aaron Huang959d3642021-01-21 15:47:41 +08003857 ConnectivityReportEvent reportEvent =
3858 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3859 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3860 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003861 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003862 }
3863
3864 @Override
3865 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3866 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3867 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003868 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003869 }
3870
3871 @Override
lucasline117e2e2019-10-22 18:27:33 +08003872 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3873 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3874 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003875 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003876 }
3877
3878 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003879 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3880 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3881 EVENT_CAPPORT_DATA_CHANGED,
3882 0, mNetId, data));
3883 }
3884
3885 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003886 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003887 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003888 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003889
3890 final PendingIntent pendingIntent;
3891 // Only the system server can register notifications with package "android"
3892 final long token = Binder.clearCallingIdentity();
3893 try {
paulhu7746e4e2020-06-09 19:07:03 +08003894 pendingIntent = PendingIntent.getBroadcast(
3895 mContext,
3896 0 /* requestCode */,
3897 intent,
3898 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003899 } finally {
3900 Binder.restoreCallingIdentity(token);
3901 }
3902 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3903 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003904 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003905 }
3906
3907 @Override
3908 public void hideProvisioningNotification() {
3909 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003910 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003911 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003912
3913 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003914 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003915 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003916 }
3917
3918 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003919 public int getInterfaceVersion() {
3920 return this.VERSION;
3921 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003922
3923 @Override
3924 public String getInterfaceHash() {
3925 return this.HASH;
3926 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003927 }
3928
Cody Kestingf1120be2020-08-03 18:01:40 -07003929 /**
3930 * Converts the given NetworkMonitor-specific validation result bitmask to a
3931 * ConnectivityDiagnostics-specific validation result int.
3932 */
3933 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3934 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3935 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3936 }
3937 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3938 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3939 }
3940 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3941 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3942 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3943 }
3944
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003945 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003946 log("Data stall detected with methods: " + p.detectionMethod);
3947
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003948 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003949 int detectionMethod = 0;
3950 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3951 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3952 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3953 }
3954 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3955 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3956 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3957 p.tcpMetricsCollectionPeriodMillis);
3958 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003959 }
3960
Cody Kestingf53a0752020-04-15 12:33:28 -07003961 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003962 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003963 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003964
3965 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3966 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3967 // the cost of going through two handlers.
3968 mConnectivityDiagnosticsHandler.sendMessage(msg);
3969 }
3970
Cody Kestingb37958e2020-05-15 10:36:01 -07003971 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3972 return (p.detectionMethod & detectionMethod) != 0;
3973 }
3974
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003975 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3976 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003977 }
3978
Erik Klinea73af002018-06-26 18:53:43 +09003979 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3980 if (nai == null) return;
3981 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3982 // in order to restart a validation pass from within netd.
3983 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3984 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003985 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003986 }
3987 }
3988
Erik Kline31b4a9e2018-01-11 21:07:29 +09003989 private void handlePrivateDnsSettingsChanged() {
3990 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3991
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003992 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003993 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003994 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003995 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3996 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003997 }
3998 }
3999
Erik Kline9a62f012018-03-21 07:18:33 -07004000 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4001 // Private DNS only ever applies to networks that might provide
4002 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004003 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004004
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004005 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004006 // schedule DNS resolutions. If a DNS resolution is required the
4007 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004008 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004009
4010 // With Private DNS bypass support, we can proceed to update the
4011 // Private DNS config immediately, even if we're in strict mode
4012 // and have not yet resolved the provider name into a set of IPs.
4013 updatePrivateDns(nai, cfg);
4014 }
4015
4016 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4017 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004018 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004019 }
4020
dalyk1720e542018-03-05 12:42:22 -05004021 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4022 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4023 if (nai == null) {
4024 return;
4025 }
4026 mDnsManager.updatePrivateDnsValidation(update);
4027 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4028 }
4029
paulhu7c0a2e62021-01-08 00:51:49 +08004030 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004031 int prefixLength) {
4032 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4033 if (nai == null) return;
4034
paulhu7c0a2e62021-01-08 00:51:49 +08004035 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4036 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004037
4038 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004039 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004040 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004041 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004042 prefixLength);
4043 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004044 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004045 return;
4046 }
4047 }
4048
Lorenzo Colittid523d142020-04-01 20:16:30 +09004049 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004050 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4051 }
4052
Hai Shalome58bdc62021-01-11 18:45:34 -08004053 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004054 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004055 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004056 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4057 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4058 }
4059
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004060 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004061 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004062 * @param nai the agent info to update
4063 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004064 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004065 */
junyulai2b6f0c22021-02-03 20:15:30 +08004066 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4067 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4068 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004069 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004070 // one lingered request, set inactive.
4071 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004072 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004073 if (DBG) log("Unsetting inactive " + nai.toShortString());
4074 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004075 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004076 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004077 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004078 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4079 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004080 }
junyulai2b6f0c22021-02-03 20:15:30 +08004081 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004082 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004083 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004084 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004085 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004086 }
4087
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004088 private void handleNetworkAgentRegistered(Message msg) {
4089 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4090 if (!mNetworkAgentInfos.contains(nai)) {
4091 return;
4092 }
4093
4094 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4095 if (VDBG) log("NetworkAgent registered");
4096 } else {
4097 loge("Error connecting NetworkAgent");
4098 mNetworkAgentInfos.remove(nai);
4099 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004100 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004101 synchronized (mNetworkForNetId) {
4102 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004103 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004104 mNetIdManager.releaseNetId(nai.network.getNetId());
4105 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004106 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004107 }
4108 }
4109 }
Paul Jensend5f53392014-11-25 15:26:53 -05004110
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004111 private void handleNetworkAgentDisconnected(Message msg) {
4112 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004113 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004114 }
4115
Chalard Jeand9fffc32018-05-11 20:19:20 +09004116 // Destroys a network, remove references to it from the internal state managed by
4117 // ConnectivityService, free its interfaces and clean up.
4118 // Must be called on the Handler thread.
4119 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004120 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004121
4122 if (!mNetworkAgentInfos.contains(nai)) return;
4123
Chalard Jeand9fffc32018-05-11 20:19:20 +09004124 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004125 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004126 }
lucaslinb25c9a62019-02-12 15:30:13 +08004127 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004128 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004129 // A network agent has disconnected.
4130 // TODO - if we move the logic to the network agent (have them disconnect
4131 // because they lost all their requests or because their score isn't good)
4132 // then they would disconnect organically, report their new state and then
4133 // disconnect the channel.
4134 if (nai.networkInfo.isConnected()) {
4135 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4136 null, null);
4137 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004138 final boolean wasDefault = isDefaultNetwork(nai);
4139 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004140 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004141 }
4142 notifyIfacesChangedForNetworkStats();
4143 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4144 // by other networks that are already connected. Perhaps that can be done by
4145 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4146 // of rematchAllNetworksAndRequests
4147 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004148 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004149
4150 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004151 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4152 // Disable wakeup packet monitoring for each interface.
4153 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4154 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004155 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004156 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004157 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004158 synchronized (mNetworkForNetId) {
4159 // Remove the NetworkAgent, but don't mark the netId as
4160 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004161 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004162 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004163 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004164 // Remove all previously satisfied requests.
4165 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004166 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004167 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004168 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004169 if (currentNetwork != null
4170 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004171 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004172 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4173 // rematch not to keep disconnected agents instead of setting it here ; this
4174 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004175 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004176 for (final NetworkOfferInfo noi : mNetworkOffers) {
4177 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004178 }
James Mattise3ef1912020-12-20 11:09:58 -08004179
Chalard Jean5b409c72021-02-04 13:12:59 +09004180 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004181 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004182 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004183 // network, because while incorrect this is the closest to the old (also
4184 // incorrect) behavior.
4185 mNetworkActivityTracker.updateDataActivityTracking(
4186 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004187 ensureNetworkTransitionWakelock(nai.toShortString());
4188 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004189 }
4190 }
junyulai2b6f0c22021-02-03 20:15:30 +08004191 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004192 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004193 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004194 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004195 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004196 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004197 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004198
4199 // Immediate teardown.
4200 if (nai.teardownDelayMs == 0) {
4201 destroyNetwork(nai);
4202 return;
4203 }
4204
4205 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304206 if (nai.created) {
4207 try {
4208 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4209 } catch (RemoteException e) {
4210 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4211 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004212 }
4213 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4214 }
4215
4216 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004217 if (nai.created) {
4218 // Tell netd to clean up the configuration for this network
4219 // (routing rules, DNS, etc).
4220 // This may be slow as it requires a lot of netd shelling out to ip and
4221 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004222 // after we've rematched networks with requests (which might change the default
4223 // network or service a new request from an app), so network traffic isn't interrupted
4224 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004225 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004226 mDnsManager.removeNetwork(nai.network);
Patrick Rohr2857ac42022-01-21 14:58:16 +01004227
4228 // clean up tc police filters on interface.
4229 if (canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
4230 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4231 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004232 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004233 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004234 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004235 }
4236
Ken Chen6df7a902021-04-09 15:08:42 +08004237 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004238 try {
4239 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004240 final NativeNetworkConfig config;
4241 if (nai.isVPN()) {
4242 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004243 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004244 return false;
4245 }
4246 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4247 INetd.PERMISSION_NONE,
4248 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004249 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004250 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004251 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4252 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004253 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004254 }
Ken Chen6df7a902021-04-09 15:08:42 +08004255 mNetd.networkCreate(config);
4256 mDnsResolver.createNetworkCache(nai.network.getNetId());
4257 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4258 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004259 return true;
4260 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004261 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004262 return false;
4263 }
4264 }
4265
Ken Chen6df7a902021-04-09 15:08:42 +08004266 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004267 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004268 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004269 } catch (RemoteException | ServiceSpecificException e) {
4270 loge("Exception destroying network(networkDestroy): " + e);
4271 }
4272 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004273 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004274 } catch (RemoteException | ServiceSpecificException e) {
4275 loge("Exception destroying network: " + e);
4276 }
4277 }
4278
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004279 // If this method proves to be too slow then we can maintain a separate
4280 // pendingIntent => NetworkRequestInfo map.
4281 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4282 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004283 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4284 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4285 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004286 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004287 return entry.getValue();
4288 }
4289 }
4290 return null;
4291 }
4292
Chalard Jean524f0b12021-10-25 21:11:56 +09004293 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4294 if (SdkLevel.isAtLeastT()) {
4295 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4296 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4297 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4298 // bug is fixed.
4299 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004300 throw new IllegalStateException("This NRI is already registered. New : " + nri
4301 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004302 }
4303 }
4304 }
4305 }
4306
Chalard Jeanac9ace02022-01-26 16:54:05 +09004307 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4308 @NonNull final NetworkCapabilities caps) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004309 if (SdkLevel.isAtLeastT() && mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004310 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4311 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004312 }
4313 return false;
4314 }
4315
James Mattisf7027322020-12-13 16:28:14 -08004316 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004317 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004318 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4319 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4320 final NetworkRequestInfo existingRequest =
4321 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004322 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004323 if (DBG) {
4324 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4325 + nri.mRequests.get(0) + " because their intents matched.");
4326 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004327 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004328 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004329 }
Erik Kline05f2b402015-04-30 12:58:40 +09004330 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004331 }
4332
James Mattisf7027322020-12-13 16:28:14 -08004333 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004334 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004335 }
4336
James Mattis3ce3d3c2021-02-09 18:18:28 -08004337 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004338 ensureRunningOnConnectivityServiceThread();
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004339 NetworkRequest requestToBeReleased = null;
James Mattis45d81842021-01-10 14:24:24 -08004340 for (final NetworkRequestInfo nri : nris) {
4341 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004342 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004343 for (final NetworkRequest req : nri.mRequests) {
4344 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004345 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004346 if (req.isListen()) {
4347 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4348 if (req.networkCapabilities.hasSignalStrength()
4349 && network.satisfiesImmutableCapabilitiesOf(req)) {
4350 updateSignalStrengthThresholds(network, "REGISTER", req);
4351 }
James Mattisf7027322020-12-13 16:28:14 -08004352 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004353 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004354 if (req.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004355 if (!hasCarrierPrivilegeForNetworkCaps(nri.mUid, req.networkCapabilities)
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004356 && !checkConnectivityRestrictedNetworksPermission(
4357 nri.mPid, nri.mUid)) {
4358 requestToBeReleased = req;
4359 }
4360 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004361 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004362
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004363 // If this NRI has a satisfier already, it is replacing an older request that
4364 // has been removed. Track it.
4365 final NetworkRequest activeRequest = nri.getActiveRequest();
4366 if (null != activeRequest) {
4367 // If there is an active request, then for sure there is a satisfier.
4368 nri.getSatisfier().addRequest(activeRequest);
4369 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004370 }
James Mattisf7027322020-12-13 16:28:14 -08004371
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004372 if (requestToBeReleased != null) {
4373 releaseNetworkRequestAndCallOnUnavailable(requestToBeReleased);
4374 return;
4375 }
4376
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004377 if (mFlags.noRematchAllRequestsOnRegister()) {
4378 rematchNetworksAndRequests(nris);
4379 } else {
4380 rematchAllNetworksAndRequests();
4381 }
James Mattis45d81842021-01-10 14:24:24 -08004382
Chalard Jean0354d8c2021-01-12 10:58:56 +09004383 // Requests that have not been matched to a network will not have been sent to the
4384 // providers, because the old satisfier and the new satisfier are the same (null in this
4385 // case). Send these requests to the providers.
4386 for (final NetworkRequestInfo nri : nris) {
4387 for (final NetworkOfferInfo noi : mNetworkOffers) {
4388 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004389 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004390 }
4391 }
4392
James Mattisf7027322020-12-13 16:28:14 -08004393 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4394 final int callingUid) {
4395 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004396 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004397 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4398 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4399 handleReleaseNetworkRequest(
4400 nri.mRequests.get(0),
4401 callingUid,
4402 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004403 }
4404 }
4405
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004406 // Determines whether the network is the best (or could become the best, if it validated), for
4407 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4408 // on the value of reason:
4409 //
4410 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4411 // then it should be torn down.
4412 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4413 // then it should be lingered.
4414 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004415 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004416
4417 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4418 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4419 return false;
4420 }
4421
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004422 final int numRequests;
4423 switch (reason) {
4424 case TEARDOWN:
4425 numRequests = nai.numRequestNetworkRequests();
4426 break;
4427 case LINGER:
4428 numRequests = nai.numForegroundNetworkRequests();
4429 break;
4430 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004431 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004432 return true;
4433 }
4434
Chalard Jean947acd42021-03-08 22:29:27 +09004435 if (numRequests > 0) return false;
4436
Paul Jensende49eb12015-06-25 15:30:08 -04004437 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004438 if (reason == UnneededFor.LINGER
4439 && !nri.isMultilayerRequest()
4440 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004441 // Background requests don't affect lingering.
4442 continue;
4443 }
4444
James Mattis3d229892020-11-16 16:46:28 -08004445 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004446 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004447 }
4448 }
Paul Jensende49eb12015-06-25 15:30:08 -04004449 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004450 }
4451
James Mattis3d229892020-11-16 16:46:28 -08004452 private boolean isNetworkPotentialSatisfier(
4453 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4454 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004455 // request, return immediately. For multilayer requests, check to see if any of the
4456 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004457 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4458 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004459 return false;
4460 }
4461 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004462 // This multilayer listen request is satisfied therefore no further requests need to be
4463 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004464 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004465 return false;
4466 }
James Mattis3d229892020-11-16 16:46:28 -08004467 // As non-multilayer listen requests have already returned, the below would only happen
4468 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004469 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004470 continue;
4471 }
4472 // If this Network is already the highest scoring Network for a request, or if
4473 // there is hope for it to become one if it validated, then it is needed.
4474 if (candidate.satisfies(req)) {
4475 // As soon as a network is found that satisfies a request, return. Specifically for
4476 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4477 // is important so as to not evaluate lower priority requests further in
4478 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004479 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4480 ? nri.getSatisfier() : null;
4481 // Note that this catches two important cases:
4482 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4483 // is currently satisfying the request. This is desirable when
4484 // cellular ends up validating but WiFi does not.
4485 // 2. Unvalidated WiFi will not be reaped when validated cellular
4486 // is currently satisfying the request. This is desirable when
4487 // WiFi ends up validating and out scoring cellular.
4488 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004489 }
4490 }
4491
4492 return false;
4493 }
4494
Erik Kline0c04b742016-07-07 16:50:58 +09004495 private NetworkRequestInfo getNriForAppRequest(
4496 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004497 // Looking up the app passed param request in mRequests isn't possible since it may return
4498 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4499 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004500 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4501 // to avoid potential race conditions when validating a package->uid mapping when sending
4502 // the callback on the very low-chance that an application shuts down prior to the callback
4503 // being sent.
4504 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4505 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004506
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004507 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004508 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004509 log(String.format("UID %d attempted to %s for unowned request %s",
4510 callingUid, requestedOperation, nri));
4511 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004512 }
Erik Kline0c04b742016-07-07 16:50:58 +09004513 }
4514
4515 return nri;
4516 }
4517
James Mattisf7027322020-12-13 16:28:14 -08004518 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4519 final String callingMethod) {
4520 if (nri.isMultilayerRequest()) {
4521 throw new IllegalStateException(
4522 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004523 }
4524 }
4525
James Mattisf7027322020-12-13 16:28:14 -08004526 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004527 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004528 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4529 // single NetworkRequest and thus does not apply to multilayer requests.
4530 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4531 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004532 return;
4533 }
James Mattis2516da32021-01-31 17:06:19 -08004534 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004535 return;
4536 }
James Mattisf7027322020-12-13 16:28:14 -08004537 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4538 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004539 }
4540 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004541 callCallbackForRequest(
4542 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004543 }
4544
James Mattisf7027322020-12-13 16:28:14 -08004545 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4546 final int callingUid,
4547 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004548 final NetworkRequestInfo nri =
4549 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4550 if (nri == null) {
4551 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004552 }
James Mattisf7027322020-12-13 16:28:14 -08004553 if (VDBG || (DBG && request.isRequest())) {
4554 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004555 }
4556 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004557 if (callOnUnavailable) {
4558 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4559 }
Erik Kline155a59a2015-11-25 12:49:38 +09004560 }
Erik Kline0c04b742016-07-07 16:50:58 +09004561
James Mattisa076c532020-12-02 14:12:41 -08004562 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004563 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004564 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004565 if (null == mNetworkRequests.remove(req)) {
4566 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4567 continue;
4568 }
James Mattisa076c532020-12-02 14:12:41 -08004569 if (req.isListen()) {
4570 removeListenRequestFromNetworks(req);
4571 }
4572 }
James Mattis8f036802021-06-20 16:26:01 -07004573 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004574 if (mDefaultNetworkRequests.remove(nri)) {
4575 // If this request was one of the defaults, then the UID rules need to be updated
4576 // WARNING : if the app(s) for which this network request is the default are doing
4577 // traffic, this will kill their connected sockets, even if an equivalent request
4578 // is going to be reinstated right away ; unconnected traffic will go on the default
4579 // until the new default is set, which will happen very soon.
4580 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4581 // remove ranges for those requests that won't have a replacement
4582 final NetworkAgentInfo satisfier = nri.getSatisfier();
4583 if (null != satisfier) {
4584 try {
paulhu0e79d952021-06-09 16:11:35 +08004585 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4586 satisfier.network.getNetId(),
4587 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004588 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004589 } catch (RemoteException e) {
4590 loge("Exception setting network preference default network", e);
4591 }
4592 }
4593 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004594 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004595 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004596 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004597
4598 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004599 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004600 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004601 }
4602 }
4603
Chalard Jean0354d8c2021-01-12 10:58:56 +09004604 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4605 // needed for this offer.
4606 for (final NetworkOfferInfo noi : mNetworkOffers) {
4607 for (final NetworkRequest req : nri.mRequests) {
4608 if (req.isRequest() && noi.offer.neededFor(req)) {
4609 noi.offer.onNetworkUnneeded(req);
4610 }
4611 }
4612 }
James Mattisa076c532020-12-02 14:12:41 -08004613 }
4614
James Mattis3ce3d3c2021-02-09 18:18:28 -08004615 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4616 for (final NetworkRequestInfo nri : nris) {
4617 if (mDefaultRequest == nri) {
4618 // Make sure we never remove the default request.
4619 continue;
4620 }
4621 handleRemoveNetworkRequest(nri);
4622 }
4623 }
4624
James Mattisa076c532020-12-02 14:12:41 -08004625 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4626 // listens don't have a singular affected Network. Check all networks to see
4627 // if this listen request applies and remove it.
4628 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4629 nai.removeRequest(req.requestId);
4630 if (req.networkCapabilities.hasSignalStrength()
4631 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4632 updateSignalStrengthThresholds(nai, "RELEASE", req);
4633 }
4634 }
4635 }
4636
4637 /**
4638 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4639 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4640 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4641 */
4642 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4643 boolean wasKept = false;
4644 final NetworkAgentInfo nai = nri.getSatisfier();
4645 if (nai != null) {
4646 final int requestLegacyType = nri.getActiveRequest().legacyType;
4647 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4648 nai.removeRequest(nri.getActiveRequest().requestId);
4649 if (VDBG || DDBG) {
4650 log(" Removing from current network " + nai.toShortString()
4651 + ", leaving " + nai.numNetworkRequests() + " requests.");
4652 }
4653 // If there are still lingered requests on this network, don't tear it down,
4654 // but resume lingering instead.
4655 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004656 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004657 notifyNetworkLosing(nai, now);
4658 }
4659 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4660 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4661 teardownUnneededNetwork(nai);
4662 } else {
4663 wasKept = true;
4664 }
James Mattisa076c532020-12-02 14:12:41 -08004665 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4666 // Went from foreground to background.
4667 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004668 }
4669
Erik Kline0c04b742016-07-07 16:50:58 +09004670 // Maintain the illusion. When this request arrived, we might have pretended
4671 // that a network connected to serve it, even though the network was already
4672 // connected. Now that this request has gone away, we might have to pretend
4673 // that the network disconnected. LegacyTypeTracker will generate that
4674 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004675 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004676 boolean doRemove = true;
4677 if (wasKept) {
4678 // check if any of the remaining requests for this network are for the
4679 // same legacy type - if so, don't remove the nai
4680 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4681 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004682 if (otherRequest.legacyType == requestLegacyType
4683 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004684 if (DBG) log(" still have other legacy request - leaving");
4685 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004686 }
4687 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004688 }
4689
Erik Kline0c04b742016-07-07 16:50:58 +09004690 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004691 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004692 }
4693 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004694 }
4695 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004696
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004697 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4698 return checkAnyPermissionOf(
4699 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4700 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4701 }
4702
Lorenzo Colittid6459092016-07-04 12:55:44 +09004703 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004704 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004705 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004707 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004708 }
4709
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004710 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004711 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4712 enforceNetworkStackSettingsOrSetup();
4713 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4714 encodeBool(accept), encodeBool(always), network));
4715 }
4716
4717 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004718 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004719 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4721 }
4722
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004723 @Override
4724 public void setTestAllowBadWifiUntil(long timeMs) {
4725 enforceSettingsPermission();
4726 if (!Build.isDebuggable()) {
4727 throw new IllegalStateException("Does not support in non-debuggable build");
4728 }
4729
4730 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4731 throw new IllegalArgumentException("It should not exceed "
4732 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4733 }
4734
4735 mHandler.sendMessage(
4736 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4737 }
4738
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004739 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4740 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4741 " accept=" + accept + " always=" + always);
4742
4743 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4744 if (nai == null) {
4745 // Nothing to do.
4746 return;
4747 }
4748
4749 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004750 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004751 return;
4752 }
4753
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004754 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004755 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004756 }
4757
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004758 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4759 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004760 // If network becomes partial connectivity and user already accepted to use this
4761 // network, we should respect the user's option and don't need to popup the
4762 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004763 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004764 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004765 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004766 }
4767
4768 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004769 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004770 }
4771
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004772 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004773 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004774 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004775 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004776 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004777 }
4778
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004779 }
4780
lucaslin2240ef62019-03-12 13:08:03 +08004781 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4782 boolean always) {
4783 if (DBG) {
4784 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4785 + " always=" + always);
4786 }
4787
4788 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4789 if (nai == null) {
4790 // Nothing to do.
4791 return;
4792 }
4793
4794 if (nai.lastValidated) {
4795 // The network validated while the dialog box was up. Take no action.
4796 return;
4797 }
4798
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004799 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4800 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004801 }
4802
4803 // TODO: Use the current design or save the user choice into IpMemoryStore.
4804 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004805 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004806 }
4807
4808 if (!accept) {
4809 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004810 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004811 // Tear down the network.
4812 teardownUnneededNetwork(nai);
4813 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004814 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4815 // result in a partial connectivity result which will be processed by
4816 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004817 //
4818 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4819 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004820 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004821 }
4822 }
4823
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004824 private void handleSetAvoidUnvalidated(Network network) {
4825 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4826 if (nai == null || nai.lastValidated) {
4827 // Nothing to do. The network either disconnected or revalidated.
4828 return;
4829 }
4830 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004831 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004832 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004833 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004834 }
4835 }
4836
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004837 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004838 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004839 mHandler.sendMessageDelayed(
4840 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4841 PROMPT_UNVALIDATED_DELAY_MS);
4842 }
4843
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004844 @Override
4845 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004846 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004847 mHandler.post(() -> {
4848 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4849 if (nai == null) return;
4850 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004851 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004852 });
4853 }
4854
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004855 /**
4856 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4857 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004858 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004859 * @param appExtras Bundle to use as intent extras for the captive portal application.
4860 * Must be treated as opaque to avoid preventing the captive portal app to
4861 * update its arguments.
4862 */
4863 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004864 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004865 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4866 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004867
4868 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4869 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004870 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4871 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004872 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4873
lucaslin75ff7022020-12-17 04:14:35 +08004874 final long token = Binder.clearCallingIdentity();
4875 try {
4876 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4877 } finally {
4878 Binder.restoreCallingIdentity(token);
4879 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004880 }
4881
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004882 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4883 private final Network mNetwork;
4884
4885 private CaptivePortalImpl(Network network) {
4886 mNetwork = network;
4887 }
4888
4889 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004890 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004891 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4892 enforceSettingsPermission();
4893 }
4894
Chiachang Wang938bfba2020-01-09 13:50:55 +08004895 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004896 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004897 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004898 }
4899
4900 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004901 public void appRequest(final int request) {
4902 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4903 if (nm == null) return;
4904
4905 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004906 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004907 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004908 }
4909 }
4910
4911 @Nullable
4912 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4913 // getNetworkAgentInfoForNetwork is thread-safe
4914 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4915 if (nai == null) return null;
4916
4917 // nai.networkMonitor() is thread-safe
4918 return nai.networkMonitor();
4919 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004920 }
4921
Hugo Benichic9048bc2016-09-14 23:23:08 +00004922 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004923 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004924 }
4925
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004926 /**
4927 * Return whether the device should maintain continuous, working connectivity by switching away
4928 * from WiFi networks having no connectivity.
4929 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4930 */
4931 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004932 if (!checkNetworkStackPermission()) {
4933 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4934 }
4935 return avoidBadWifi();
4936 }
4937
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004938 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004939 ensureRunningOnConnectivityServiceThread();
4940 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004941 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004942 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004943 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004944 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4945 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4946 for (final NetworkOfferInfo noi : offersToUpdate) {
4947 updateOfferScore(noi.offer);
4948 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004949 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004950 }
4951
Erik Kline95ecfee2016-10-02 18:02:14 +09004952 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004953 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004954 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004955 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004956 if (!configRestrict) {
4957 pw.println("Bad Wi-Fi avoidance: unrestricted");
4958 return;
4959 }
4960
4961 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4962 pw.increaseIndent();
4963 pw.println("Config restrict: " + configRestrict);
4964
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004965 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004966 String description;
4967 // Can't use a switch statement because strings are legal case labels, but null is not.
4968 if ("0".equals(value)) {
4969 description = "get stuck";
4970 } else if (value == null) {
4971 description = "prompt";
4972 } else if ("1".equals(value)) {
4973 description = "avoid";
4974 } else {
4975 description = value + " (?)";
4976 }
4977 pw.println("User setting: " + description);
4978 pw.println("Network overrides:");
4979 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004980 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004981 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004982 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004983 }
4984 }
4985 pw.decreaseIndent();
4986 pw.decreaseIndent();
4987 }
4988
paulhu7746e4e2020-06-09 19:07:03 +08004989 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4990 // unify the method.
4991 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4992 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4993 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4994 return settingsComponent != null
4995 ? settingsComponent.getPackageName() : "com.android.settings";
4996 }
4997
lucaslinb1e8e382019-01-24 15:55:30 +08004998 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004999 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005000 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005001 switch (type) {
5002 case NO_INTERNET:
5003 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005004 // High priority because it is only displayed for explicitly selected networks.
5005 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005006 break;
lucasline117e2e2019-10-22 18:27:33 +08005007 case PRIVATE_DNS_BROKEN:
5008 action = Settings.ACTION_WIRELESS_SETTINGS;
5009 // High priority because we should let user know why there is no internet.
5010 highPriority = true;
5011 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005012 case LOST_INTERNET:
5013 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005014 // High priority because it could help the user avoid unexpected data usage.
5015 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005016 break;
lucaslin2240ef62019-03-12 13:08:03 +08005017 case PARTIAL_CONNECTIVITY:
5018 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005019 // Don't bother the user with a high-priority notification if the network was not
5020 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005021 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005022 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005023 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005024 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005025 return;
5026 }
5027
5028 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005029 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005030 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005031 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005032 // Some OEMs have their own Settings package. Thus, need to get the current using
5033 // Settings package name instead of just use default name "com.android.settings".
5034 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5035 intent.setClassName(settingsPkgName,
5036 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005037 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005038
paulhu2af50222020-10-11 22:52:27 +08005039 PendingIntent pendingIntent = PendingIntent.getActivity(
5040 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005041 0 /* requestCode */,
5042 intent,
paulhu2af50222020-10-11 22:52:27 +08005043 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005044
Serik Beketayevec8ad212020-12-07 22:43:07 -08005045 mNotifier.showNotification(
5046 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005047 }
5048
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005049 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5050 // Don't prompt if the network is validated, and don't prompt on captive portals
5051 // because we're already prompting the user to sign in.
5052 if (nai.everValidated || nai.everCaptivePortalDetected) {
5053 return false;
5054 }
5055
5056 // If a network has partial connectivity, always prompt unless the user has already accepted
5057 // partial connectivity and selected don't ask again. This ensures that if the device
5058 // automatically connects to a network that has partial Internet access, the user will
5059 // always be able to use it, either because they've already chosen "don't ask again" or
5060 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005061 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005062 return true;
5063 }
5064
5065 // If a network has no Internet access, only prompt if the network was explicitly selected
5066 // and if the user has not already told us to use the network regardless of whether it
5067 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005068 if (nai.networkAgentConfig.explicitlySelected
5069 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005070 return true;
5071 }
5072
5073 return false;
5074 }
5075
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005076 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09005077 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005078 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5079
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005080 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005081 return;
5082 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005083
5084 // Stop automatically reconnecting to this network in the future. Automatically connecting
5085 // to a network that provides no or limited connectivity is not useful, because the user
5086 // cannot use that network except through the notification shown by this method, and the
5087 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005088 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005089
lucaslin2240ef62019-03-12 13:08:03 +08005090 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
5091 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
5092 // popup the notification immediately when the network is partial connectivity.
5093 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08005094 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005095 } else {
5096 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5097 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005098 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005099
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005100 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5101 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005102 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005103
lucaslin2240ef62019-03-12 13:08:03 +08005104 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5105 return;
5106 }
5107
5108 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005109 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005110 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005111 }
5112
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005113 @Override
5114 public int getMultipathPreference(Network network) {
5115 enforceAccessPermission();
5116
5117 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005118 if (nai != null && nai.networkCapabilities
5119 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005120 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5121 }
5122
Aaron Huang9a57acf2020-12-08 10:03:29 +08005123 final NetworkPolicyManager netPolicyManager =
5124 mContext.getSystemService(NetworkPolicyManager.class);
5125
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005126 final long token = Binder.clearCallingIdentity();
5127 final int networkPreference;
5128 try {
5129 networkPreference = netPolicyManager.getMultipathPreference(network);
5130 } finally {
5131 Binder.restoreCallingIdentity(token);
5132 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005133 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005134 return networkPreference;
5135 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005136 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5137 }
5138
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005139 @Override
5140 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005141 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005142 }
5143
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005144 private class InternalHandler extends Handler {
5145 public InternalHandler(Looper looper) {
5146 super(looper);
5147 }
5148
5149 @Override
5150 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005151 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005152 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005153 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005154 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005155 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005156 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005157 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005158 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005159 break;
5160 }
Jason Monka69f1b02013-10-10 14:02:51 -04005161 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005162 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5163 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005164 break;
5165 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005166 case EVENT_REGISTER_NETWORK_PROVIDER: {
5167 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005168 break;
5169 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005170 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5171 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005172 break;
5173 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005174 case EVENT_REGISTER_NETWORK_OFFER: {
5175 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5176 break;
5177 }
5178 case EVENT_UNREGISTER_NETWORK_OFFER: {
5179 final NetworkOfferInfo offer =
5180 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5181 if (null != offer) {
5182 handleUnregisterNetworkOffer(offer);
5183 }
5184 break;
5185 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005186 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005187 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5188 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5189 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005190 break;
5191 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005192 case EVENT_REGISTER_NETWORK_REQUEST:
5193 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005194 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005195 break;
5196 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005197 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5198 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005199 handleRegisterNetworkRequestWithIntent(msg);
5200 break;
5201 }
Erik Kline155a59a2015-11-25 12:49:38 +09005202 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5203 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5204 handleTimedOutNetworkRequest(nri);
5205 break;
5206 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005207 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5208 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5209 break;
5210 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005211 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005212 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5213 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005214 break;
5215 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005216 case EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE: {
5217 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5218 /* callOnUnavailable */ true);
5219 break;
5220 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005221 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005222 Network network = (Network) msg.obj;
5223 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005224 break;
5225 }
lucaslin2240ef62019-03-12 13:08:03 +08005226 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5227 Network network = (Network) msg.obj;
5228 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5229 toBool(msg.arg2));
5230 break;
5231 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005232 case EVENT_SET_AVOID_UNVALIDATED: {
5233 handleSetAvoidUnvalidated((Network) msg.obj);
5234 break;
5235 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005236 case EVENT_PROMPT_UNVALIDATED: {
5237 handlePromptUnvalidated((Network) msg.obj);
5238 break;
5239 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005240 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5241 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005242 break;
5243 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005244 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005245 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005246 mKeepaliveTracker.handleStartKeepalive(msg);
5247 break;
5248 }
5249 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005250 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005251 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5252 int slot = msg.arg1;
5253 int reason = msg.arg2;
5254 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5255 break;
5256 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005257 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5258 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5259 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005260 break;
5261 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005262 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5263 handlePrivateDnsSettingsChanged();
5264 break;
dalyk1720e542018-03-05 12:42:22 -05005265 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5266 handlePrivateDnsValidationUpdate(
5267 (PrivateDnsValidationUpdate) msg.obj);
5268 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005269 case EVENT_UID_BLOCKED_REASON_CHANGED:
5270 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005271 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005272 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5273 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5274 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005275 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005276 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5277 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005278 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005279 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005280 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005281 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005282 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5283 IOnCompleteListener> arg =
5284 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5285 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005286 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005287 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005288 }
lucaslin1193a5d2021-01-21 02:04:15 +08005289 case EVENT_REPORT_NETWORK_ACTIVITY:
5290 mNetworkActivityTracker.handleReportNetworkActivity();
5291 break;
paulhu51f77dc2021-06-07 02:34:20 +00005292 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5293 handleMobileDataPreferredUidsChanged();
5294 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005295 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5296 final long timeMs = ((Long) msg.obj).longValue();
5297 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5298 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005299 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5300 handleIngressRateLimitChanged();
5301 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005302 }
5303 }
5304 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005305
Lorenzo Colittid6459092016-07-04 12:55:44 +09005306 @Override
markchien5776f962019-12-16 20:15:20 +08005307 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005308 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005309 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5310 Context.TETHERING_SERVICE);
5311 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005312 }
5313
Lorenzo Colittid6459092016-07-04 12:55:44 +09005314 @Override
markchien5776f962019-12-16 20:15:20 +08005315 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005316 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005317 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5318 Context.TETHERING_SERVICE);
5319 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005320 }
5321
Lorenzo Colittid6459092016-07-04 12:55:44 +09005322 @Override
markchien5776f962019-12-16 20:15:20 +08005323 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005324 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005325 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5326 Context.TETHERING_SERVICE);
5327 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005328 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005329
markchien5776f962019-12-16 20:15:20 +08005330
Lorenzo Colittid6459092016-07-04 12:55:44 +09005331 @Override
markchien5776f962019-12-16 20:15:20 +08005332 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005333 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005334 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5335 Context.TETHERING_SERVICE);
5336
5337 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005338 }
5339
Lorenzo Colittid6459092016-07-04 12:55:44 +09005340 @Override
markchien5776f962019-12-16 20:15:20 +08005341 @Deprecated
5342 public String[] getTetherableUsbRegexs() {
5343 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5344 Context.TETHERING_SERVICE);
5345
5346 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005347 }
5348
Udam Saini8f7d6a72017-06-07 12:06:28 -07005349 @Override
markchien5776f962019-12-16 20:15:20 +08005350 @Deprecated
5351 public String[] getTetherableWifiRegexs() {
5352 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5353 Context.TETHERING_SERVICE);
5354 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005355 }
5356
Robert Greenwalte0b00512014-07-02 09:59:16 -07005357 // Called when we lose the default network and have no replacement yet.
5358 // This will automatically be cleared after X seconds or a new default network
5359 // becomes CONNECTED, whichever happens first. The timer is started by the
5360 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005361 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005362 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005363 if (mNetTransitionWakeLock.isHeld()) {
5364 return;
5365 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005366 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005367 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5368 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005369 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005370 mWakelockLogs.log("ACQUIRE for " + forWhom);
5371 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005372 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005373 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005374 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005375 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005376
Hugo Benichi471b62a2017-03-30 23:18:10 +09005377 // Called when we gain a new default network to release the network transition wakelock in a
5378 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5379 // message is cancelled.
5380 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005381 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005382 if (!mNetTransitionWakeLock.isHeld()) {
5383 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005384 }
5385 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005386 // Cancel self timeout on wakelock hold.
5387 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5388 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5389 mHandler.sendMessageDelayed(msg, 1000);
5390 }
5391
5392 // Called when either message of ensureNetworkTransitionWakelock or
5393 // scheduleReleaseNetworkTransitionWakelock is processed.
5394 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5395 String event = eventName(eventId);
5396 synchronized (this) {
5397 if (!mNetTransitionWakeLock.isHeld()) {
5398 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005399 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005400 return;
5401 }
5402 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005403 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5404 mTotalWakelockDurationMs += lockDuration;
5405 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5406 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005407 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005408 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005409 }
5410
Robert Greenwalt986c7412010-09-08 15:24:47 -07005411 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005412 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005413 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005414 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005415 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005416 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005417 }
5418
Lorenzo Colittid6459092016-07-04 12:55:44 +09005419 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005420 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005421 enforceAccessPermission();
5422 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005423 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005424 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005425
5426 final NetworkAgentInfo nai;
5427 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005428 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005429 } else {
5430 nai = getNetworkAgentInfoForNetwork(network);
5431 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005432
5433 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005434 mHandler.obtainMessage(
5435 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005436 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005437
Hugo Benichid6b510a2017-04-06 17:22:18 +09005438 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005439 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005440 if (nai == null
5441 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005442 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005443 return;
5444 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005445 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005446 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005447 mConnectivityDiagnosticsHandler.sendMessage(
5448 mConnectivityDiagnosticsHandler.obtainMessage(
5449 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5450 new ReportedNetworkConnectivityInfo(
5451 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005452 return;
5453 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005454 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005455 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005456 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005457 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005458 // Validating a network that has not yet connected could result in a call to
5459 // rematchNetworkAndRequests() which is not meant to work on such networks.
5460 if (!nai.everConnected) {
5461 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005462 }
paulhu7aeba372020-12-30 00:42:19 +08005463 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5464 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005465 return;
5466 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005467
5468 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5469 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5470 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5471 // completed.
5472 mConnectivityDiagnosticsHandler.sendMessage(
5473 mConnectivityDiagnosticsHandler.obtainMessage(
5474 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5475 new ReportedNetworkConnectivityInfo(
5476 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005477 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005478 }
5479
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005480 // TODO: call into netd.
5481 private boolean queryUserAccess(int uid, Network network) {
5482 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5483 if (nai == null) return false;
5484
5485 // Any UID can use its default network.
5486 if (nai == getDefaultNetworkForUid(uid)) return true;
5487
5488 // Privileged apps can use any network.
5489 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5490 return true;
5491 }
5492
5493 // An unprivileged UID can use a VPN iff the VPN applies to it.
5494 if (nai.isVPN()) {
5495 return nai.networkCapabilities.appliesToUid(uid);
5496 }
5497
5498 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5499 // sockets, i.e., if it is the owner.
5500 final NetworkAgentInfo vpn = getVpnForUid(uid);
5501 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5502 && uid != vpn.networkCapabilities.getOwnerUid()) {
5503 return false;
5504 }
5505
5506 // The UID's permission must be at least sufficient for the network. Since the restricted
5507 // permission was already checked above, that just leaves background networks.
5508 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5509 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5510 }
5511
5512 // Unrestricted network. Anyone gets to use it.
5513 return true;
5514 }
5515
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005516 /**
5517 * Returns information about the proxy a certain network is using. If given a null network, it
5518 * it will return the proxy for the bound network for the caller app or the default proxy if
5519 * none.
5520 *
5521 * @param network the network we want to get the proxy information for.
5522 * @return Proxy information if a network has a proxy configured, or otherwise null.
5523 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005524 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005525 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005526 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005527 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005528 if (network == null) {
5529 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005530 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005531 true);
5532 if (activeNetwork == null) {
5533 return null;
5534 }
5535 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005536 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005537 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5538 // caller may not have.
5539 return getLinkPropertiesProxyInfo(network);
5540 }
5541 // No proxy info available if the calling UID does not have network access.
5542 return null;
5543 }
5544
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005545
5546 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005547 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5548 if (nai == null) return null;
5549 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005550 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5551 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005552 }
5553 }
5554
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005555 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005556 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005557 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005558 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005559 }
5560
Chalard Jean777e2e52018-06-07 18:02:37 +09005561 @Override
5562 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005563 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005564 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005565 }
5566
Jason Monk4d5e20f2014-04-25 15:00:09 -04005567 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005568 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005569 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005570 proxy = null;
5571 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005572 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005573 }
5574
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005575 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5576 // when any network changes proxy.
5577 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5578 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005579 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005580 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5581 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5582
Chalard Jean7d97afc2018-06-07 17:41:29 +09005583 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005584 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005585 }
5586 }
5587
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005588 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005589 final private HashMap<Uri, Integer> mUriEventMap;
5590 final private Context mContext;
5591 final private Handler mHandler;
5592
5593 SettingsObserver(Context context, Handler handler) {
5594 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005595 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005596 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005597 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005598 }
5599
Erik Kline05f2b402015-04-30 12:58:40 +09005600 void observe(Uri uri, int what) {
5601 mUriEventMap.put(uri, what);
5602 final ContentResolver resolver = mContext.getContentResolver();
5603 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005604 }
5605
5606 @Override
5607 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005608 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005609 }
5610
5611 @Override
5612 public void onChange(boolean selfChange, Uri uri) {
5613 final Integer what = mUriEventMap.get(uri);
5614 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005615 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005616 } else {
5617 loge("No matching event to send for URI=" + uri);
5618 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005619 }
5620 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005621
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005622 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005623 Log.d(TAG, s);
5624 }
5625
5626 private static void logw(String s) {
5627 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005628 }
5629
Daniel Brightf9e945b2020-06-15 16:10:01 -07005630 private static void logwtf(String s) {
5631 Log.wtf(TAG, s);
5632 }
5633
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005634 private static void logwtf(String s, Throwable t) {
5635 Log.wtf(TAG, s, t);
5636 }
5637
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005638 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005639 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005640 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005641
Hugo Benichi39621362017-02-11 17:04:43 +09005642 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005643 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005644 }
5645
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005646 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005647 * Return the information of all ongoing VPNs.
5648 *
5649 * <p>This method is used to update NetworkStatsService.
5650 *
5651 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005652 */
junyulai2050bed2021-01-23 09:46:34 +08005653 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005654 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005655 if (mLockdownEnabled) {
5656 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005657 }
junyulai2050bed2021-01-23 09:46:34 +08005658 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005659 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005660 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005661 if (info != null) {
5662 infoList.add(info);
5663 }
5664 }
junyulai2050bed2021-01-23 09:46:34 +08005665 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005666 }
5667
5668 /**
5669 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005670 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005671 */
junyulai2050bed2021-01-23 09:46:34 +08005672 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005673 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005674 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5675 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005676 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5677 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5678 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005679 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5680 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005681 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005682 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005683 }
5684 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005685
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005686 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005687
5688 List<String> interfaces = new ArrayList<>();
5689 for (Network network : underlyingNetworks) {
5690 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5691 if (underlyingNai == null) continue;
5692 LinkProperties lp = underlyingNai.linkProperties;
5693 for (String iface : lp.getAllInterfaceNames()) {
5694 if (!TextUtils.isEmpty(iface)) {
5695 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005696 }
5697 }
Benedict Wong34857f82019-06-12 17:46:15 +00005698 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005699
5700 if (interfaces.isEmpty()) return null;
5701
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005702 // Must be non-null or NetworkStatsService will crash.
5703 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5704 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005705 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005706 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005707
junyulai2050bed2021-01-23 09:46:34 +08005708 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5709 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005710 }
5711
James Mattisd31bdfa2020-12-23 16:37:26 -08005712 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005713 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5714 Network[] underlyingNetworks) {
5715 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005716 if (underlyingNetworks == null && defaultNetwork != null) {
5717 // null underlying networks means to track the default.
5718 underlyingNetworks = new Network[] { defaultNetwork };
5719 }
5720 return underlyingNetworks;
5721 }
5722
5723 // Returns true iff |network| is an underlying network of |nai|.
5724 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5725 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5726 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005727 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005728 final Network[] underlying = underlyingNetworksOrDefault(
5729 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005730 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005731 }
5732
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005733 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005734 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005735 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005736 * When underlying networks change, such networks may have to update capabilities to reflect
5737 * things like the metered bit, their transports, and so on. The capabilities are calculated
5738 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005739 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005740 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005741 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005742 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005743 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005744 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005745 }
5746 }
5747 }
5748
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005749 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5750 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5751 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5752 // a VPN is not up.
5753 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5754 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5755 for (UidRange range : blockedUidRanges) {
5756 if (range.contains(uid)) return true;
5757 }
5758 return false;
5759 }
5760
5761 @Override
5762 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005763 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005764 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5765 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5766 }
5767
5768 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5769 if (DBG) {
5770 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5771 + Arrays.toString(ranges));
5772 }
5773 // Cannot use a Set since the list of UID ranges might contain duplicates.
5774 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5775 for (int i = 0; i < ranges.length; i++) {
5776 if (requireVpn) {
5777 newVpnBlockedUidRanges.add(ranges[i]);
5778 } else {
5779 newVpnBlockedUidRanges.remove(ranges[i]);
5780 }
5781 }
5782
5783 try {
5784 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5785 } catch (RemoteException | ServiceSpecificException e) {
5786 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5787 + Arrays.toString(ranges) + "): netd command failed: " + e);
5788 }
5789
5790 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5791 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005792 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5793 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005794 }
5795
5796 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5797 }
5798
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005799 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005800 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005801 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005802 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005803 }
5804
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005805 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5806 return mLockdownEnabled
5807 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5808 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005809 }
5810
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005811 private NetworkAgentInfo getLegacyLockdownNai() {
5812 if (!mLockdownEnabled) {
5813 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005814 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005815 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005816 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5817 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005818
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005819 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005820 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5821 // a local variable. There is no need to make a copy because its contents cannot change.
5822 final Network[] underlying = nai.declaredUnderlyingNetworks;
5823 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005824 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005825 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005826
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005827 // The legacy lockdown VPN always uses the default network.
5828 // If the VPN's underlying network is no longer the current default network, it means that
5829 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005830 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5831 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005832 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005833 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005834 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005835 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005836
5837 return nai;
5838 };
5839
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005840 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5841 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5842 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005843 private DetailedState getLegacyLockdownState(DetailedState origState) {
5844 if (origState != DetailedState.CONNECTED) {
5845 return origState;
5846 }
5847 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5848 ? DetailedState.CONNECTING
5849 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005850 }
5851
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005852 private void filterForLegacyLockdown(NetworkInfo ni) {
5853 if (!mLockdownEnabled || !ni.isConnected()) return;
5854 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5855 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5856 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5857 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5858 // network, this time with a state of CONNECTED.
5859 //
5860 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5861 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5862 // is not too far off the truth, since an always-on VPN, when not connected, is always
5863 // trying to reconnect.
5864 if (getLegacyLockdownNai() == null) {
5865 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5866 }
5867 }
5868
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005869 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005870 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005871 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005872 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005873 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5874 return;
5875 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005876 final long ident = Binder.clearCallingIdentity();
5877 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005878 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005879 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005880 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005881 } finally {
5882 Binder.restoreCallingIdentity(ident);
5883 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005884 }
Wink Savillecb117d32013-08-29 14:57:08 -07005885
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005886 @Override
5887 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005888 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005889 final long ident = Binder.clearCallingIdentity();
5890 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005891 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005892 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005893 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5894 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005895 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005896 } finally {
5897 Binder.restoreCallingIdentity(ident);
5898 }
5899 }
5900
James Mattis02220e22021-03-13 19:27:21 -08005901 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005902 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005903 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5904 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5905 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005906 }
5907
James Mattis02220e22021-03-13 19:27:21 -08005908 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005909 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005910 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005911 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005912 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005913 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005914 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5915 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5916 }
junyulaid91e7052020-08-28 13:44:33 +08005917 }
5918
James Mattis02220e22021-03-13 19:27:21 -08005919 private void onPackageChanged(@NonNull final String packageName) {
5920 // This is necessary in case a package is added or removed, but also when it's replaced to
5921 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5922 // as one in the preferences, then it should follow the same routing as that other package,
5923 // which means updating the rules is never to be needed in this case (whether it joins or
5924 // leaves a UID with a preference).
5925 if (isMappedInOemNetworkPreference(packageName)) {
5926 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5927 }
5928 }
5929
5930 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005931 @Override
5932 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005933 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005934 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005935 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005936
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005937 // User should be filled for below intents, check the existence.
5938 if (user == null) {
5939 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5940 return;
5941 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005942
Lorenzo Colitticd675292021-02-04 17:32:07 +09005943 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005944 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005945 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005946 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005947 } else {
junyulaid91e7052020-08-28 13:44:33 +08005948 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005949 }
5950 }
5951 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005952
James Mattis02220e22021-03-13 19:27:21 -08005953 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5954 @Override
5955 public void onReceive(Context context, Intent intent) {
5956 ensureRunningOnConnectivityServiceThread();
5957 switch (intent.getAction()) {
5958 case Intent.ACTION_PACKAGE_ADDED:
5959 case Intent.ACTION_PACKAGE_REMOVED:
5960 case Intent.ACTION_PACKAGE_REPLACED:
5961 onPackageChanged(intent.getData().getSchemeSpecificPart());
5962 break;
5963 default:
5964 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5965 }
5966 }
5967 };
5968
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005969 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005970 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005971
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005972 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005973 public final String name;
5974 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005975 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005976 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005977
lifraf3a3492021-03-10 13:58:14 +08005978 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5979 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005980 this.name = name;
5981 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005982 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005983 mDeathRecipient = deathRecipient;
5984
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005985 if (mDeathRecipient == null) {
5986 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005987 }
5988 }
5989
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005990 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005991 try {
5992 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5993 } catch (RemoteException e) {
5994 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005995 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005996 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005997 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005998
James Mattis4fce5d12020-11-12 15:53:42 -08005999 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6000 for (int i = 0; i < requests.size(); i++) {
6001 ensureNetworkRequestHasType(requests.get(i));
6002 }
6003 }
6004
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006005 private void ensureNetworkRequestHasType(NetworkRequest request) {
6006 if (request.type == NetworkRequest.Type.NONE) {
6007 throw new IllegalArgumentException(
6008 "All NetworkRequests in ConnectivityService must have a type");
6009 }
6010 }
6011
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006012 /**
6013 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006014 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006015 */
James Mattis258ea3c2020-11-15 15:04:40 -08006016 @VisibleForTesting
6017 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006018 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6019 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006020 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006021
James Mattisa076c532020-12-02 14:12:41 -08006022 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6023 void setSatisfier(
6024 @Nullable final NetworkAgentInfo satisfier,
6025 @Nullable final NetworkRequest activeRequest) {
6026 mSatisfier = satisfier;
6027 mActiveRequest = activeRequest;
6028 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006029
James Mattisd31bdfa2020-12-23 16:37:26 -08006030 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006031 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006032 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006033 private NetworkAgentInfo mSatisfier;
6034 NetworkAgentInfo getSatisfier() {
6035 return mSatisfier;
6036 }
6037
6038 // The request in mRequests assigned to a network agent. This is null if none of the
6039 // requests in mRequests can be satisfied. This member has the constraint of only being
6040 // accessible on the handler thread.
6041 @Nullable
6042 private NetworkRequest mActiveRequest;
6043 NetworkRequest getActiveRequest() {
6044 return mActiveRequest;
6045 }
6046
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006047 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006048 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006049 @Nullable
6050 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006051
6052 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006053 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006054 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006055 final int mPid;
6056 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006057 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006058 @Nullable
6059 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006060
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006061 // Counter keeping track of this NRI.
6062 final PerUidCounter mPerUidCounter;
6063
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006064 // Effective UID of this request. This is different from mUid when a privileged process
6065 // files a request on behalf of another UID. This UID is used to determine blocked status,
6066 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6067 // maximum limit of registered callbacks per UID.
6068 final int mAsUid;
6069
paulhu48291862021-07-14 14:53:57 +08006070 // Preference order of this request.
6071 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006072
James Mattis3ce3d3c2021-02-09 18:18:28 -08006073 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6074 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6075 // maintained for keying off of. This is only a concern when the original nri
6076 // mNetworkRequests changes which happens currently for apps that register callbacks to
6077 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6078 // that match the per-app default nri that currently tracks the calling app's uid so that
6079 // callbacks are fired at the appropriate time. When the callbacks fire,
6080 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6081 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6082 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6083 @NonNull
6084 private final NetworkRequest mNetworkRequestForCallback;
6085 NetworkRequest getNetworkRequestForCallback() {
6086 return mNetworkRequestForCallback;
6087 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006088
James Mattisd31bdfa2020-12-23 16:37:26 -08006089 /**
6090 * Get the list of UIDs this nri applies to.
6091 */
6092 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006093 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006094 // networkCapabilities.getUids() returns a defensive copy.
6095 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006096 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6097 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006098 }
6099
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006100 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6101 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006102 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006103 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006104 }
6105
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006106 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006107 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006108 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006109 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006110 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006111 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006112 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006113 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006114 mBinder = null;
6115 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006116 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006117 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006118 mPerUidCounter = getRequestCounter(this);
6119 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006120 /**
6121 * Location sensitive data not included in pending intent. Only included in
6122 * {@link NetworkCallback}.
6123 */
6124 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006125 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006126 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006127 }
6128
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006129 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006130 @Nullable final IBinder binder,
6131 @NetworkCallback.Flag int callbackFlags,
6132 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006133 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6134 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006135 }
6136
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006137 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006138 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006139 @Nullable final IBinder binder,
6140 @NetworkCallback.Flag int callbackFlags,
6141 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006142 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006143 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006144 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006145 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006146 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006147 mBinder = binder;
6148 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006149 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006150 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006151 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006152 mPerUidCounter = getRequestCounter(this);
6153 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006154 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006155 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006156 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006157 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006158 }
6159
James Mattis3ce3d3c2021-02-09 18:18:28 -08006160 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6161 @NonNull final List<NetworkRequest> r) {
6162 super();
6163 ensureAllNetworkRequestsHaveType(r);
6164 mRequests = initializeRequests(r);
6165 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006166 final NetworkAgentInfo satisfier = nri.getSatisfier();
6167 if (null != satisfier) {
6168 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6169 // The active request is necessary to figure out what callbacks to send, in
6170 // particular then a network updates its capabilities.
6171 // As this code creates a new NRI with a new set of requests, figure out which of
6172 // the list of requests should be the active request. It is always the first
6173 // request of the list that can be satisfied by the satisfier since the order of
6174 // requests is a priority order.
6175 // Note even in the presence of a satisfier there may not be an active request,
6176 // when the satisfier is the no-service network.
6177 NetworkRequest activeRequest = null;
6178 for (final NetworkRequest candidate : r) {
6179 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6180 activeRequest = candidate;
6181 break;
6182 }
6183 }
6184 setSatisfier(satisfier, activeRequest);
6185 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006186 mMessenger = nri.mMessenger;
6187 mBinder = nri.mBinder;
6188 mPid = nri.mPid;
6189 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006190 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006191 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006192 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006193 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006194 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006195 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006196 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006197 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006198 }
6199
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006200 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006201 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006202 }
6203
paulhue9913722021-05-26 15:19:20 +08006204 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006205 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006206 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006207 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006208 }
6209
James Mattis2516da32021-01-31 17:06:19 -08006210 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6211 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6212 // false.
6213 boolean isBeingSatisfied() {
6214 return (null != mSatisfier && null != mActiveRequest);
6215 }
6216
James Mattis3d229892020-11-16 16:46:28 -08006217 boolean isMultilayerRequest() {
6218 return mRequests.size() > 1;
6219 }
6220
James Mattis45d81842021-01-10 14:24:24 -08006221 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6222 // Creating a defensive copy to prevent the sender from modifying the list being
6223 // reflected in the return value of this method.
6224 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006225 return Collections.unmodifiableList(tempRequests);
6226 }
6227
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006228 void decrementRequestCount() {
6229 mPerUidCounter.decrementCount(mUid);
6230 }
6231
James Mattisb1392002021-03-31 13:57:52 -07006232 void linkDeathRecipient() {
6233 if (null != mBinder) {
6234 try {
6235 mBinder.linkToDeath(this, 0);
6236 } catch (RemoteException e) {
6237 binderDied();
6238 }
6239 }
6240 }
6241
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006242 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006243 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006244 try {
6245 mBinder.unlinkToDeath(this, 0);
6246 } catch (NoSuchElementException e) {
6247 // Temporary workaround for b/194394697 pending analysis of additional logs
6248 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6249 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006250 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006251 }
6252
paulhu48291862021-07-14 14:53:57 +08006253 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6254 // Compare two preference orders.
6255 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006256 }
6257
paulhu48291862021-07-14 14:53:57 +08006258 int getPreferenceOrderForNetd() {
6259 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6260 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6261 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006262 }
paulhu48291862021-07-14 14:53:57 +08006263 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006264 }
6265
James Mattis4fce5d12020-11-12 15:53:42 -08006266 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006267 public void binderDied() {
6268 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006269 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006270 // As an immutable collection, mRequests cannot change by the time the
6271 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6272 // is acceptable. Use handleReleaseNetworkRequest and not directly
6273 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6274 // the app already unregistered the request.
6275 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6276 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006277 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006278
James Mattis4fce5d12020-11-12 15:53:42 -08006279 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006280 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006281 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6282 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006283 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006284 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006285 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006286 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006287 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006288 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006289 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006290 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006291 }
6292
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006293 // This checks that the passed capabilities either do not request a
6294 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006295 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006296 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006297 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006298 throw new SecurityException("Insufficient permissions to request a specific SSID");
6299 }
paulhu1a407652019-03-22 16:35:06 +08006300
6301 if (nc.hasSignalStrength()
6302 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6303 throw new SecurityException(
6304 "Insufficient permissions to request a specific signal strength");
6305 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006306 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006307
junyulai2217bec2021-04-14 23:33:31 +08006308 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006309 enforceNetworkFactoryPermission();
6310 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006311 }
6312
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006313 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006314 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006315 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006316 // mNetworkRequests may contain the same value multiple times in case of
6317 // multilayer requests. It won't matter in this case because the thresholds
6318 // will then be the same and be deduplicated as they enter the `thresholds` set.
6319 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006320 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6321 for (final NetworkRequest req : nri.mRequests) {
6322 if (req.networkCapabilities.hasSignalStrength()
6323 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6324 thresholds.add(req.networkCapabilities.getSignalStrength());
6325 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006326 }
6327 }
6328 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006329 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006330 }
6331
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006332 private void updateSignalStrengthThresholds(
6333 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006334 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006335
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006336 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006337 String detail;
6338 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6339 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6340 } else {
6341 detail = reason;
6342 }
6343 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006344 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006345 }
6346
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006347 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006348 }
6349
Chalard Jeandd421992021-12-16 23:16:02 +09006350 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006351 if (nc == null) {
6352 return;
6353 }
6354 NetworkSpecifier ns = nc.getNetworkSpecifier();
6355 if (ns == null) {
6356 return;
6357 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006358 if (ns instanceof MatchAllNetworkSpecifier) {
6359 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6360 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006361 }
6362
Chalard Jeandd421992021-12-16 23:16:02 +09006363 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006364 ensureValidNetworkSpecifier(nc);
6365 if (nc.isPrivateDnsBroken()) {
6366 throw new IllegalArgumentException("Can't request broken private DNS");
6367 }
Chalard Jean9a30acf2021-12-13 22:53:51 +09006368 if (nc.hasAccessUids()) {
6369 throw new IllegalArgumentException("Can't request access UIDs");
6370 }
lucasline117e2e2019-10-22 18:27:33 +08006371 }
6372
Chalard Jeandd421992021-12-16 23:16:02 +09006373 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6374 ensureListenableCapabilities(nc);
6375 final String badCapability = nc.describeFirstNonRequestableCapability();
6376 if (badCapability != null) {
6377 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6378 }
6379 }
6380
Chiachang Wang3bc52762021-11-25 14:17:57 +08006381 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6382 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006383 private boolean isTargetSdkAtleast(int version, int callingUid,
6384 @NonNull String callingPackageName) {
6385 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006386 final PackageManager pm =
6387 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006388 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006389 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006390 if (callingVersion < version) return false;
6391 } catch (PackageManager.NameNotFoundException e) { }
6392 return true;
6393 }
6394
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006395 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006396 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006397 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006398 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006399 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006400 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006401 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6402 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006403 throw new SecurityException("Insufficient permissions to specify legacy type");
6404 }
markchienfac84a22020-03-18 21:16:15 +08006405 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006406 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006407 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006408 // Privileged callers can track the default network of another UID by passing in a UID.
6409 if (asUid != Process.INVALID_UID) {
6410 enforceSettingsPermission();
6411 } else {
6412 asUid = callingUid;
6413 }
junyulaiad010792021-01-11 16:53:38 +08006414 final NetworkRequest.Type reqType;
6415 try {
6416 reqType = NetworkRequest.Type.values()[reqTypeInt];
6417 } catch (ArrayIndexOutOfBoundsException e) {
6418 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6419 }
6420 switch (reqType) {
6421 case TRACK_DEFAULT:
6422 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006423 // is unused and will be replaced by ones appropriate for the UID (usually, the
6424 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006425 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006426 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006427 enforceAccessPermission();
6428 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006429 case TRACK_SYSTEM_DEFAULT:
6430 enforceSettingsPermission();
6431 networkCapabilities = new NetworkCapabilities(defaultNc);
6432 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006433 case BACKGROUND_REQUEST:
6434 enforceNetworkStackOrSettingsPermission();
6435 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006436 case REQUEST:
6437 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6438 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6439 callingAttributionTag);
6440 // TODO: this is incorrect. We mark the request as metered or not depending on
6441 // the state of the app when the request is filed, but we never change the
6442 // request if the app changes network state. http://b/29964605
6443 enforceMeteredApnPolicy(networkCapabilities);
6444 break;
junyulai1b1c8742021-03-12 20:05:08 +08006445 case LISTEN_FOR_BEST:
6446 enforceAccessPermission();
6447 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6448 break;
junyulaiad010792021-01-11 16:53:38 +08006449 default:
6450 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006451 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006452 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006453 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006454 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006455
junyulai1b1c8742021-03-12 20:05:08 +08006456 // Enforce FOREGROUND if the caller does not have permission to use background network.
6457 if (reqType == LISTEN_FOR_BEST) {
6458 restrictBackgroundRequestForCaller(networkCapabilities);
6459 }
6460
6461 // Set the UID range for this request to the single UID of the requester, unless the
6462 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006463 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6464 // are no visible methods to set the UIDs, an app could use reflection to try and get
6465 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006466 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006467 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6468 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006469
Etan Cohen85000162017-02-05 10:42:27 -08006470 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006471 throw new IllegalArgumentException("Bad timeout specified");
6472 }
Etan Cohen9786d922015-11-18 10:56:15 -08006473
James Mattis3ce3d3c2021-02-09 18:18:28 -08006474 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006475 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006476 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006477 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006478 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006479 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006480
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006481 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6482 // copied from the default request above. (This is necessary to ensure, for example, that
6483 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6484 // changes don't alter request matching.
6485 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6486 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006487 throw new IllegalStateException(
6488 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006489 + networkCapabilities + " vs. " + defaultNc);
6490 }
6491
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006492 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006493 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006494 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006495 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006496 }
6497 return networkRequest;
6498 }
6499
James Mattis3ce3d3c2021-02-09 18:18:28 -08006500 /**
6501 * Return the nri to be used when registering a network request. Specifically, this is used with
6502 * requests registered to track the default request. If there is currently a per-app default
6503 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6504 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006505 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6506 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006507 * @param nr the network request for the nri.
6508 * @param msgr the messenger for the nri.
6509 * @param binder the binder for the nri.
6510 * @param callingAttributionTag the calling attribution tag for the nri.
6511 * @return the nri to register.
6512 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006513 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006514 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006515 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006516 @Nullable String callingAttributionTag) {
6517 final List<NetworkRequest> requests;
6518 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6519 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006520 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006521 } else {
6522 requests = Collections.singletonList(nr);
6523 }
Roshan Pius951c0032020-12-22 15:10:42 -08006524 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006525 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006526 }
6527
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006528 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6529 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006530 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006531 if (!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
6532 enforceConnectivityRestrictedNetworksPermission();
6533 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006534 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006535 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006536 }
6537 }
6538
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006539 private boolean checkConnectivityRestrictedNetworksPermission(int callerPid, int callerUid) {
6540 if (checkAnyPermissionOf(callerPid, callerUid,
6541 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)
6542 || checkAnyPermissionOf(callerPid, callerUid,
6543 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
6544 return true;
6545 }
6546 return false;
6547 }
6548
fenglu3f357402015-03-20 11:29:56 -07006549 @Override
fenglub00f4882015-04-21 17:12:05 -07006550 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006551 enforceAccessPermission();
6552 NetworkAgentInfo nai = null;
6553 if (network == null) {
6554 return false;
6555 }
6556 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006557 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006558 }
6559 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006560 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006561 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006562 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006563 Integer uidReqs = mBandwidthRequests.get(uid);
6564 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006565 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006566 }
6567 mBandwidthRequests.put(uid, ++uidReqs);
6568 }
fenglu3f357402015-03-20 11:29:56 -07006569 return true;
6570 }
6571 return false;
6572 }
6573
Felipe Leme0a5ae422016-06-20 16:36:29 -07006574 private boolean isSystem(int uid) {
6575 return uid < Process.FIRST_APPLICATION_UID;
6576 }
fenglu3f357402015-03-20 11:29:56 -07006577
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006578 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006579 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006580 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006581 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006582 return;
6583 }
Hugo Benichi39621362017-02-11 17:04:43 +09006584 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6585 // Policy already enforced.
6586 return;
6587 }
paulhuaf50d7d2020-12-24 19:47:34 +08006588 final long ident = Binder.clearCallingIdentity();
6589 try {
6590 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6591 // If UID is restricted, don't allow them to bring up metered APNs.
6592 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6593 }
6594 } finally {
6595 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006596 }
6597 }
6598
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006599 @Override
6600 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006601 PendingIntent operation, @NonNull String callingPackageName,
6602 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006603 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006604 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006605 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006606 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6607 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006608 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006609 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006610 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006611 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006612 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6613 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006614
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006615 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006616 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006617 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6618 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006619 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006620 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6621 nri));
6622 return networkRequest;
6623 }
6624
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006625 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6626 mHandler.sendMessageDelayed(
6627 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006628 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006629 }
6630
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006631 @Override
6632 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006633 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006634 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006635 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006636 }
6637
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006638 // In order to implement the compatibility measure for pre-M apps that call
6639 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6640 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6641 // This ensures it has permission to do so.
6642 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6643 if (nc == null) {
6644 return false;
6645 }
6646 int[] transportTypes = nc.getTransportTypes();
6647 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6648 return false;
6649 }
6650 try {
6651 mContext.enforceCallingOrSelfPermission(
6652 android.Manifest.permission.ACCESS_WIFI_STATE,
6653 "ConnectivityService");
6654 } catch (SecurityException e) {
6655 return false;
6656 }
6657 return true;
6658 }
6659
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006660 @Override
6661 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006662 Messenger messenger, IBinder binder,
6663 @NetworkCallback.Flag int callbackFlags,
6664 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006665 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006666 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6667 enforceAccessPermission();
6668 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006669
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006670 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006671 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006672 Binder.getCallingPid(), callingUid, callingPackageName);
6673 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006674 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6675 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6676 // onLost and onAvailable callbacks when networks move in and out of the background.
6677 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6678 // can't request networks.
6679 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006680 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006681
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006682 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006683 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006684 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006685 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006686 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006687 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006688
6689 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6690 return networkRequest;
6691 }
6692
6693 @Override
6694 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006695 PendingIntent operation, @NonNull String callingPackageName,
6696 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006697 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006698 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006699 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6700 enforceAccessPermission();
6701 }
Chalard Jeandd421992021-12-16 23:16:02 +09006702 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006703 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006704 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006705 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006706 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006707
6708 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006709 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006710 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6711 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006712 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006713
WeiZhang1cc3f172021-06-03 19:02:04 -05006714 mHandler.sendMessage(mHandler.obtainMessage(
6715 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006716 }
6717
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006718 /** Returns the next Network provider ID. */
6719 public final int nextNetworkProviderId() {
6720 return mNextNetworkProviderId.getAndIncrement();
6721 }
6722
Erik Kline0c04b742016-07-07 16:50:58 +09006723 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006724 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006725 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006726 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006727 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006728 }
6729
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006730 private void releaseNetworkRequestAndCallOnUnavailable(NetworkRequest networkRequest) {
6731 ensureNetworkRequestHasType(networkRequest);
6732 mHandler.sendMessage(mHandler.obtainMessage(
6733 EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE, mDeps.getCallingUid(), 0,
6734 networkRequest));
6735 }
6736
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006737 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6738 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006739 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6740 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6741 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006742 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006743 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006744 return;
6745 }
6746
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006747 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6748 mNetworkProviderInfos.put(npi.messenger, npi);
6749 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006750 }
6751
6752 @Override
6753 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006754 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006755 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006756 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006757 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006758 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6759 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006760 }
6761
6762 @Override
6763 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006764 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006765 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006766 }
6767
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006768 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006769 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006770 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6771 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006772 Objects.requireNonNull(score);
6773 Objects.requireNonNull(caps);
6774 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006775 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006776 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006777 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6778 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006779 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6780 }
6781
Chalard Jeanbb902a52021-08-18 01:35:19 +09006782 private void updateOfferScore(final NetworkOffer offer) {
6783 final boolean yieldToBadWiFi =
6784 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6785 final NetworkOffer newOffer = new NetworkOffer(
6786 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6787 offer.caps, offer.callback, offer.providerId);
6788 if (offer.equals(newOffer)) return;
6789 handleRegisterNetworkOffer(newOffer);
6790 }
6791
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006792 @Override
6793 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6794 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6795 }
6796
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006797 private void handleUnregisterNetworkProvider(Messenger messenger) {
6798 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6799 if (npi == null) {
6800 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006801 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006802 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006803 // Unregister all the offers from this provider
6804 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6805 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006806 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006807 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6808 toRemove.add(noi);
6809 }
6810 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006811 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006812 handleUnregisterNetworkOffer(noi);
6813 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006814 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006815 }
6816
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006817 @Override
James Mattisf7027322020-12-13 16:28:14 -08006818 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006819 if (request.hasTransport(TRANSPORT_TEST)) {
6820 enforceNetworkFactoryOrTestNetworksPermission();
6821 } else {
6822 enforceNetworkFactoryPermission();
6823 }
James Mattisf7027322020-12-13 16:28:14 -08006824 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6825 if (nri != null) {
6826 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6827 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6828 mHandler.post(() -> handleReleaseNetworkRequest(
6829 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6830 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006831 }
6832
Paul Jensen1f567382015-02-13 14:18:39 -05006833 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6834 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006835 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006836 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006837 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006838 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006839 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006840
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006841 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006842 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006843 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006844
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006845 // UID ranges for users that are currently blocked by VPNs.
6846 // This array is accessed and iterated on multiple threads without holding locks, so its
6847 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6848 // (on the handler thread).
6849 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6850
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006851 // Must only be accessed on the handler thread
6852 @NonNull
6853 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6854
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006855 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006856 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006857
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006858 // Current OEM network preferences. This object must only be written to on the handler thread.
6859 // Since it is immutable and always non-null, other threads may read it if they only care
6860 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006861 @NonNull
6862 private OemNetworkPreferences mOemNetworkPreferences =
6863 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006864 // Current per-profile network preferences. This object follows the same threading rules as
6865 // the OEM network preferences above.
6866 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006867 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6868 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006869
paulhu51f77dc2021-06-07 02:34:20 +00006870 // A set of UIDs that should use mobile data preferentially if available. This object follows
6871 // the same threading rules as the OEM network preferences above.
6872 @NonNull
6873 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6874
James Mattiscb1e0362021-04-06 17:07:42 -07006875 // OemNetworkPreferences activity String log entries.
6876 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6877 @NonNull
6878 private final LocalLog mOemNetworkPreferencesLogs =
6879 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6880
James Mattis02220e22021-03-13 19:27:21 -08006881 /**
6882 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6883 * @param packageName the package name to check existence of a mapping for.
6884 * @return true if a mapping exists, false otherwise
6885 */
6886 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6887 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6888 }
6889
James Mattise3ef1912020-12-20 11:09:58 -08006890 // The always-on request for an Internet-capable network that apps without a specific default
6891 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006892 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006893 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006894 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006895 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006896 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006897 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006898 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006899
James Mattisd31bdfa2020-12-23 16:37:26 -08006900 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6901 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6902 }
6903
6904 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006905 * Return the default network request currently tracking the given uid.
6906 * @param uid the uid to check.
6907 * @return the NetworkRequestInfo tracking the given uid.
6908 */
6909 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006910 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006911 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006912 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006913 // Checking the first request is sufficient as only multilayer requests will have more
6914 // than one request and for multilayer, all requests will track the same uids.
6915 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006916 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006917 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006918 highestPriorityNri = nri;
6919 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006920 }
6921 }
paulhuaa0743d2021-05-26 21:56:03 +08006922 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006923 }
6924
6925 /**
6926 * Get a copy of the network requests of the default request that is currently tracking the
6927 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006928 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6929 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006930 * @param requestorUid the uid to check the default for.
6931 * @param requestorPackageName the requestor's package name.
6932 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6933 */
6934 @NonNull
6935 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006936 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006937 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006938 getDefaultRequestTrackingUid(asUid).mRequests,
6939 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006940 }
6941
6942 /**
6943 * Copy the given nri's NetworkRequest collection.
6944 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006945 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6946 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006947 * @param requestorUid the uid to set on the copied collection.
6948 * @param requestorPackageName the package name to set on the copied collection.
6949 * @return the copied NetworkRequest collection.
6950 */
6951 @NonNull
6952 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006953 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6954 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006955 final List<NetworkRequest> requests = new ArrayList<>();
6956 for (final NetworkRequest nr : requestsToCopy) {
6957 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006958 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006959 nr.legacyType, nextNetworkRequestId(), nr.type));
6960 }
6961 return requests;
6962 }
6963
6964 @NonNull
6965 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006966 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6967 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006968 // These capabilities are for a TRACK_DEFAULT callback, so:
6969 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6970 // mDefaultRequest and a per-UID default request.
6971 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006972 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006973 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006974 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6975 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006976 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006977 restrictRequestUidsForCallerAndSetRequestorInfo(
6978 netCap, requestorUid, requestorPackageName);
6979 return netCap;
6980 }
6981
6982 /**
6983 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6984 * @param nr the network request to check for equality against.
6985 * @return the nri if one exists, null otherwise.
6986 */
6987 @Nullable
6988 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6989 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6990 if (nri.getNetworkRequestForCallback().equals(nr)) {
6991 return nri;
6992 }
6993 }
6994 return null;
6995 }
6996
6997 /**
6998 * Check if an nri is currently being managed by per-app default networking.
6999 * @param nri the nri to check.
7000 * @return true if this nri is currently being managed by per-app default networking.
7001 */
7002 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7003 // nri.mRequests.get(0) is only different from the original request filed in
7004 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7005 // functionality therefore if these two don't match, it means this particular nri is
7006 // currently being managed by a per-app default.
7007 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7008 }
7009
7010 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007011 * Determine if an nri is a managed default request that disallows default networking.
7012 * @param nri the request to evaluate
7013 * @return true if device-default networking is disallowed
7014 */
7015 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7016 // Check if this nri is a managed default that supports the default network at its
7017 // lowest priority request.
7018 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7019 final NetworkCapabilities lowestPriorityNetCap =
7020 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7021 return isPerAppDefaultRequest(nri)
7022 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7023 lowestPriorityNetCap));
7024 }
7025
Erik Kline05f2b402015-04-30 12:58:40 +09007026 // Request used to optionally keep mobile data active even when higher
7027 // priority networks like Wi-Fi are active.
7028 private final NetworkRequest mDefaultMobileDataRequest;
7029
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007030 // Request used to optionally keep wifi data active even when higher
7031 // priority networks like ethernet are active.
7032 private final NetworkRequest mDefaultWifiRequest;
7033
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007034 // Request used to optionally keep vehicle internal network always active
7035 private final NetworkRequest mDefaultVehicleRequest;
7036
James Mattisd31bdfa2020-12-23 16:37:26 -08007037 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7038 // network with no service. This NAI should never be matched against, nor should any public API
7039 // ever return the associated network. For this reason, this NAI is not in the list of available
7040 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7041 // default requests that don't support using the device default network which will ultimately
7042 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7043 @VisibleForTesting
7044 final NetworkAgentInfo mNoServiceNetwork;
7045
Chalard Jean5b409c72021-02-04 13:12:59 +09007046 // The NetworkAgentInfo currently satisfying the default request, if any.
7047 private NetworkAgentInfo getDefaultNetwork() {
7048 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007049 }
7050
James Mattis2516da32021-01-31 17:06:19 -08007051 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007052 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007053 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7054 // Currently, all network requests will have the same uids therefore checking the first
7055 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007056 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007057 if (null == uids) {
7058 continue;
7059 }
7060 for (final UidRange range : uids) {
7061 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007062 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007063 highestPriorityNri = nri;
7064 }
James Mattis2516da32021-01-31 17:06:19 -08007065 }
7066 }
7067 }
paulhuaa0743d2021-05-26 21:56:03 +08007068 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007069 }
7070
Varun Ananddf569952019-02-06 10:13:38 -08007071 @Nullable
7072 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7073 return nai != null ? nai.network : null;
7074 }
7075
7076 private void ensureRunningOnConnectivityServiceThread() {
7077 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7078 throw new IllegalStateException(
7079 "Not running on ConnectivityService thread: "
7080 + Thread.currentThread().getName());
7081 }
7082 }
7083
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007084 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007085 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7086 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007087 }
7088
Chalard Jean29d06db2018-05-02 21:14:54 +09007089 /**
7090 * Register a new agent with ConnectivityService to handle a network.
7091 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007092 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007093 * @param networkInfo the initial info associated with this network. It can be updated later :
7094 * see {@link #updateNetworkInfo}.
7095 * @param linkProperties the initial link properties of this network. They can be updated
7096 * later : see {@link #updateLinkProperties}.
7097 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007098 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09007099 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09007100 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007101 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007102 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007103 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007104 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007105 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007106 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007107 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7108 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007109 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7110 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7111 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007112 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007113 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007114 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
7115 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007116 } else {
7117 enforceNetworkFactoryPermission();
7118 }
7119
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007120 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007121 final long token = Binder.clearCallingIdentity();
7122 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007123 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007124 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007125 } finally {
7126 Binder.restoreCallingIdentity(token);
7127 }
7128 }
7129
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007130 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007131 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007132 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7133 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007134
Chalard Jean366c5252022-01-25 18:27:53 +09007135 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
7136 // the capabilities' access UID comply with security limitations. They will be sanitized
7137 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7138 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007139 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jean366c5252022-01-25 18:27:53 +09007140 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo),
7141 linkProperties, networkCapabilities,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007142 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007143 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7144 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007145
Chalard Jeanf2da1772018-04-26 16:16:10 +09007146 final String extraInfo = networkInfo.getExtraInfo();
7147 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007148 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007149 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007150 mDeps.getNetworkStack().makeNetworkMonitor(
7151 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007152 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7153 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007154 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007155 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007156 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007157 }
7158
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007159 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007160 if (VDBG) log("Network Monitor created for " + nai);
7161 // nai.nc and nai.lp are the same object that was passed by the network agent if the agent
7162 // lives in the same process as this code (e.g. wifi), so make sure this code doesn't
7163 // mutate their object
7164 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
7165 final LinkProperties lp = new LinkProperties(nai.linkProperties);
7166 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
7167 processCapabilitiesFromAgent(nai, nc);
7168 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
7169 processLinkPropertiesFromAgent(nai, lp);
7170 nai.linkProperties = lp;
7171
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007172 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007173
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007174 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007175 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007176 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007177 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007178
7179 try {
7180 networkMonitor.start();
7181 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007182 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007183 }
Chalard Jean366c5252022-01-25 18:27:53 +09007184
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007185 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007186 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007187 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007188 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007189 }
7190
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007191 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7192 @NonNull public final NetworkOffer offer;
7193
7194 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7195 this.offer = offer;
7196 }
7197
7198 @Override
7199 public void binderDied() {
7200 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7201 }
7202 }
7203
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007204 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7205 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7206 if (npi.providerId == providerId) return true;
7207 }
7208 return false;
7209 }
7210
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007211 /**
7212 * Register or update a network offer.
7213 * @param newOffer The new offer. If the callback member is the same as an existing
7214 * offer, it is an update of that offer.
7215 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007216 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007217 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7218 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007219 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007220 // This may actually happen if a provider updates its score or registers and then
7221 // immediately unregisters. The offer would still be in the handler queue, but the
7222 // provider would have been removed.
7223 if (DBG) log("Received offer from an unregistered provider");
7224 return;
7225 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007226 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7227 if (null != existingOffer) {
7228 handleUnregisterNetworkOffer(existingOffer);
7229 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007230 if (DBG) {
7231 // handleUnregisterNetworkOffer has already logged the old offer
7232 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7233 }
7234 } else {
7235 if (DBG) {
7236 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7237 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007238 }
7239 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7240 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007241 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007242 } catch (RemoteException e) {
7243 noi.binderDied();
7244 return;
7245 }
7246 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007247 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007248 }
7249
7250 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7251 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007252 if (DBG) {
7253 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7254 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007255
7256 // If the provider removes the offer and dies immediately afterwards this
7257 // function may be called twice in a row, but the array will no longer contain
7258 // the offer.
7259 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007260 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007261 }
7262
7263 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7264 @NonNull final INetworkOfferCallback callback) {
7265 ensureRunningOnConnectivityServiceThread();
7266 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007267 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007268 }
7269 return null;
7270 }
7271
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007272 /**
7273 * Called when receiving LinkProperties directly from a NetworkAgent.
7274 * Stores into |nai| any data coming from the agent that might also be written to the network's
7275 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7276 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007277 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007278 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007279 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7280 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007281 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007282 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007283 }
7284
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007285 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007286 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007287 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007288
Lorenzo Colittid523d142020-04-01 20:16:30 +09007289 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7290 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7291 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007292 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007293
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007294 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007295
7296 // update filtering rules, need to happen after the interface update so netd knows about the
7297 // new interface (the interface name -> index map becomes initialized)
7298 updateVpnFiltering(newLp, oldLp, networkAgent);
7299
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007300 updateMtu(newLp, oldLp);
7301 // TODO - figure out what to do for clat
7302// for (LinkProperties lp : newLp.getStackedLinks()) {
7303// updateMtu(lp, null);
7304// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007305 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007306 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7307 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007308
Erik Klineb9888902016-04-05 13:30:49 +09007309 updateRoutes(newLp, oldLp, netId);
7310 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007311 // Make sure LinkProperties represents the latest private DNS status.
7312 // This does not need to be done before updateDnses because the
7313 // LinkProperties are not the source of the private DNS configuration.
7314 // updateDnses will fetch the private DNS configuration from DnsManager.
7315 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007316
Chalard Jean5b409c72021-02-04 13:12:59 +09007317 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007318 handleApplyDefaultProxy(newLp.getHttpProxy());
7319 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007320 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007321 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007322
7323 updateWakeOnLan(newLp);
7324
Hai Shalome58bdc62021-01-11 18:45:34 -08007325 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7326 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7327 // does, it needs to be merged here.
7328 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7329 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007330
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007331 // TODO - move this check to cover the whole function
7332 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007333 synchronized (networkAgent) {
7334 networkAgent.linkProperties = newLp;
7335 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007336 // Start or stop DNS64 detection and 464xlat according to network state.
7337 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007338 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007339 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7340 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007341 if (networkAgent.everConnected) {
7342 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7343 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007344 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007345
7346 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007347 }
7348
Hai Shalome58bdc62021-01-11 18:45:34 -08007349 /**
7350 * @param naData captive portal data from NetworkAgent
7351 * @param apiData captive portal data from capport API
7352 */
7353 @Nullable
7354 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7355 CaptivePortalData apiData) {
7356 if (naData == null || apiData == null) {
7357 return naData == null ? apiData : naData;
7358 }
7359 final CaptivePortalData.Builder captivePortalBuilder =
7360 new CaptivePortalData.Builder(naData);
7361
7362 if (apiData.isCaptive()) {
7363 captivePortalBuilder.setCaptive(true);
7364 }
7365 if (apiData.isSessionExtendable()) {
7366 captivePortalBuilder.setSessionExtendable(true);
7367 }
7368 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7369 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7370 // otherwise data would be inconsistent. Prefer the capport API info if present,
7371 // as it can generally be refreshed more often.
7372 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7373 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7374 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7375 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7376 // No source has time / bytes remaining information: surface the newest refresh time
7377 // for other fields
7378 captivePortalBuilder.setRefreshTime(
7379 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7380 }
7381
Hai Shalom7c6ab402021-02-04 19:34:06 -08007382 // Prioritize the user portal URL from the network agent if the source is authenticated.
7383 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7384 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7385 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7386 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007387 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007388 // Prioritize the venue information URL from the network agent if the source is
7389 // authenticated.
7390 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7391 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7392 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7393 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007394 }
7395 return captivePortalBuilder.build();
7396 }
7397
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007398 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007399 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007400 // marks on unsupported interfaces is harmless.
7401 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7402 return;
7403 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007404
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007405 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7406 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7407
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007408 // Mask/mark of zero will not detect anything interesting.
7409 // Don't install rules unless both values are nonzero.
7410 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007411 return;
7412 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007413
7414 final String prefix = "iface:" + iface;
7415 try {
7416 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007417 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007418 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007419 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007420 }
7421 } catch (Exception e) {
7422 loge("Exception modifying wakeup packet monitoring: " + e);
7423 }
7424
Joel Scherpelza235a812017-05-22 13:47:41 +09007425 }
7426
Chalard Jean9589e722019-11-19 19:03:53 +09007427 private void updateInterfaces(final @Nullable LinkProperties newLp,
7428 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007429 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007430 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007431 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7432 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007433 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007434 for (final String iface : interfaceDiff.added) {
7435 try {
7436 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007437 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007438 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007439 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7440 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007441 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007442 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007443 }
Paul Jensenbff73492014-04-28 10:33:11 -04007444 }
7445 }
Chalard Jean9589e722019-11-19 19:03:53 +09007446 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007447 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007448 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007449 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007450 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007451 } catch (Exception e) {
7452 loge("Exception removing interface: " + e);
7453 }
7454 }
7455 }
7456
Tyler Weare4314862019-12-05 14:55:30 -08007457 // TODO: move to frameworks/libs/net.
7458 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7459 final String nextHop;
7460
7461 switch (route.getType()) {
7462 case RouteInfo.RTN_UNICAST:
7463 if (route.hasGateway()) {
7464 nextHop = route.getGateway().getHostAddress();
7465 } else {
7466 nextHop = INetd.NEXTHOP_NONE;
7467 }
7468 break;
7469 case RouteInfo.RTN_UNREACHABLE:
7470 nextHop = INetd.NEXTHOP_UNREACHABLE;
7471 break;
7472 case RouteInfo.RTN_THROW:
7473 nextHop = INetd.NEXTHOP_THROW;
7474 break;
7475 default:
7476 nextHop = INetd.NEXTHOP_NONE;
7477 break;
7478 }
7479
7480 final RouteInfoParcel rip = new RouteInfoParcel();
7481 rip.ifName = route.getInterface();
7482 rip.destination = route.getDestination().toString();
7483 rip.nextHop = nextHop;
7484 rip.mtu = route.getMtu();
7485
7486 return rip;
7487 }
7488
Paul Jensene0fd4a82014-08-06 15:51:33 -04007489 /**
7490 * Have netd update routes from oldLp to newLp.
7491 * @return true if routes changed between oldLp and newLp
7492 */
7493 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007494 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007495 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7496 new CompareOrUpdateResult<>(
7497 oldLp != null ? oldLp.getAllRoutes() : null,
7498 newLp != null ? newLp.getAllRoutes() : null,
7499 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007500
7501 // add routes before removing old in case it helps with continuous connectivity
7502
Chalard Jean9dd11612018-06-04 16:52:49 +09007503 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007504 for (RouteInfo route : routeDiff.added) {
7505 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007506 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007507 try {
Tyler Weare4314862019-12-05 14:55:30 -08007508 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007509 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007510 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007511 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007512 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007513 }
7514 }
7515 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007516 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007517 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007518 try {
Tyler Weare4314862019-12-05 14:55:30 -08007519 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007520 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007521 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007522 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007523 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007524 }
7525 }
7526
7527 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007528 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007529 try {
Tyler Weare4314862019-12-05 14:55:30 -08007530 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007531 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007532 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007533 }
7534 }
Tyler Weare4314862019-12-05 14:55:30 -08007535
7536 for (RouteInfo route : routeDiff.updated) {
7537 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7538 try {
7539 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7540 } catch (Exception e) {
7541 loge("Exception in networkUpdateRouteParcel: " + e);
7542 }
7543 }
7544 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7545 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007546 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007547
Erik Klineb9888902016-04-05 13:30:49 +09007548 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7549 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7550 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007551 }
Erik Klineb9888902016-04-05 13:30:49 +09007552
Erik Kline31b4a9e2018-01-11 21:07:29 +09007553 if (DBG) {
7554 final Collection<InetAddress> dnses = newLp.getDnsServers();
7555 log("Setting DNS servers for network " + netId + " to " + dnses);
7556 }
Erik Klineb9888902016-04-05 13:30:49 +09007557 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007558 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007559 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007560 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007561 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007562 }
Erik Kline54e35c02017-04-07 15:29:29 +09007563 }
7564
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007565 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7566 NetworkAgentInfo nai) {
7567 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7568 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7569 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7570 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7571
7572 if (!wasFiltering && !needsFiltering) {
7573 // Nothing to do.
7574 return;
7575 }
7576
7577 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7578 // Nothing changed.
7579 return;
7580 }
7581
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007582 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007583 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007584 // TODO: this create a window of opportunity for apps to receive traffic between the time
7585 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007586 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007587 // old rules are being removed.
7588 if (wasFiltering) {
7589 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7590 }
7591 if (needsFiltering) {
7592 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7593 }
7594 }
7595
Valentin Iftime9fa35092019-09-24 13:32:13 +02007596 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007597 if (mWolSupportedInterfaces == null) {
7598 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007599 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007600 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007601 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7602 }
7603
Luke Huangb913c812018-08-24 20:33:16 +08007604 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007605 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007606 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007607 }
7608 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007609 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007610 }
Luke Huangb913c812018-08-24 20:33:16 +08007611 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007612 }
7613
Chalard Jean62edfd82019-12-02 18:39:29 +09007614 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7615 @NonNull final NetworkCapabilities newNc) {
7616 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7617 final int newPermission = getNetworkPermission(newNc);
7618 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7619 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007620 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007621 } catch (RemoteException | ServiceSpecificException e) {
7622 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007623 }
7624 }
7625 }
7626
Paul Jensen53f08952015-06-16 14:27:36 -04007627 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007628 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7629 * Stores into |nai| any data coming from the agent that might also be written to the network's
7630 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7631 * agent is not lost when updateCapabilities is called.
7632 */
7633 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Chalard Jean15228572022-01-28 19:29:12 +09007634 if (nc.hasConnectivityManagedCapability()) {
7635 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
7636 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007637 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7638 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7639 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7640 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007641 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7642 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7643 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7644 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7645 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007646 nai.declaredCapabilities = new NetworkCapabilities(nc);
Chalard Jeanac9ace02022-01-26 16:54:05 +09007647 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(nc, nai.creatorUid,
7648 mCarrierPrivilegeAuthenticator);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007649 }
7650
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007651 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007652 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007653 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007654 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007655 underlyingNetworks = underlyingNetworksOrDefault(
7656 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007657 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007658 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7659 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007660 // metered if any underlying is metered, or originally declared metered by the agent.
7661 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007662 boolean roaming = false; // roaming if any underlying is roaming
7663 boolean congested = false; // congested if any underlying is congested
7664 boolean suspended = true; // suspended if all underlying are suspended
7665
7666 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007667 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007668 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007669 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007670 for (Network underlyingNetwork : underlyingNetworks) {
7671 final NetworkAgentInfo underlying =
7672 getNetworkAgentInfoForNetwork(underlyingNetwork);
7673 if (underlying == null) continue;
7674
7675 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7676 hadUnderlyingNetworks = true;
7677 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007678 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007679 }
7680
7681 // Merge capabilities of this underlying network. For bandwidth, assume the
7682 // worst case.
7683 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7684 underlyingCaps.getLinkDownstreamBandwidthKbps());
7685 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7686 underlyingCaps.getLinkUpstreamBandwidthKbps());
7687 // If this underlying network is metered, the VPN is metered (it may cost money
7688 // to send packets on this network).
7689 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7690 // If this underlying network is roaming, the VPN is roaming (the billing structure
7691 // is different than the usual, local one).
7692 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7693 // If this underlying network is congested, the VPN is congested (the current
7694 // condition of the network affects the performance of this network).
7695 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7696 // If this network is not suspended, the VPN is not suspended (the VPN
7697 // is able to transfer some data).
7698 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007699 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007700 }
7701 }
7702 if (!hadUnderlyingNetworks) {
7703 // No idea what the underlying networks are; assume reasonable defaults
7704 metered = true;
7705 roaming = false;
7706 congested = false;
7707 suspended = false;
7708 }
7709
lifrade6c2a2021-03-04 14:08:08 +08007710 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007711 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7712 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7713 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7714 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7715 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7716 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007717 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007718 }
7719
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007720 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007721 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7722 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7723 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007724 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007725 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007726 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007727 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007728 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7729 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007730 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007731 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007732 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007733 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007734 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7735 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007736 // does not cause any request (that is not a listen) currently matching that agent to
7737 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007738 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007739 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007740 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007741 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007742 }
7743
Paul Jensen53f08952015-06-16 14:27:36 -04007744 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007745 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007746 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007747 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007748 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007749 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007750 }
Paul Jensende49eb12015-06-25 15:30:08 -04007751 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007752 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007753 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007754 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007755 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007756 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007757 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007758 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007759 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007760 }
lucaslin2240ef62019-03-12 13:08:03 +08007761 if (nai.partialConnectivity) {
7762 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7763 } else {
7764 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7765 }
lucasline117e2e2019-10-22 18:27:33 +08007766 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007767
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007768 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007769 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7770 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007771 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007772 }
7773
Lorenzo Colittibd079452021-07-02 11:47:57 +09007774 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007775 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7776 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007777 }
7778
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007779 return newNc;
7780 }
7781
Lorenzo Colitti44840702021-01-11 22:27:57 +09007782 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7783 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7784 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7785 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7786 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7787 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7788 if (prevSuspended != suspended) {
7789 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7790 // onResumed have been removed.
7791 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7792 : ConnectivityManager.CALLBACK_RESUMED);
7793 }
7794 if (prevSuspended != suspended || prevRoaming != roaming) {
7795 // updateNetworkInfo will mix in the suspended info from the capabilities and
7796 // take appropriate action for the network having possibly changed state.
7797 updateNetworkInfo(nai, nai.networkInfo);
7798 }
7799 }
7800
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007801 /**
7802 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7803 *
7804 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7805 * capabilities we manage and store in {@code nai}, such as validated status and captive
7806 * portal status)
7807 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7808 * potentially triggers rematches.
7809 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7810 * change.)
7811 *
7812 * @param oldScore score of the network before any of the changes that prompted us
7813 * to call this function.
7814 * @param nai the network having its capabilities updated.
7815 * @param nc the new network capabilities.
7816 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007817 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7818 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007819 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007820 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007821 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007822 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007823
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007824 updateVpnUids(nai, prevNc, newNc);
7825 updateAccessUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007826 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007827
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007828 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007829 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7830 // the change we're processing can't affect any requests, it can only affect the listens
7831 // on this network. We might have been called by rematchNetworkAndRequests when a
7832 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007833 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007834 } else {
7835 // If the requestable capabilities have changed or the score changed, we can't have been
7836 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007837 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007838 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007839 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007840 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007841
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007842 final boolean oldMetered = prevNc.isMetered();
7843 final boolean newMetered = newNc.isMetered();
7844 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007845
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007846 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007847 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7848 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007849 }
junyulaif2c67e42018-08-07 19:50:45 +08007850
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007851 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7852 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007853
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007854 // Report changes that are interesting for network statistics tracking.
7855 if (meteredChanged || roamingChanged) {
7856 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007857 }
7858
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007859 // This network might have been underlying another network. Propagate its capabilities.
7860 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007861
7862 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007863 mDnsManager.updateTransportsForNetwork(
7864 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007865 }
lucaslin53e8a262021-06-08 01:43:59 +08007866
7867 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007868 }
7869
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007870 /** Convenience method to update the capabilities for a given network. */
7871 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7872 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7873 }
7874
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007875 /**
7876 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7877 * network.
7878 *
7879 * Ingress interface filtering enforces that all apps under the given network can only receive
7880 * packets from the network's interface (and loopback). This is important for VPNs because
7881 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7882 * non-VPN interfaces.
7883 *
7884 * As a result, this method should return true iff
7885 * 1. the network is an app VPN (not legacy VPN)
7886 * 2. the VPN does not allow bypass
7887 * 3. the VPN is fully-routed
7888 * 4. the VPN interface is non-null
7889 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007890 * @see INetd#firewallAddUidInterfaceRules
7891 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007892 */
7893 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7894 LinkProperties lp) {
7895 if (nc == null || lp == null) return false;
7896 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007897 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007898 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007899 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007900 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7901 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007902 }
7903
Chiachang Wang28afaff2020-12-10 22:24:47 +08007904 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7905 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7906 int index = 0;
7907 for (UidRange range : ranges) {
7908 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7909 index++;
7910 }
7911 return stableRanges;
7912 }
7913
Chalard Jeane6c95272022-01-25 21:04:21 +09007914 private static UidRangeParcel[] intsToUidRangeStableParcels(
7915 final @NonNull ArraySet<Integer> uids) {
7916 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
7917 int index = 0;
7918 for (int uid : uids) {
7919 stableRanges[index] = new UidRangeParcel(uid, uid);
7920 index++;
7921 }
7922 return stableRanges;
7923 }
7924
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007925 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7926 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7927 for (int i = 0; i < ranges.length; i++) {
7928 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7929 }
7930 return stableRanges;
7931 }
7932
Ken Chen5e65a852020-12-24 12:59:10 +08007933 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7934 int[] exemptUids) {
7935 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7936 try {
7937 mNetd.socketDestroy(ranges, exemptUids);
7938 } catch (Exception e) {
7939 loge("Exception in socket destroy: ", e);
7940 }
7941 }
7942 }
7943
paulhuaa0743d2021-05-26 21:56:03 +08007944 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007945 int[] exemptUids = new int[2];
7946 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7947 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7948 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7949 exemptUids[0] = VPN_UID;
7950 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7951 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7952
7953 maybeCloseSockets(nai, ranges, exemptUids);
7954 try {
7955 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007956 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007957 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007958 } else {
paulhu0e79d952021-06-09 16:11:35 +08007959 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007960 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007961 }
7962 } catch (Exception e) {
7963 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7964 " on netId " + nai.network.netId + ". " + e);
7965 }
7966 maybeCloseSockets(nai, ranges, exemptUids);
7967 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007968
lucaslin53e8a262021-06-08 01:43:59 +08007969 private boolean isProxySetOnAnyDefaultNetwork() {
7970 ensureRunningOnConnectivityServiceThread();
7971 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7972 final NetworkAgentInfo nai = nri.getSatisfier();
7973 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7974 return true;
7975 }
7976 }
7977 return false;
7978 }
7979
7980 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7981 NetworkCapabilities newNc) {
7982 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7983 // the proxy might be changed since the default network satisfied by the apps might also
7984 // changed.
7985 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7986 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007987 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7988 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7989 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007990 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7991 mProxyTracker.sendProxyBroadcast();
7992 }
7993 }
7994
Chalard Jeane6c95272022-01-25 21:04:21 +09007995 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
7996 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007997 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7998 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007999 if (null == prevRanges) prevRanges = new ArraySet<>();
8000 if (null == newRanges) newRanges = new ArraySet<>();
8001 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8002
8003 prevRanges.removeAll(newRanges);
8004 newRanges.removeAll(prevRangesCopy);
8005
8006 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008007 // When updating the VPN uid routing rules, add the new range first then remove the old
8008 // range. If old range were removed first, there would be a window between the old
8009 // range being removed and the new range being added, during which UIDs contained
8010 // in both ranges are not subject to any VPN routing rules. Adding new range before
8011 // removing old range works because, unlike the filtering rules below, it's possible to
8012 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008013 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8014 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8015 // [1-5] & [1-2],[4-5] == [3]
8016 // Then we can do:
8017 // maybeCloseSockets([3])
8018 // mNetd.networkAddUidRanges([1-2],[4-5])
8019 // mNetd.networkRemoveUidRanges([1-5])
8020 // maybeCloseSockets([3])
8021 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8022 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008023 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008024 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008025 }
8026 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008027 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008028 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008029 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
8030 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
8031 final String iface = nai.linkProperties.getInterfaceName();
8032 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008033 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008034 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8035 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8036 // were added first and then newRanges got removed later, there would be only one uid
8037 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8038 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8039 // Note that this is in contrast with the (more robust) update of VPN routing rules
8040 // above, where the addition of new ranges happens before the removal of old ranges.
8041 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8042 // to be removed will never overlap with the new range to be added.
8043 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08008044 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008045 }
8046 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08008047 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008048 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008049 } catch (Exception e) {
8050 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008051 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008052 }
8053 }
8054
Chalard Jeane6c95272022-01-25 21:04:21 +09008055 private void updateAccessUids(@NonNull NetworkAgentInfo nai,
8056 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8057 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
8058 final boolean prevEmpty = null == prevNc || prevNc.getAccessUidsNoCopy().isEmpty();
8059 final boolean newEmpty = null == newNc || newNc.getAccessUidsNoCopy().isEmpty();
8060 if (prevEmpty && newEmpty) return;
8061
8062 final ArraySet<Integer> prevUids =
8063 null == prevNc ? new ArraySet<>() : prevNc.getAccessUidsNoCopy();
8064 final ArraySet<Integer> newUids =
8065 null == newNc ? new ArraySet<>() : newNc.getAccessUidsNoCopy();
8066
8067 if (prevUids.equals(newUids)) return;
8068
8069 // This implementation is very simple and vastly faster for sets of Integers than
8070 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8071 // a key computed from the value and has storage for that.
8072 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8073 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8074 toRemove.removeAll(newUids);
8075 toAdd.removeAll(prevUids);
8076
8077 try {
8078 if (!toAdd.isEmpty()) {
8079 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8080 nai.network.netId,
8081 intsToUidRangeStableParcels(toAdd),
8082 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8083 }
8084 if (!toRemove.isEmpty()) {
8085 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8086 nai.network.netId,
8087 intsToUidRangeStableParcels(toRemove),
8088 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8089 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008090 } catch (ServiceSpecificException e) {
8091 // Has the interface disappeared since the network was built ?
8092 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008093 } catch (RemoteException e) {
8094 // Netd died. This usually causes a runtime restart anyway.
8095 }
8096 }
8097
Hugo Benichi9d35b752017-09-01 01:23:32 +00008098 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008099 ensureRunningOnConnectivityServiceThread();
8100
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008101 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008102 // Ignore updates for disconnected networks
8103 return;
8104 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008105 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008106 log("Update of LinkProperties for " + nai.toShortString()
8107 + "; created=" + nai.created
8108 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00008109 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008110 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8111 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008112 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008113 }
8114
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008115 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8116 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008117 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008118 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008119 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008120 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8121 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8122 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008123 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8124 // need to be sent as a separate extra.
8125 final NetworkRequest req = nri.isMultilayerRequest()
8126 ? nri.getActiveRequest()
8127 // Non-multilayer listen requests do not have an active request
8128 : nri.mRequests.get(0);
8129 if (req == null) {
8130 Log.wtf(TAG, "No request in NRI " + nri);
8131 }
8132 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008133 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008134 sendIntent(nri.mPendingIntent, intent);
8135 }
8136 // else not handled
8137 }
8138
8139 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8140 mPendingIntentWakeLock.acquire();
8141 try {
8142 if (DBG) log("Sending " + pendingIntent);
8143 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
8144 } catch (PendingIntent.CanceledException e) {
8145 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8146 mPendingIntentWakeLock.release();
8147 releasePendingNetworkRequest(pendingIntent);
8148 }
8149 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8150 }
8151
8152 @Override
8153 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8154 String resultData, Bundle resultExtras) {
8155 if (DBG) log("Finished sending " + pendingIntent);
8156 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008157 // Release with a delay so the receiving client has an opportunity to put in its
8158 // own request.
8159 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008160 }
8161
James Mattis212df9e2020-12-03 19:57:41 -08008162 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
8163 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
8164 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008165 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008166 // Default request has no msgr. Also prevents callbacks from being invoked for
8167 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8168 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8169 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008170 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008171 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008172 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008173 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008174 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008175 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008176 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008177 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8178 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008179 }
Roshan Pius951c0032020-12-22 15:10:42 -08008180 final boolean includeLocationSensitiveInfo =
8181 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008182 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008183 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008184 final NetworkCapabilities nc =
8185 networkCapabilitiesRestrictedForCallerPermissions(
8186 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8187 putParcelable(
8188 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008189 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008190 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008191 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008192 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008193 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8194 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008195 // For this notification, arg1 contains the blocked status.
8196 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008197 break;
8198 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008199 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008200 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008201 break;
8202 }
8203 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008204 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008205 final NetworkCapabilities netCap =
8206 networkCapabilitiesRestrictedForCallerPermissions(
8207 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8208 putParcelable(
8209 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008210 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008211 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008212 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008213 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008214 break;
8215 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008216 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008217 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8218 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008219 break;
8220 }
junyulaif2c67e42018-08-07 19:50:45 +08008221 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008222 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008223 msg.arg1 = arg1;
8224 break;
8225 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008226 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008227 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008228 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008229 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008230 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008231 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008232 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008233 }
James Mattis45d81842021-01-10 14:24:24 -08008234 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008235 } catch (RemoteException e) {
8236 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008237 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008238 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008239 }
8240
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008241 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8242 bundle.putParcelable(t.getClass().getSimpleName(), t);
8243 }
8244
Chalard Jean0702f982021-09-16 21:50:07 +09008245 /**
8246 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8247 *
8248 * When a request should be assigned to a new network, it is normally lingered to give
8249 * time for apps to gracefully migrate their connections. When both networks are on the same
8250 * radio, but that radio can't do time-sharing efficiently, this may end up being
8251 * counter-productive because any traffic on the old network may drastically reduce the
8252 * performance of the new network.
8253 * The stack supports a configuration to let modem vendors state that their radio can't
8254 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8255 * from one cell network to another can't be done gracefully.
8256 *
8257 * @param oldNai the old network serving the request
8258 * @param newNai the new network serving the request
8259 * @return whether the switch can be graceful
8260 */
8261 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8262 @NonNull final NetworkAgentInfo newSatisfier) {
8263 if (mCellularRadioTimesharingCapable) return true;
8264 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8265 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8266 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8267 }
8268
Paul Jensenaf94b982014-09-30 15:37:41 -04008269 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008270 if (nai.numRequestNetworkRequests() != 0) {
8271 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8272 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008273 // Ignore listening and track default requests.
8274 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008275 loge("Dead network still had at least " + nr);
8276 break;
8277 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008278 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008279 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008280 }
8281
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008282 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8283 if (oldNetwork == null) {
8284 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8285 return;
8286 }
Chalard Jean49707572019-12-10 21:07:02 +09008287 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008288
8289 // If we get here it means that the last linger timeout for this network expired. So there
8290 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008291 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008292
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008293 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008294 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008295 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008296 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008297 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008298 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008299 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008300 }
8301
James Mattise3ef1912020-12-20 11:09:58 -08008302 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8303 boolean isDefaultChanged = false;
8304 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8305 final NetworkReassignment.RequestReassignment reassignment =
8306 changes.getReassignment(defaultRequestInfo);
8307 if (null == reassignment) {
8308 continue;
8309 }
8310 // reassignment only contains those instances where the satisfying network changed.
8311 isDefaultChanged = true;
8312 // Notify system services of the new default.
8313 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8314 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008315
James Mattise3ef1912020-12-20 11:09:58 -08008316 if (isDefaultChanged) {
8317 // Hold a wakelock for a short time to help apps in migrating to a new default.
8318 scheduleReleaseNetworkTransitionWakelock();
8319 }
8320 }
8321
8322 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8323 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8324 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8325 if (DBG) {
8326 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8327 }
Chalard Jean8e382112019-12-03 20:45:30 +09008328
James Mattisd31bdfa2020-12-23 16:37:26 -08008329 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8330 if (newDefaultNetwork != null) {
8331 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008332 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008333
James Mattisd31bdfa2020-12-23 16:37:26 -08008334 // Set an app level managed default and return since further processing only applies to the
8335 // default network.
8336 if (mDefaultRequest != nri) {
8337 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8338 return;
8339 }
8340
8341 makeDefaultNetwork(newDefaultNetwork);
8342
James Mattise3ef1912020-12-20 11:09:58 -08008343 if (oldDefaultNetwork != null) {
8344 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8345 }
8346 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008347 handleApplyDefaultProxy(null != newDefaultNetwork
8348 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8349 updateTcpBufferSizes(null != newDefaultNetwork
8350 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008351 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008352 }
8353
James Mattisd31bdfa2020-12-23 16:37:26 -08008354 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8355 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8356 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8357 try {
8358 if (VDBG) {
8359 log("Setting default network for " + nri
8360 + " using UIDs " + nri.getUids()
8361 + " with old network " + (oldDefaultNetwork != null
8362 ? oldDefaultNetwork.network().getNetId() : "null")
8363 + " and new network " + (newDefaultNetwork != null
8364 ? newDefaultNetwork.network().getNetId() : "null"));
8365 }
8366 if (nri.getUids().isEmpty()) {
8367 throw new IllegalStateException("makeDefaultForApps called without specifying"
8368 + " any applications to set as the default." + nri);
8369 }
8370 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008371 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008372 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008373 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008374 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008375 }
8376 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008377 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008378 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008379 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008380 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008381 }
8382 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008383 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008384 }
8385 }
8386
8387 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8388 try {
8389 if (null != newDefaultNetwork) {
8390 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8391 } else {
8392 mNetd.networkClearDefault();
8393 }
8394 } catch (RemoteException | ServiceSpecificException e) {
8395 loge("Exception setting default network :" + e);
8396 }
8397 }
8398
Chalard Jean05cbe972019-12-09 11:50:38 +09008399 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008400 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008401 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008402 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008403 processNewlySatisfiedListenRequests(nai);
8404 }
8405
8406 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008407 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8408 if (nri.isMultilayerRequest()) {
8409 continue;
8410 }
8411 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008412 if (!nr.isListen()) continue;
8413 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008414 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008415 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8416 }
8417 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008418 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008419
Chalard Jeancd397a22019-11-22 22:33:33 +09008420 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008421 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8422 if (nri.isMultilayerRequest()) {
8423 continue;
8424 }
8425 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008426 if (!nr.isListen()) continue;
8427 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8428 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008429 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008430 }
8431 }
8432 }
8433
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008434 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008435 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008436 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008437 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008438 @Nullable public final NetworkRequest mOldNetworkRequest;
8439 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008440 @Nullable public final NetworkAgentInfo mOldNetwork;
8441 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008442 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008443 @Nullable final NetworkRequest oldNetworkRequest,
8444 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008445 @Nullable final NetworkAgentInfo oldNetwork,
8446 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008447 mNetworkRequestInfo = networkRequestInfo;
8448 mOldNetworkRequest = oldNetworkRequest;
8449 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008450 mOldNetwork = oldNetwork;
8451 mNewNetwork = newNetwork;
8452 }
Chalard Jean49707572019-12-10 21:07:02 +09008453
8454 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008455 final NetworkRequest requestToShow = null != mNewNetworkRequest
8456 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8457 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008458 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8459 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008460 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008461 }
8462
Chalard Jean46a62372019-12-10 21:25:24 +09008463 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008464
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008465 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008466 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008467 }
8468
8469 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008470 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008471 // The code is never supposed to add two reassignments of the same request. Make
8472 // sure this stays true, but without imposing this expensive check on all
8473 // reassignments on all user devices.
8474 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008475 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008476 throw new IllegalStateException("Trying to reassign ["
8477 + reassignment + "] but already have ["
8478 + existing + "]");
8479 }
8480 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008481 }
Chalard Jean46a62372019-12-10 21:25:24 +09008482 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008483 }
8484
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008485 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008486 // the passed request.
8487 @Nullable
8488 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008489 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008490 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008491 }
8492 return null;
8493 }
Chalard Jean49707572019-12-10 21:07:02 +09008494
8495 public String toString() {
8496 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8497 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008498 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008499 for (final RequestReassignment rr : getRequestReassignments()) {
8500 sj.add(rr.toString());
8501 }
8502 return sj.toString();
8503 }
8504
8505 public String debugString() {
8506 final StringBuilder sb = new StringBuilder();
8507 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008508 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008509 for (final RequestReassignment rr : getRequestReassignments()) {
8510 sb.append("\n ").append(rr);
8511 }
8512 return sb.append("\n").toString();
8513 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008514 }
8515
Chalard Jean24344d72019-12-04 13:32:31 +09008516 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008517 @Nullable final NetworkRequest previousRequest,
8518 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008519 @Nullable final NetworkAgentInfo previousSatisfier,
8520 @Nullable final NetworkAgentInfo newSatisfier,
8521 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008522 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008523 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008524 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008525 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008526 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008527 }
James Mattisa076c532020-12-02 14:12:41 -08008528 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008529 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8530 // If this network switch can't be supported gracefully, the request is not
8531 // lingered. This allows letting go of the network sooner to reclaim some
8532 // performance on the new network, since the radio can't do both at the same
8533 // time while preserving good performance.
8534 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8535 }
Chalard Jean24344d72019-12-04 13:32:31 +09008536 } else {
8537 if (VDBG || DDBG) log(" accepting network in place of null");
8538 }
junyulai0ac374f2020-12-14 18:41:52 +08008539
8540 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8541 // and immediately satisfies a request then remove the timer. This will happen for
8542 // all networks except in the case of an underlying network for a VCN.
8543 if (newSatisfier.isNascent()) {
8544 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008545 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008546 }
8547
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008548 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008549 newSatisfier.unlingerRequest(newRequest.requestId);
8550 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008551 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008552 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008553 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008554 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008555 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008556 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008557 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008558 }
James Mattisa076c532020-12-02 14:12:41 -08008559 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008560 }
James Mattisa076c532020-12-02 14:12:41 -08008561 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008562 }
8563
James Mattisa076c532020-12-02 14:12:41 -08008564 /**
8565 * This function is triggered when something can affect what network should satisfy what
8566 * request, and it computes the network reassignment from the passed collection of requests to
8567 * network match to the one that the system should now have. That data is encoded in an
8568 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8569 * satisfier.
8570 *
8571 * After the reassignment is computed, it is applied to the state objects.
8572 *
8573 * @param networkRequests the nri objects to evaluate for possible network reassignment
8574 * @return NetworkReassignment listing of proposed network assignment changes
8575 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008576 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008577 private NetworkReassignment computeNetworkReassignment(
8578 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008579 final NetworkReassignment changes = new NetworkReassignment();
8580
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008581 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008582 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008583 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008584 if (!nai.everConnected) {
8585 continue;
8586 }
Chalard Jean857a1712019-12-10 21:08:07 +09008587 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008588 }
Chalard Jean857a1712019-12-10 21:08:07 +09008589
James Mattisa076c532020-12-02 14:12:41 -08008590 for (final NetworkRequestInfo nri : networkRequests) {
8591 // Non-multilayer listen requests can be ignored.
8592 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8593 continue;
8594 }
8595 NetworkAgentInfo bestNetwork = null;
8596 NetworkRequest bestRequest = null;
8597 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008598 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008599 // Stop evaluating as the highest possible priority request is satisfied.
8600 if (null != bestNetwork) {
8601 bestRequest = req;
8602 break;
8603 }
8604 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008605 if (null == bestNetwork && isDefaultBlocked(nri)) {
8606 // Remove default networking if disallowed for managed default requests.
8607 bestNetwork = mNoServiceNetwork;
8608 }
8609 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008610 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008611 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008612 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008613 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008614 }
8615 return changes;
8616 }
8617
James Mattisa076c532020-12-02 14:12:41 -08008618 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8619 return new HashSet<>(mNetworkRequests.values());
8620 }
8621
Paul Jensenc88b39b2015-06-16 14:27:36 -04008622 /**
James Mattisa076c532020-12-02 14:12:41 -08008623 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008624 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008625 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008626 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008627 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8628 }
8629
8630 /**
8631 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8632 * being disconnected.
8633 */
8634 private void rematchNetworksAndRequests(
8635 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8636 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008637 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008638 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008639 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008640 if (VDBG || DDBG) {
8641 log(changes.debugString());
8642 } else if (DBG) {
8643 log(changes.toString()); // Shorter form, only one line of log
8644 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008645 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008646 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008647 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008648
Chalard Jeand7f762d2019-12-10 19:01:29 +09008649 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008650 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008651 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008652
8653 // Since most of the time there are only 0 or 1 background networks, it would probably
8654 // be more efficient to just use an ArrayList here. TODO : measure performance
8655 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8656 for (final NetworkAgentInfo nai : nais) {
8657 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8658 }
8659
Chalard Jeand7f762d2019-12-10 19:01:29 +09008660 // First, update the lists of satisfied requests in the network agents. This is necessary
8661 // because some code later depends on this state to be correct, most prominently computing
8662 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008663 for (final NetworkReassignment.RequestReassignment event :
8664 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008665 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8666 event.mOldNetworkRequest, event.mNewNetworkRequest,
8667 event.mOldNetwork, event.mNewNetwork,
8668 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008669 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008670
James Mattise3ef1912020-12-20 11:09:58 -08008671 // Process default network changes if applicable.
8672 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008673
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008674 // Notify requested networks are available after the default net is switched, but
8675 // before LegacyTypeTracker sends legacy broadcasts
8676 for (final NetworkReassignment.RequestReassignment event :
8677 changes.getRequestReassignments()) {
8678 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008679 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008680 } else {
James Mattisa076c532020-12-02 14:12:41 -08008681 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008682 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008683 }
8684 }
8685
junyulai0ac374f2020-12-14 18:41:52 +08008686 // Update the inactivity state before processing listen callbacks, because the background
8687 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008688 // just yet though, because they have to be sent after the listens are processed to keep
8689 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008690 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008691 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008692 // Rematching may have altered the inactivity state of some networks, so update all
8693 // inactivity timers. updateInactivityState reads the state from the network agent
8694 // and does nothing if the state has not changed : the source of truth is controlled
8695 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8696 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008697 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008698 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008699 }
8700 }
8701
Chalard Jeanb10ab412019-12-11 14:12:30 +09008702 for (final NetworkAgentInfo nai : nais) {
8703 if (!nai.everConnected) continue;
8704 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008705 // Process listen requests and update capabilities if the background state has
8706 // changed for this network. For consistency with previous behavior, send onLost
8707 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008708 processNewlyLostListenRequests(nai);
8709 if (oldBackground != nai.isBackgroundNetwork()) {
8710 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008711 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008712 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008713 }
8714
junyulai0ac374f2020-12-14 18:41:52 +08008715 for (final NetworkAgentInfo nai : inactiveNetworks) {
8716 // For nascent networks, if connecting with no foreground request, skip broadcasting
8717 // LOSING for backward compatibility. This is typical when mobile data connected while
8718 // wifi connected with mobile data always-on enabled.
8719 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008720 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008721 }
8722
James Mattise3ef1912020-12-20 11:09:58 -08008723 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008724
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008725 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008726 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008727 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008728 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008729 // This network has active linger timers and no requests, but is not
8730 // lingering. Linger it.
8731 //
8732 // One way (the only way?) this can happen if this network is unvalidated
8733 // and became unneeded due to another network improving its score to the
8734 // point where this network will no longer be able to satisfy any requests
8735 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008736 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008737 notifyNetworkLosing(nai, now);
8738 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008739 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008740 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008741 teardownUnneededNetwork(nai);
8742 }
8743 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008744 }
8745 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008746
Chalard Jean62edfd82019-12-02 18:39:29 +09008747 /**
8748 * Apply a change in background state resulting from rematching networks with requests.
8749 *
8750 * During rematch, a network may change background states by starting to satisfy or stopping
8751 * to satisfy a foreground request. Listens don't count for this. When a network changes
8752 * background states, its capabilities need to be updated and callbacks fired for the
8753 * capability change.
8754 *
8755 * @param nai The network that changed background states
8756 */
8757 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8758 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8759 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8760 updateNetworkPermissions(nai, newNc);
8761 nai.getAndSetNetworkCapabilities(newNc);
8762 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8763 }
8764
Chalard Jeanf0344532019-11-19 19:23:38 +09008765 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008766 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008767 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008768 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8769 changes.getReassignment(mDefaultRequest);
8770 final NetworkAgentInfo oldDefaultNetwork =
8771 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8772 final NetworkAgentInfo newDefaultNetwork =
8773 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008774
Chalard Jean5b409c72021-02-04 13:12:59 +09008775 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008776 // Maintain the illusion : since the legacy API only understands one network at a time,
8777 // if the default network changed, apps should see a disconnected broadcast for the
8778 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008779 if (oldDefaultNetwork != null) {
8780 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8781 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008782 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008783 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008784 // The new default network can be newly null if and only if the old default
8785 // network doesn't satisfy the default request any more because it lost a
8786 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008787 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008788 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008789 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008790 }
8791 }
8792
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008793 // Now that all the callbacks have been sent, send the legacy network broadcasts
8794 // as needed. This is necessary so that legacy requests correctly bind dns
8795 // requests to this network. The legacy users are listening for this broadcast
8796 // and will generally do a dns request so they can ensureRouteToHost and if
8797 // they do that before the callbacks happen they'll use the default network.
8798 //
8799 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8800 // callbacks, but if apps can receive the broadcast before the callback, they still might
8801 // have an inconsistent view of networking.
8802 //
8803 // This *does* introduce a race where if the user uses the new api
8804 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8805 // they may get old info. Reverse this after the old startUsing api is removed.
8806 // This is on top of the multiple intent sequencing referenced in the todo above.
8807 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008808 if (nai.everConnected) {
8809 addNetworkToLegacyTypeTracker(nai);
8810 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008811 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008812 }
8813
Chalard Jean0354d8c2021-01-12 10:58:56 +09008814 private void issueNetworkNeeds() {
8815 ensureRunningOnConnectivityServiceThread();
8816 for (final NetworkOfferInfo noi : mNetworkOffers) {
8817 issueNetworkNeeds(noi);
8818 }
8819 }
8820
8821 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8822 ensureRunningOnConnectivityServiceThread();
8823 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8824 informOffer(nri, noi.offer, mNetworkRanker);
8825 }
8826 }
8827
8828 /**
8829 * Inform a NetworkOffer about any new situation of a request.
8830 *
8831 * This function handles updates to offers. A number of events may happen that require
8832 * updating the registrant for this offer about the situation :
8833 * • The offer itself was updated. This may lead the offer to no longer being able
8834 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8835 * or conversely being strengthened enough to beat the satisfier (and therefore
8836 * start being needed)
8837 * • The network satisfying a request changed (including cases where the request
8838 * starts or stops being satisfied). The new network may be a stronger or weaker
8839 * match than the old one, possibly affecting whether the offer is needed.
8840 * • The network satisfying a request updated their score. This may lead the offer
8841 * to no longer be able to beat it if the current satisfier got better, or
8842 * conversely start being a good choice if the current satisfier got weaker.
8843 *
8844 * @param nri The request
8845 * @param offer The offer. This may be an updated offer.
8846 */
8847 private static void informOffer(@NonNull NetworkRequestInfo nri,
8848 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8849 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8850 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008851
8852 // Multi-layer requests have a currently active request, the one being satisfied.
8853 // Since the system will try to bring up a better network than is currently satisfying
8854 // the request, NetworkProviders need to be told the offers matching the requests *above*
8855 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8856 // not needed, and the offer is needed for the active request iff the offer can beat
8857 // the satisfier.
8858 // For non-multilayer requests, the logic above gracefully degenerates to only the
8859 // last case.
8860 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8861 // providers that the offer is needed for this request, until the active request is found.
8862 // In a second phase, deal with the currently active request. In a third phase, inform
8863 // the providers that offer is unneeded for the remaining requests.
8864
8865 // First phase : inform providers of all requests above the active request.
8866 int i;
8867 for (i = 0; nri.mRequests.size() > i; ++i) {
8868 final NetworkRequest request = nri.mRequests.get(i);
8869 if (activeRequest == request) break; // Found the active request : go to phase 2
8870 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8871 // Since this request is higher-priority than the one currently satisfied, if the
8872 // offer can satisfy it, the provider should try and bring up the network for sure ;
8873 // no need to even ask the ranker – an offer that can satisfy is always better than
8874 // no network. Hence tell the provider so unless it already knew.
8875 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8876 offer.onNetworkNeeded(request);
8877 }
8878 }
8879
8880 // Second phase : deal with the active request (if any)
8881 if (null != activeRequest && activeRequest.isRequest()) {
8882 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008883 // If an offer can satisfy the request, it is considered needed if it is currently
8884 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008885 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008886 && satisfier.factorySerialNumber == offer.providerId
8887 && activeRequest.canBeSatisfiedBy(offer.caps);
8888 final boolean newNeeded = currentlyServing
8889 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008890 if (newNeeded != oldNeeded) {
8891 if (newNeeded) {
8892 offer.onNetworkNeeded(activeRequest);
8893 } else {
8894 // The offer used to be able to beat the satisfier. Now it can't.
8895 offer.onNetworkUnneeded(activeRequest);
8896 }
8897 }
8898 }
8899
8900 // Third phase : inform the providers that the offer isn't needed for any request
8901 // below the active one.
8902 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8903 final NetworkRequest request = nri.mRequests.get(i);
8904 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8905 // Since this request is lower-priority than the one currently satisfied, if the
8906 // offer can satisfy it, the provider should not try and bring up the network.
8907 // Hence tell the provider so unless it already knew.
8908 if (offer.neededFor(request)) {
8909 offer.onNetworkUnneeded(request);
8910 }
8911 }
8912 }
8913
Chalard Jean61c79252019-11-07 23:07:32 +09008914 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8915 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8916 NetworkRequest nr = nai.requestAt(i);
8917 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8918 // legacy type tracker filters out repeat adds
8919 mLegacyTypeTracker.add(nr.legacyType, nai);
8920 }
8921 }
8922
8923 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008924 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008925 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8926 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8927 if (nai.isVPN()) {
8928 mLegacyTypeTracker.add(TYPE_VPN, nai);
8929 }
8930 }
8931
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008932 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008933 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008934 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008935 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008936 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008937 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008938
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008939 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008940 // Don't repeat publish.
8941 if (newInetCondition == mDefaultInetConditionPublished) return;
8942
8943 mDefaultInetConditionPublished = newInetCondition;
8944 sendInetConditionBroadcast(nai.networkInfo);
8945 }
8946
Chalard Jeand61375d2020-01-14 22:46:36 +09008947 @NonNull
8948 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8949 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008950 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008951 final boolean suspended =
8952 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8953 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8954 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8955 // state. This is because the network could have been suspended before connecting,
8956 // or it could be disconnecting while being suspended, and in both these cases
8957 // the state should not be overridden. Note that the only detailed state that
8958 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8959 // worry about multiple different substates of CONNECTED.
8960 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8961 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008962 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8963 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8964 // network agent is created, then goes to suspended, then goes out of suspended without
8965 // ever setting connected. Check if network agent is ever connected to update the state.
8966 newInfo.setDetailedState(nai.everConnected
8967 ? NetworkInfo.DetailedState.CONNECTED
8968 : NetworkInfo.DetailedState.CONNECTING,
8969 info.getReason(),
8970 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008971 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008972 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008973 return newInfo;
8974 }
8975
8976 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8977 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8978
Erik Kline99f301b2017-02-15 19:59:17 +09008979 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008980 NetworkInfo oldInfo = null;
8981 synchronized (networkAgent) {
8982 oldInfo = networkAgent.networkInfo;
8983 networkAgent.networkInfo = newInfo;
8984 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008985
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008986 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008987 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8988 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008989 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008990
Robin Leea8c0b6e2016-05-01 23:00:00 +01008991 if (!networkAgent.created
8992 && (state == NetworkInfo.State.CONNECTED
8993 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008994
8995 // A network that has just connected has zero requests and is thus a foreground network.
8996 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8997
Patrick Rohr2857ac42022-01-21 14:58:16 +01008998 // If a rate limit has been configured and is applicable to this network (network
8999 // provides internet connectivity), apply it.
9000 // Note: in case of a system server crash, there is a very small chance that this
9001 // leaves some interfaces rate limited (i.e. if the rate limit had been changed just
9002 // before the crash and was never applied). One solution would be to delete all
9003 // potential tc police filters every time this is called. Since this is an unlikely
9004 // scenario in the first place (and worst case, the interface stays rate limited until
9005 // the device is rebooted), this seems a little overkill.
9006 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9007 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9008 mIngressRateLimit);
9009 }
9010
Luke Huangfdd11f82019-04-09 18:41:49 +08009011 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009012 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009013 // Initialize the network's capabilities to their starting values according to the
9014 // underlying networks. This ensures that the capabilities are correct before
9015 // anything happens to the network.
9016 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009017 }
Paul Jensen74940202014-08-04 12:21:19 -04009018 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009019 networkAgent.onNetworkCreated();
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009020 updateAccessUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009021 }
9022
9023 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
9024 networkAgent.everConnected = true;
9025
lucaslin45e639b2019-04-03 17:09:28 +08009026 // NetworkCapabilities need to be set before sending the private DNS config to
9027 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009028 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9029
Erik Kline9a62f012018-03-21 07:18:33 -07009030 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009031 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9032 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009033
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009034 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9035 // command must be sent after updating LinkProperties to maximize chances of
9036 // NetworkMonitor seeing the correct LinkProperties when starting.
9037 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009038 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009039 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009040 }
Chalard Jeand4900722022-02-06 12:25:38 +09009041 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9042 params.networkAgentConfig = networkAgent.networkAgentConfig;
9043 params.networkCapabilities = networkAgent.networkCapabilities;
9044 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9045 true /* parcelSensitiveFields */);
9046 networkAgent.networkMonitor().notifyNetworkConnected(params);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09009047 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009048
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009049 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9050 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9051 // capabilities, so it only needs to be done once on initial connect, not every time the
9052 // network's capabilities change. Note that we do this before rematching the network,
9053 // so we could decide to tear it down immediately afterwards. That's fine though - on
9054 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9055 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009056 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009057
junyulai0ac374f2020-12-14 18:41:52 +08009058 // Before first rematching networks, put an inactivity timer without any request, this
9059 // allows {@code updateInactivityState} to update the state accordingly and prevent
9060 // tearing down for any {@code unneeded} evaluation in this period.
9061 // Note that the timer will not be rescheduled since the expiry time is
9062 // fixed after connection regardless of the network satisfying other requests or not.
9063 // But it will be removed as soon as the network satisfies a request for the first time.
9064 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9065 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009066 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009067
Paul Jensen05e85ee2014-09-11 11:00:39 -04009068 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009069 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009070
9071 // This has to happen after matching the requests, because callbacks are just requests.
9072 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009073 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009074 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009075 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009076 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009077 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009078 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009079 if (networkAgent.isVPN()) {
9080 // As the active or bound network changes for apps, broadcast the default proxy, as
9081 // apps may need to update their proxy data. This is called after disconnecting from
9082 // VPN to make sure we do not broadcast the old proxy data.
9083 // TODO(b/122649188): send the broadcast only to VPN users.
9084 mProxyTracker.sendProxyBroadcast();
9085 }
Yintang Gu5014b522019-06-18 14:24:32 +08009086 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
9087 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009088 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009089 }
9090 }
9091
Chalard Jean28018572020-12-21 18:36:52 +09009092 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009093 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9094 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009095 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009096 }
9097
Erik Kline99f301b2017-02-15 19:59:17 +09009098 // Notify only this one new request of the current state. Transfer all the
9099 // current state by calling NetworkCapabilities and LinkProperties callbacks
9100 // so that callers can be guaranteed to have as close to atomicity in state
9101 // transfer as can be supported by this current API.
9102 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009103 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009104 if (nri.mPendingIntent != null) {
9105 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9106 // Attempt no subsequent state pushes where intents are involved.
9107 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009108 }
Erik Kline99f301b2017-02-15 19:59:17 +09009109
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009110 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009111 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009112 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9113 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9114 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009115 }
9116
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009117 // Notify the requests on this NAI that the network is now lingered.
9118 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009119 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009120 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9121 }
9122
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009123 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9124 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9125 return vpnBlocked
9126 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9127 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9128 }
9129
9130 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9131 if (blockedReasons == BLOCKED_REASON_NONE) {
9132 mUidBlockedReasons.delete(uid);
9133 } else {
9134 mUidBlockedReasons.put(uid, blockedReasons);
9135 }
9136 }
9137
junyulaif2c67e42018-08-07 19:50:45 +08009138 /**
9139 * Notify of the blocked state apps with a registered callback matching a given NAI.
9140 *
9141 * Unlike other callbacks, blocked status is different between each individual uid. So for
9142 * any given nai, all requests need to be considered according to the uid who filed it.
9143 *
9144 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009145 * @param oldMetered True if the previous network capabilities were metered.
9146 * @param newMetered True if the current network capabilities are metered.
9147 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9148 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009149 */
9150 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009151 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9152 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009153
9154 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9155 NetworkRequest nr = nai.requestAt(i);
9156 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009157
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009158 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9159 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9160 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009161 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009162 : oldVpnBlocked;
9163
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009164 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9165 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9166 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009167 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009168 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009169 }
9170 }
9171 }
9172
9173 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009174 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009175 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009176 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009177 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009178 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009179 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009180 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009181 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009182
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009183 final int oldBlockedState = getBlockedState(
9184 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9185 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9186 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009187 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009188 }
junyulaif2c67e42018-08-07 19:50:45 +08009189 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9190 NetworkRequest nr = nai.requestAt(i);
9191 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009192 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009193 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9194 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009195 }
9196 }
9197 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009198 }
9199
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009200 @VisibleForTesting
9201 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009202 // The NetworkInfo we actually send out has no bearing on the real
9203 // state of affairs. For example, if the default connection is mobile,
9204 // and a request for HIPRI has just gone away, we need to pretend that
9205 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9206 // the state to DISCONNECTED, even though the network is of type MOBILE
9207 // and is still connected.
9208 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9209 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009210 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009211 if (state != DetailedState.DISCONNECTED) {
9212 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009213 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009214 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009215 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009216 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9217 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9218 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9219 if (info.isFailover()) {
9220 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9221 nai.networkInfo.setFailover(false);
9222 }
9223 if (info.getReason() != null) {
9224 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9225 }
9226 if (info.getExtraInfo() != null) {
9227 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9228 }
9229 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009230 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009231 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009232 if (newDefaultAgent != null) {
9233 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9234 newDefaultAgent.networkInfo);
9235 } else {
9236 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9237 }
9238 }
9239 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9240 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009241 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009242 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009243 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009244 }
9245 }
9246 }
9247
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009248 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009249 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009250 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009251 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009252 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009253 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9254 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009255 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9256 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009257 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009258 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009259 } else {
9260 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9261 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009262 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009263 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009264
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009265 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9266 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9267 }
9268
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009269 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009270 * Returns the list of all interfaces that could be used by network traffic that does not
9271 * explicitly specify a network. This includes the default network, but also all VPNs that are
9272 * currently connected.
9273 *
9274 * Must be called on the handler thread.
9275 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009276 @NonNull
9277 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009278 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009279 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009280 final Set<Integer> activeNetIds = new ArraySet<>();
9281 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9282 if (nri.isBeingSatisfied()) {
9283 activeNetIds.add(nri.getSatisfier().network().netId);
9284 }
9285 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009286 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08009287 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009288 defaultNetworks.add(nai.network);
9289 }
9290 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009291 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009292 }
9293
9294 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009295 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9296 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009297 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009298 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009299 ensureRunningOnConnectivityServiceThread();
9300 String activeIface = null;
9301 LinkProperties activeLinkProperties = getActiveLinkProperties();
9302 if (activeLinkProperties != null) {
9303 activeIface = activeLinkProperties.getInterfaceName();
9304 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009305
junyulai2050bed2021-01-23 09:46:34 +08009306 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009307 try {
junyulaide41fc22021-01-22 22:46:01 +08009308 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08009309 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08009310 snapshots.add(snapshot);
9311 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009312 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9313 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009314 } catch (Exception ignored) {
9315 }
9316 }
9317
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009318 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009319 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009320 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009321 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009322 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009323
9324 if (!TextUtils.isEmpty(settingUrl)) {
9325 return settingUrl;
9326 }
9327
9328 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009329 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009330 if (!TextUtils.isEmpty(settingUrl)) {
9331 return settingUrl;
9332 }
9333
9334 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009335 }
9336
9337 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009338 public void startNattKeepalive(Network network, int intervalSeconds,
9339 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009340 enforceKeepalivePermission();
9341 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009342 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009343 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009344 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009345 }
9346
9347 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009348 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009349 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009350 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009351 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009352 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009353 mKeepaliveTracker.startNattKeepalive(
9354 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9355 intervalSeconds, cb,
9356 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9357 } finally {
9358 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9359 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009360 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9361 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009362 }
9363 }
junyulaid05a1922019-01-15 11:32:44 +08009364 }
9365
9366 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009367 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009368 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009369 try {
9370 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009371 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009372 mKeepaliveTracker.startTcpKeepalive(
9373 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9374 } finally {
9375 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9376 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009377 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9378 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009379 }
9380 }
junyulai0835a1e2019-01-08 20:04:33 +08009381 }
9382
9383 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009384 public void stopKeepalive(Network network, int slot) {
9385 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009386 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009387 }
9388
9389 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009390 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009391 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009392
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009393 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009394 final long token = Binder.clearCallingIdentity();
9395 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009396 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9397 UserHandle.getUserHandleForUid(uid))) {
9398 return;
9399 }
9400
Heemin Seogdb8489d2019-06-12 09:21:44 -07009401 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9402 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009403
9404 // Turn airplane mode off
9405 setAirplaneMode(false);
9406
9407 // restore private DNS settings to default mode (opportunistic)
9408 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9409 UserHandle.getUserHandleForUid(uid))) {
9410 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9411 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9412 }
9413
9414 Settings.Global.putString(mContext.getContentResolver(),
9415 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009416 } finally {
9417 Binder.restoreCallingIdentity(token);
9418 }
Stuart Scottd5463642015-04-02 18:00:02 -07009419 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009420
Ricky Wai7097cc92018-01-23 04:09:45 +00009421 @Override
9422 public byte[] getNetworkWatchlistConfigHash() {
9423 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9424 if (nwm == null) {
9425 loge("Unable to get NetworkWatchlistManager");
9426 return null;
9427 }
9428 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9429 return nwm.getWatchlistConfigHash();
9430 }
9431
Hugo Benichibe0c7652016-05-31 16:28:06 +09009432 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009433 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009434 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009435 }
Hugo Benichif4210292017-04-21 15:07:12 +09009436
9437 private static boolean toBool(int encodedBoolean) {
9438 return encodedBoolean != 0; // Only 0 means false.
9439 }
9440
9441 private static int encodeBool(boolean b) {
9442 return b ? 1 : 0;
9443 }
mswest4632928412018-03-12 10:34:34 -07009444
9445 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009446 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9447 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9448 @NonNull String[] args) {
9449 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9450 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009451 }
9452
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009453 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009454 @Override
9455 public int onCommand(String cmd) {
9456 if (cmd == null) {
9457 return handleDefaultCommands(cmd);
9458 }
9459 final PrintWriter pw = getOutPrintWriter();
9460 try {
9461 switch (cmd) {
9462 case "airplane-mode":
9463 final String action = getNextArg();
9464 if ("enable".equals(action)) {
9465 setAirplaneMode(true);
9466 return 0;
9467 } else if ("disable".equals(action)) {
9468 setAirplaneMode(false);
9469 return 0;
9470 } else if (action == null) {
9471 final ContentResolver cr = mContext.getContentResolver();
9472 final int enabled = Settings.Global.getInt(cr,
9473 Settings.Global.AIRPLANE_MODE_ON);
9474 pw.println(enabled == 0 ? "disabled" : "enabled");
9475 return 0;
9476 } else {
9477 onHelp();
9478 return -1;
9479 }
9480 default:
9481 return handleDefaultCommands(cmd);
9482 }
9483 } catch (Exception e) {
9484 pw.println(e);
9485 }
9486 return -1;
9487 }
9488
9489 @Override
9490 public void onHelp() {
9491 PrintWriter pw = getOutPrintWriter();
9492 pw.println("Connectivity service commands:");
9493 pw.println(" help");
9494 pw.println(" Print this help text.");
9495 pw.println(" airplane-mode [enable|disable]");
9496 pw.println(" Turn airplane mode on or off.");
9497 pw.println(" airplane-mode");
9498 pw.println(" Get airplane mode.");
9499 }
9500 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009501
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009502 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009503 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9504 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9505 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009506 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009507 }
9508
9509 /**
9510 * @param connectionInfo the connection to resolve.
9511 * @return {@code uid} if the connection is found and the app has permission to observe it
9512 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9513 * connection is not found.
9514 */
9515 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009516 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9517 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9518 }
9519
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009520 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009521 connectionInfo.local, connectionInfo.remote);
9522
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009523 if (uid == INVALID_UID) return uid; // Not found.
9524
9525 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9526 // VPN, if any, that applies to the UID that owns the connection.
9527 if (checkNetworkStackPermission()) return uid;
9528
9529 final NetworkAgentInfo vpn = getVpnForUid(uid);
9530 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009531 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009532 return INVALID_UID;
9533 }
9534
9535 return uid;
9536 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009537
Benedict Wong493e04b2018-11-09 14:45:34 -08009538 /**
9539 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9540 *
9541 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9542 */
9543 @Override
9544 public IBinder startOrGetTestNetworkService() {
9545 synchronized (mTNSLock) {
9546 TestNetworkService.enforceTestNetworkPermissions(mContext);
9547
9548 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009549 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009550 }
9551
9552 return mTNS;
9553 }
9554 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009555
Cody Kesting73708bf2019-12-18 10:57:50 -08009556 /**
9557 * Handler used for managing all Connectivity Diagnostics related functions.
9558 *
9559 * @see android.net.ConnectivityDiagnosticsManager
9560 *
9561 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9562 */
9563 @VisibleForTesting
9564 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009565 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9566
Cody Kesting73708bf2019-12-18 10:57:50 -08009567 /**
9568 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9569 * android.net.ConnectivityDiagnosticsManager}.
9570 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9571 * NetworkRequestInfo to be registered
9572 */
9573 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9574
9575 /**
9576 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9577 * android.net.ConnectivityDiagnosticsManager}.
9578 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9579 * arg1 = the uid of the caller
9580 */
9581 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9582
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009583 /**
9584 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9585 * after processing {@link #EVENT_NETWORK_TESTED} events.
9586 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9587 * NetworkMonitor.
9588 * data = PersistableBundle of extras passed from NetworkMonitor.
9589 *
9590 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9591 */
9592 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9593
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009594 /**
9595 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9596 * been detected on the network.
9597 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9598 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9599 * arg2 = NetID.
9600 * data = PersistableBundle of extras passed from NetworkMonitor.
9601 */
9602 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9603
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009604 /**
9605 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9606 * the platform. This event will invoke {@link
9607 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9608 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009609 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009610 */
9611 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9612
Cody Kesting73708bf2019-12-18 10:57:50 -08009613 private ConnectivityDiagnosticsHandler(Looper looper) {
9614 super(looper);
9615 }
9616
9617 @Override
9618 public void handleMessage(Message msg) {
9619 switch (msg.what) {
9620 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9621 handleRegisterConnectivityDiagnosticsCallback(
9622 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9623 break;
9624 }
9625 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9626 handleUnregisterConnectivityDiagnosticsCallback(
9627 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9628 break;
9629 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009630 case EVENT_NETWORK_TESTED: {
9631 final ConnectivityReportEvent reportEvent =
9632 (ConnectivityReportEvent) msg.obj;
9633
Aaron Huang959d3642021-01-21 15:47:41 +08009634 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009635 break;
9636 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009637 case EVENT_DATA_STALL_SUSPECTED: {
9638 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009639 final Pair<Long, PersistableBundle> arg =
9640 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009641 if (nai == null) break;
9642
Aaron Huang959d3642021-01-21 15:47:41 +08009643 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009644 break;
9645 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009646 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009647 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009648 break;
9649 }
9650 default: {
9651 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9652 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009653 }
9654 }
9655 }
9656
9657 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9658 @VisibleForTesting
9659 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9660 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9661 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009662 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009663
9664 @VisibleForTesting
9665 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009666 @NonNull IConnectivityDiagnosticsCallback cb,
9667 @NonNull NetworkRequestInfo nri,
9668 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009669 mCb = cb;
9670 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009671 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009672 }
9673
9674 @Override
9675 public void binderDied() {
9676 log("ConnectivityDiagnosticsCallback IBinder died.");
9677 unregisterConnectivityDiagnosticsCallback(mCb);
9678 }
9679 }
9680
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009681 /**
9682 * Class used for sending information from {@link
9683 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9684 */
9685 private static class NetworkTestedResults {
9686 private final int mNetId;
9687 private final int mTestResult;
9688 private final long mTimestampMillis;
9689 @Nullable private final String mRedirectUrl;
9690
9691 private NetworkTestedResults(
9692 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9693 mNetId = netId;
9694 mTestResult = testResult;
9695 mTimestampMillis = timestampMillis;
9696 mRedirectUrl = redirectUrl;
9697 }
9698 }
9699
9700 /**
9701 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9702 * ConnectivityDiagnosticsHandler}.
9703 */
9704 private static class ConnectivityReportEvent {
9705 private final long mTimestampMillis;
9706 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009707 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009708
Aaron Huang959d3642021-01-21 15:47:41 +08009709 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9710 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009711 mTimestampMillis = timestampMillis;
9712 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009713 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009714 }
9715 }
9716
Cody Kestingf1120be2020-08-03 18:01:40 -07009717 /**
9718 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9719 * ConnectivityDiagnosticsHandler}.
9720 */
9721 private static class ReportedNetworkConnectivityInfo {
9722 public final boolean hasConnectivity;
9723 public final boolean isNetworkRevalidating;
9724 public final int reporterUid;
9725 @NonNull public final NetworkAgentInfo nai;
9726
9727 private ReportedNetworkConnectivityInfo(
9728 boolean hasConnectivity,
9729 boolean isNetworkRevalidating,
9730 int reporterUid,
9731 @NonNull NetworkAgentInfo nai) {
9732 this.hasConnectivity = hasConnectivity;
9733 this.isNetworkRevalidating = isNetworkRevalidating;
9734 this.reporterUid = reporterUid;
9735 this.nai = nai;
9736 }
9737 }
9738
Cody Kesting73708bf2019-12-18 10:57:50 -08009739 private void handleRegisterConnectivityDiagnosticsCallback(
9740 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9741 ensureRunningOnConnectivityServiceThread();
9742
9743 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009744 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009745 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9746
James Mattis64b8b0f2020-11-24 17:40:49 -08009747 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9748 // confusing for these networks to change when an NRI is satisfied in another layer.
9749 if (nri.isMultilayerRequest()) {
9750 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9751 + "network requests.");
9752 }
9753
Cody Kesting73708bf2019-12-18 10:57:50 -08009754 // This means that the client registered the same callback multiple times. Do
9755 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009756 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009757 if (VDBG) log("Diagnostics callback is already registered");
9758
9759 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9760 // incremented when the NetworkRequestInfo is created as part of
9761 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009762 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009763 return;
9764 }
9765
Cody Kesting31f1ff62020-03-05 10:46:02 -08009766 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009767
9768 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009769 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009770 } catch (RemoteException e) {
9771 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009772 return;
9773 }
9774
9775 // Once registered, provide ConnectivityReports for matching Networks
9776 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9777 synchronized (mNetworkForNetId) {
9778 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9779 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009780 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9781 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009782 matchingNetworks.add(nai);
9783 }
9784 }
9785 }
9786 for (final NetworkAgentInfo nai : matchingNetworks) {
9787 final ConnectivityReport report = nai.getConnectivityReport();
9788 if (report == null) {
9789 continue;
9790 }
9791 if (!checkConnectivityDiagnosticsPermissions(
9792 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9793 continue;
9794 }
9795
9796 try {
9797 cb.onConnectivityReportAvailable(report);
9798 } catch (RemoteException e) {
9799 // Exception while sending the ConnectivityReport. Move on to the next network.
9800 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009801 }
9802 }
9803
9804 private void handleUnregisterConnectivityDiagnosticsCallback(
9805 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9806 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009807 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009808
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009809 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9810 mConnectivityDiagnosticsCallbacks.remove(iCb);
9811 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009812 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9813 return;
9814 }
9815
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009816 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009817
Cody Kesting70fa2b22020-12-02 12:16:56 -08009818 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9819 // (if the Binder died)
9820 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9821 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009822 return;
9823 }
9824
Cody Kesting46cb1672020-03-04 13:35:20 -08009825 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9826 // incremented when the NetworkRequestInfo is created as part of
9827 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009828 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009829
Cody Kesting31f1ff62020-03-05 10:46:02 -08009830 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009831 }
9832
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009833 private void handleNetworkTestedWithExtras(
9834 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9835 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009836 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009837 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009838 final ConnectivityReport report =
9839 new ConnectivityReport(
9840 reportEvent.mNai.network,
9841 reportEvent.mTimestampMillis,
9842 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009843 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009844 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009845 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009846
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009847 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009848 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009849 for (final IConnectivityDiagnosticsCallback cb : results) {
9850 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009851 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009852 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009853 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009854 }
9855 }
9856 }
9857
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009858 private void handleDataStallSuspected(
9859 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9860 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009861 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009862 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009863 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009864 new DataStallReport(
9865 nai.network,
9866 timestampMillis,
9867 detectionMethod,
9868 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009869 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009870 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009871 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009872 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009873 for (final IConnectivityDiagnosticsCallback cb : results) {
9874 try {
9875 cb.onDataStallSuspected(report);
9876 } catch (RemoteException ex) {
9877 loge("Error invoking onDataStallSuspected", ex);
9878 }
9879 }
9880 }
9881
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009882 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009883 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9884 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9885 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9886
9887 // If the Network is being re-validated as a result of this call to
9888 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9889 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009890 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009891 getMatchingPermissionedCallbacks(
9892 nai,
9893 reportedNetworkConnectivityInfo.isNetworkRevalidating
9894 ? Process.INVALID_UID
9895 : reportedNetworkConnectivityInfo.reporterUid);
9896
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009897 for (final IConnectivityDiagnosticsCallback cb : results) {
9898 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009899 cb.onNetworkConnectivityReported(
9900 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009901 } catch (RemoteException ex) {
9902 loge("Error invoking onNetworkConnectivityReported", ex);
9903 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009904
9905 // If the Network isn't re-validating, also provide the cached report. If there is no
9906 // cached report, the Network is still being validated and a report will be sent once
9907 // validation is complete. Note that networks which never undergo validation will still
9908 // have a cached ConnectivityReport with RESULT_SKIPPED.
9909 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9910 try {
9911 cb.onConnectivityReportAvailable(cachedReport);
9912 } catch (RemoteException ex) {
9913 loge("Error invoking onConnectivityReportAvailable", ex);
9914 }
9915 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009916 }
9917 }
9918
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009919 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009920 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9921 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009922 sanitized.setUids(null);
9923 sanitized.setAdministratorUids(new int[0]);
9924 sanitized.setOwnerUid(Process.INVALID_UID);
9925 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009926 }
9927
Cody Kestingf1120be2020-08-03 18:01:40 -07009928 /**
9929 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9930 *
9931 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9932 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009933 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009934 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009935 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009936 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009937 mConnectivityDiagnosticsCallbacks.entrySet()) {
9938 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9939 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009940
James Mattis64b8b0f2020-11-24 17:40:49 -08009941 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009942 if (!nai.satisfies(nri.mRequests.get(0))) {
9943 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009944 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009945
9946 // UID for this callback must either be:
9947 // - INVALID_UID (which sends callbacks to all UIDs), or
9948 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9949 // notified as a result)
9950 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9951 continue;
9952 }
9953
9954 if (!checkConnectivityDiagnosticsPermissions(
9955 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9956 continue;
9957 }
9958
9959 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009960 }
9961 return results;
9962 }
9963
Cody Kesting7474f672021-05-11 14:22:40 -07009964 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9965 @NonNull NetworkAgentInfo nai) {
9966 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9967 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9968 }
9969
Cody Kesting160ef392021-05-05 13:17:22 -07009970 private boolean hasLocationPermission(String packageName, int uid) {
9971 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9972 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9973 // call in a try-catch.
9974 try {
9975 if (!mLocationPermissionChecker.checkLocationPermission(
9976 packageName, null /* featureId */, uid, null /* message */)) {
9977 return false;
9978 }
9979 } catch (SecurityException e) {
9980 return false;
9981 }
9982
9983 return true;
9984 }
9985
9986 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9987 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009988 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009989 && virtual.networkCapabilities.getOwnerUid() == uid
9990 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9991 return true;
9992 }
9993 }
9994
9995 return false;
9996 }
9997
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009998 @VisibleForTesting
9999 boolean checkConnectivityDiagnosticsPermissions(
10000 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10001 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10002 return true;
10003 }
10004
Cody Kesting160ef392021-05-05 13:17:22 -070010005 // Administrator UIDs also contains the Owner UID
10006 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10007 if (!CollectionUtils.contains(administratorUids, callbackUid)
10008 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010009 return false;
10010 }
10011
Cody Kesting7474f672021-05-11 14:22:40 -070010012 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10013 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010014 }
10015
Cody Kestingd199a9d2019-12-17 12:55:28 -080010016 @Override
10017 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010018 @NonNull IConnectivityDiagnosticsCallback callback,
10019 @NonNull NetworkRequest request,
10020 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010021 Objects.requireNonNull(callback, "callback must not be null");
10022 Objects.requireNonNull(request, "request must not be null");
10023 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10024
Cody Kesting73708bf2019-12-18 10:57:50 -080010025 if (request.legacyType != TYPE_NONE) {
10026 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10027 + " Please use NetworkCapabilities instead.");
10028 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010029 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010030 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010031
10032 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10033 // and administrator uids to be safe.
10034 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010035 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010036
10037 final NetworkRequest requestWithId =
10038 new NetworkRequest(
10039 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10040
10041 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10042 //
10043 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10044 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10045 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010046 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010047 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010048 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010049
10050 mConnectivityDiagnosticsHandler.sendMessage(
10051 mConnectivityDiagnosticsHandler.obtainMessage(
10052 ConnectivityDiagnosticsHandler
10053 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10054 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010055 }
10056
10057 @Override
10058 public void unregisterConnectivityDiagnosticsCallback(
10059 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010060 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010061 mConnectivityDiagnosticsHandler.sendMessage(
10062 mConnectivityDiagnosticsHandler.obtainMessage(
10063 ConnectivityDiagnosticsHandler
10064 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010065 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010066 0,
10067 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010068 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010069
10070 @Override
10071 public void simulateDataStall(int detectionMethod, long timestampMillis,
10072 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010073 Objects.requireNonNull(network, "network must not be null");
10074 Objects.requireNonNull(extras, "extras must not be null");
10075
Cody Kestingf53a0752020-04-15 12:33:28 -070010076 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
10077 android.Manifest.permission.NETWORK_STACK);
10078 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10079 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010080 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010081 }
10082
10083 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010084 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010085 throw new SecurityException("Data Stall simulation is only possible for network "
10086 + "creators");
10087 }
10088
Cody Kesting652e3ec2020-05-21 12:08:21 -070010089 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10090 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10091 // Data Stall information as a DataStallReportParcelable and passing to
10092 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10093 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010094 final DataStallReportParcelable p = new DataStallReportParcelable();
10095 p.timestampMillis = timestampMillis;
10096 p.detectionMethod = detectionMethod;
10097
10098 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10099 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10100 }
10101 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10102 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10103 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10104 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10105 }
10106
Serik Beketayevec8ad212020-12-07 22:43:07 -080010107 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010108 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010109
lucaslin66f44212021-02-23 01:12:55 +080010110 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10111 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010112 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010113 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010114 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010115 }
lucaslin37a16d92021-01-21 19:48:09 +080010116
10117 @Override
10118 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010119 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010120 nai.clatd.interfaceLinkStateChanged(iface, up);
10121 }
10122 }
10123
10124 @Override
10125 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010126 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010127 nai.clatd.interfaceRemoved(iface);
10128 }
lucaslin66f44212021-02-23 01:12:55 +080010129 }
10130 }
10131
lucaslin1a8b4c62021-01-21 02:02:55 +080010132 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10133
10134 /**
10135 * Class used for updating network activity tracking with netd and notify network activity
10136 * changes.
10137 */
10138 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010139 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010140 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010141 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010142 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10143 new RemoteCallbackList<>();
10144 // Indicate the current system default network activity is active or not.
10145 @GuardedBy("mActiveIdleTimers")
10146 private boolean mNetworkActive;
10147 @GuardedBy("mActiveIdleTimers")
10148 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
10149 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010150
lucaslin1193a5d2021-01-21 02:04:15 +080010151 private class IdleTimerParams {
10152 public final int timeout;
10153 public final int transportType;
10154
10155 IdleTimerParams(int timeout, int transport) {
10156 this.timeout = timeout;
10157 this.transportType = transport;
10158 }
10159 }
10160
10161 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010162 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010163 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010164 mNetd = netd;
10165 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010166 }
10167
lucaslin66f44212021-02-23 01:12:55 +080010168 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10169 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10170 synchronized (mActiveIdleTimers) {
10171 mNetworkActive = active;
10172 // If there are no idle timers, it means that system is not monitoring
10173 // activity, so the system default network for those default network
10174 // unspecified apps is always considered active.
10175 //
10176 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10177 // any network activity change event. Whenever this event is received,
10178 // the mActiveIdleTimers should be always not empty. The legacy behavior
10179 // is no-op. Remove to refer to mNetworkActive only.
10180 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10181 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10182 }
10183 }
10184 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010185
lucaslin1193a5d2021-01-21 02:04:15 +080010186 // The network activity should only be updated from ConnectivityService handler thread
10187 // when mActiveIdleTimers lock is held.
10188 @GuardedBy("mActiveIdleTimers")
10189 private void reportNetworkActive() {
10190 final int length = mNetworkActivityListeners.beginBroadcast();
10191 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10192 try {
10193 for (int i = 0; i < length; i++) {
10194 try {
10195 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10196 } catch (RemoteException | RuntimeException e) {
10197 loge("Fail to send network activie to listener " + e);
10198 }
10199 }
10200 } finally {
10201 mNetworkActivityListeners.finishBroadcast();
10202 }
10203 }
10204
10205 @GuardedBy("mActiveIdleTimers")
10206 public void handleReportNetworkActivity() {
10207 synchronized (mActiveIdleTimers) {
10208 reportNetworkActive();
10209 }
10210 }
10211
lucaslin1a8b4c62021-01-21 02:02:55 +080010212 // This is deprecated and only to support legacy use cases.
10213 private int transportTypeToLegacyType(int type) {
10214 switch (type) {
10215 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010216 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010217 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010218 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010219 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010220 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010221 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010222 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010223 default:
10224 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10225 }
10226 return ConnectivityManager.TYPE_NONE;
10227 }
10228
10229 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10230 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10231 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10232 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10233 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10234 final long ident = Binder.clearCallingIdentity();
10235 try {
10236 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10237 RECEIVE_DATA_ACTIVITY_CHANGE,
10238 null /* resultReceiver */,
10239 null /* scheduler */,
10240 0 /* initialCode */,
10241 null /* initialData */,
10242 null /* initialExtra */);
10243 } finally {
10244 Binder.restoreCallingIdentity(ident);
10245 }
10246 }
10247
10248 /**
10249 * Setup data activity tracking for the given network.
10250 *
10251 * Every {@code setupDataActivityTracking} should be paired with a
10252 * {@link #removeDataActivityTracking} for cleanup.
10253 */
10254 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10255 final String iface = networkAgent.linkProperties.getInterfaceName();
10256
10257 final int timeout;
10258 final int type;
10259
10260 if (networkAgent.networkCapabilities.hasTransport(
10261 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10262 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010263 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010264 10);
10265 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10266 } else if (networkAgent.networkCapabilities.hasTransport(
10267 NetworkCapabilities.TRANSPORT_WIFI)) {
10268 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010269 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010270 15);
10271 type = NetworkCapabilities.TRANSPORT_WIFI;
10272 } else {
10273 return; // do not track any other networks
10274 }
10275
lucaslinb961efc2021-01-21 02:03:17 +080010276 updateRadioPowerState(true /* isActive */, type);
10277
lucaslin1a8b4c62021-01-21 02:02:55 +080010278 if (timeout > 0 && iface != null) {
10279 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010280 synchronized (mActiveIdleTimers) {
10281 // Networks start up.
10282 mNetworkActive = true;
10283 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10284 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10285 reportNetworkActive();
10286 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010287 } catch (Exception e) {
10288 // You shall not crash!
10289 loge("Exception in setupDataActivityTracking " + e);
10290 }
10291 }
10292 }
10293
10294 /**
10295 * Remove data activity tracking when network disconnects.
10296 */
10297 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10298 final String iface = networkAgent.linkProperties.getInterfaceName();
10299 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10300
lucaslinb961efc2021-01-21 02:03:17 +080010301 if (iface == null) return;
10302
10303 final int type;
10304 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10305 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10306 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10307 type = NetworkCapabilities.TRANSPORT_WIFI;
10308 } else {
10309 return; // do not track any other networks
10310 }
10311
10312 try {
10313 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010314 synchronized (mActiveIdleTimers) {
10315 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10316 // The call fails silently if no idle timer setup for this interface
10317 mNetd.idletimerRemoveInterface(iface, params.timeout,
10318 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010319 }
lucaslinb961efc2021-01-21 02:03:17 +080010320 } catch (Exception e) {
10321 // You shall not crash!
10322 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010323 }
10324 }
10325
10326 /**
10327 * Update data activity tracking when network state is updated.
10328 */
10329 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10330 NetworkAgentInfo oldNetwork) {
10331 if (newNetwork != null) {
10332 setupDataActivityTracking(newNetwork);
10333 }
10334 if (oldNetwork != null) {
10335 removeDataActivityTracking(oldNetwork);
10336 }
10337 }
lucaslinb961efc2021-01-21 02:03:17 +080010338
10339 private void updateRadioPowerState(boolean isActive, int transportType) {
10340 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10341 switch (transportType) {
10342 case NetworkCapabilities.TRANSPORT_CELLULAR:
10343 bs.reportMobileRadioPowerState(isActive, NO_UID);
10344 break;
10345 case NetworkCapabilities.TRANSPORT_WIFI:
10346 bs.reportWifiRadioPowerState(isActive, NO_UID);
10347 break;
10348 default:
10349 logw("Untracked transport type:" + transportType);
10350 }
10351 }
lucaslin1193a5d2021-01-21 02:04:15 +080010352
10353 public boolean isDefaultNetworkActive() {
10354 synchronized (mActiveIdleTimers) {
10355 // If there are no idle timers, it means that system is not monitoring activity,
10356 // so the default network is always considered active.
10357 //
10358 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10359 // tracking is disabled (negative idle timer value configured), or no active default
10360 // network. In the latter case, this reports active but it should report inactive.
10361 return mNetworkActive || mActiveIdleTimers.isEmpty();
10362 }
10363 }
10364
10365 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10366 mNetworkActivityListeners.register(l);
10367 }
10368
10369 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10370 mNetworkActivityListeners.unregister(l);
10371 }
lucaslin012f7a12021-01-21 02:04:35 +080010372
10373 public void dump(IndentingPrintWriter pw) {
10374 synchronized (mActiveIdleTimers) {
10375 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10376 pw.println("Idle timers:");
10377 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10378 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10379 final IdleTimerParams params = ent.getValue();
10380 pw.print(" timeout="); pw.print(params.timeout);
10381 pw.print(" type="); pw.println(params.transportType);
10382 }
10383 }
10384 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010385 }
James Mattis47db0582021-01-01 14:13:35 -080010386
Daniel Brightf9e945b2020-06-15 16:10:01 -070010387 /**
10388 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10389 *
10390 * @param socketInfo the socket information
10391 * @param callback the callback to register
10392 */
10393 @Override
10394 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10395 @NonNull final IQosCallback callback) {
10396 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10397 if (nai == null || nai.networkCapabilities == null) {
10398 try {
10399 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10400 } catch (final RemoteException ex) {
10401 loge("registerQosCallbackInternal: RemoteException", ex);
10402 }
10403 return;
10404 }
10405 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10406 }
10407
10408 /**
10409 * Register a {@link IQosCallback} with base {@link QosFilter}.
10410 *
10411 * @param filter the filter to register
10412 * @param callback the callback to register
10413 * @param nai the agent information related to the filter's network
10414 */
10415 @VisibleForTesting
10416 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10417 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10418 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10419 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10420
10421 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10422 enforceConnectivityRestrictedNetworksPermission();
10423 }
10424 mQosCallbackTracker.registerCallback(callback, filter, nai);
10425 }
10426
10427 /**
10428 * Unregisters the given callback.
10429 *
10430 * @param callback the callback to unregister
10431 */
10432 @Override
10433 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010434 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010435 mQosCallbackTracker.unregisterCallback(callback);
10436 }
James Mattis47db0582021-01-01 14:13:35 -080010437
James Mattis45d81842021-01-10 14:24:24 -080010438 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010439 * Request that a user profile is put by default on a network matching a given preference.
10440 *
10441 * See the documentation for the individual preferences for a description of the supported
10442 * behaviors.
10443 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010444 * @param profile the user profile for whih the preference is being set.
10445 * @param preferences the list of profile network preferences for the
10446 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010447 * @param listener an optional listener to listen for completion of the operation.
10448 */
10449 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010450 public void setProfileNetworkPreferences(
10451 @NonNull final UserHandle profile,
10452 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010453 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010454 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010455 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010456
10457 if (preferences.size() == 0) {
10458 preferences.add((new ProfileNetworkPreference.Builder()).build());
10459 }
10460
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010461 PermissionUtils.enforceNetworkStackPermission(mContext);
10462 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010463 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010464 }
10465 if (profile.getIdentifier() < 0) {
10466 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10467 + "UserHandle.CURRENT not supported)");
10468 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010469 final UserManager um = mContext.getSystemService(UserManager.class);
10470 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010471 throw new IllegalArgumentException("Profile must be a managed profile");
10472 }
paulhuaa0743d2021-05-26 21:56:03 +080010473
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010474 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10475 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010476 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010477 for (final ProfileNetworkPreference preference : preferences) {
10478 final NetworkCapabilities nc;
10479 switch (preference.getPreference()) {
10480 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10481 nc = null;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010482 if (preference.getPreferenceEnterpriseId() != 0) {
10483 throw new IllegalArgumentException(
10484 "Invalid enterprise identifier in setProfileNetworkPreferences");
10485 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010486 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010487 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10488 allowFallback = false;
10489 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010490 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010491 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10492 throw new IllegalArgumentException(
10493 "Invalid enterprise identifier in setProfileNetworkPreferences");
10494 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010495 final Set<UidRange> uidRangeSet =
10496 getUidListToBeAppliedForNetworkPreference(profile, preference);
10497 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10498 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10499 } else {
10500 throw new IllegalArgumentException(
10501 "Overlapping uid range in setProfileNetworkPreferences");
10502 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010503 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010504 nc.addEnterpriseId(
10505 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010506 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10507 break;
10508 default:
10509 throw new IllegalArgumentException(
10510 "Invalid preference in setProfileNetworkPreferences");
10511 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010512 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10513 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010514 }
10515 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010516 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010517 }
10518
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010519 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10520 @NonNull final UserHandle profile,
10521 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10522 final UidRange profileUids = UidRange.createForUser(profile);
10523 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10524 profileNetworkPreference.getIncludedUids());
10525 if (uidRangeSet.size() > 0) {
10526 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10527 throw new IllegalArgumentException(
10528 "Allow uid range is outside the uid range of profile.");
10529 }
10530 } else {
10531 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10532 profileNetworkPreference.getExcludedUids());
10533 if (disallowUidRangeSet.size() > 0) {
10534 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10535 throw new IllegalArgumentException(
10536 "disallow uid range is outside the uid range of profile.");
10537 }
10538 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10539 disallowUidRangeSet);
10540 } else {
10541 uidRangeSet = new ArraySet<UidRange>();
10542 uidRangeSet.add(profileUids);
10543 }
10544 }
10545 return uidRangeSet;
10546 }
10547
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010548 private boolean isEnterpriseIdentifierValid(
10549 @NetworkCapabilities.EnterpriseId int identifier) {
10550 if ((identifier >= NET_ENTERPRISE_ID_1)
10551 && (identifier <= NET_ENTERPRISE_ID_5)) {
10552 return true;
10553 }
10554 return false;
10555 }
10556
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010557 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10558 @Nullable final NetworkCapabilities nc) {
10559 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10560 ensureRequestableCapabilities(nc);
10561 }
10562
10563 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010564 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010565 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010566 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010567 // The NRI for a user should contain the request for capabilities.
10568 // If fallback to default network is needed then NRI should include
10569 // the request for the default network. Create an image of it to
10570 // have the correct UIDs in it (also a request can only be part of one NRI, because
10571 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010572 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10573 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010574 if (pref.allowFallback) {
10575 nrs.add(createDefaultInternetRequestForTransport(
10576 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10577 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010578 if (VDBG) {
10579 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10580 pref.capabilities.getUids()));
10581 }
10582
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010583 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010584 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010585 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010586 result.add(nri);
10587 }
10588 return result;
10589 }
10590
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010591 /**
10592 * Compare if the given UID range sets have the same UIDs.
10593 *
10594 */
10595 private boolean isRangeAlreadyInPreferenceList(
10596 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10597 @NonNull Set<UidRange> uidRangeSet) {
10598 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10599 return false;
10600 }
10601 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10602 if (UidRangeUtils.doesRangeSetOverlap(
10603 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10604 return true;
10605 }
10606 }
10607 return false;
10608 }
10609
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010610 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010611 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010612 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010613 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10614 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10615 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10616 }
paulhu74128522021-09-28 02:29:03 +000010617 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10618 addPerAppDefaultNetworkRequests(
10619 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010620 // Finally, rematch.
10621 rematchAllNetworksAndRequests();
10622
10623 if (null != listener) {
10624 try {
10625 listener.onComplete();
10626 } catch (RemoteException e) {
10627 loge("Listener for setProfileNetworkPreference has died");
10628 }
10629 }
10630 }
10631
paulhu51f77dc2021-06-07 02:34:20 +000010632 @VisibleForTesting
10633 @NonNull
10634 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10635 @NonNull final Set<Integer> uids) {
10636 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10637 if (uids.size() == 0) {
10638 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10639 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10640 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10641 return nris;
10642 }
10643
10644 final List<NetworkRequest> requests = new ArrayList<>();
10645 // The NRI should be comprised of two layers:
10646 // - The request for the mobile network preferred.
10647 // - The request for the default network, for fallback.
10648 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010649 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010650 requests.add(createDefaultInternetRequestForTransport(
10651 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10652 final Set<UidRange> ranges = new ArraySet<>();
10653 for (final int uid : uids) {
10654 ranges.add(new UidRange(uid, uid));
10655 }
10656 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010657 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010658 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010659 return nris;
10660 }
10661
10662 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010663 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010664 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10665 addPerAppDefaultNetworkRequests(
10666 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010667 // Finally, rematch.
10668 rematchAllNetworksAndRequests();
10669 }
10670
Patrick Rohr2857ac42022-01-21 14:58:16 +010010671 private void handleIngressRateLimitChanged() {
10672 final long oldIngressRateLimit = mIngressRateLimit;
10673 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10674 mContext);
10675 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10676 if (canNetworkBeRateLimited(networkAgent)) {
10677 // If rate limit has previously been enabled, remove the old limit first.
10678 if (oldIngressRateLimit >= 0) {
10679 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10680 }
10681 if (mIngressRateLimit >= 0) {
10682 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10683 mIngressRateLimit);
10684 }
10685 }
10686 }
10687 }
10688
10689 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010690 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10691 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10692 // internet connectivity can be rate limited.
10693 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10694 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010695 return false;
10696 }
10697
10698 final String iface = networkAgent.linkProperties.getInterfaceName();
10699 if (iface == null) {
10700 // This can never happen.
10701 logwtf("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
10702 return false;
10703 }
10704 return true;
10705 }
10706
James Mattis45d81842021-01-10 14:24:24 -080010707 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010708 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10709 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010710 }
10711
10712 /**
10713 * Used by automotive devices to set the network preferences used to direct traffic at an
10714 * application level as per the given OemNetworkPreferences. An example use-case would be an
10715 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10716 * vehicle via a particular network.
10717 *
10718 * Calling this will overwrite the existing preference.
10719 *
James Mattisda32cfe2021-01-26 16:23:52 -080010720 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010721 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010722 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010723 */
James Mattis47db0582021-01-01 14:13:35 -080010724 @Override
James Mattis45d81842021-01-10 14:24:24 -080010725 public void setOemNetworkPreference(
10726 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010727 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010728
James Mattisfa270db2021-05-31 17:11:10 -070010729 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10730 // Only bypass the permission/device checks if this is a valid test request.
10731 if (isValidTestOemNetworkPreference(preference)) {
10732 enforceManageTestNetworksPermission();
10733 } else {
10734 enforceAutomotiveDevice();
10735 enforceOemNetworkPreferencesPermission();
10736 validateOemNetworkPreferences(preference);
10737 }
James Mattis45d81842021-01-10 14:24:24 -080010738
James Mattis45d81842021-01-10 14:24:24 -080010739 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10740 new Pair<>(preference, listener)));
10741 }
10742
James Mattisfa270db2021-05-31 17:11:10 -070010743 /**
10744 * Check the validity of an OEM network preference to be used for testing purposes.
10745 * @param preference the preference to validate
10746 * @return true if this is a valid OEM network preference test request.
10747 */
10748 private boolean isValidTestOemNetworkPreference(
10749 @NonNull final OemNetworkPreferences preference) {
10750 // Allow for clearing of an existing OemNetworkPreference used for testing.
10751 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10752 // changes after this check is complete. This is an unlikely scenario as calling of this API
10753 // is controlled by the OEM therefore the added complexity is not worth adding given those
10754 // circumstances. That said, it is an edge case to be aware of hence this comment.
10755 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10756 && isTestOemNetworkPreference(mOemNetworkPreferences);
10757 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10758 }
10759
10760 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10761 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10762 return prefMap.size() == 1
10763 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10764 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10765 }
10766
James Mattis45d81842021-01-10 14:24:24 -080010767 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10768 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10769 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010770 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10771 throw new IllegalArgumentException(
10772 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10773 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010774 }
10775 }
10776 }
10777
10778 private void handleSetOemNetworkPreference(
10779 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010780 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010781 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10782 if (DBG) {
10783 log("set OEM network preferences :" + preference.toString());
10784 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010785
James Mattiscb1e0362021-04-06 17:07:42 -070010786 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010787 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10788 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10789 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010790 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010791
10792 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010793 try {
10794 listener.onComplete();
10795 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010796 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010797 }
James Mattis45d81842021-01-10 14:24:24 -080010798 }
10799 }
10800
paulhu74128522021-09-28 02:29:03 +000010801 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010802 // Skip the requests which are set by other network preference. Because the uid range rules
10803 // should stay in netd.
10804 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010805 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010806 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010807 }
10808
James Mattis3ce3d3c2021-02-09 18:18:28 -080010809 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10810 ensureRunningOnConnectivityServiceThread();
10811 mDefaultNetworkRequests.addAll(nris);
10812 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10813 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010814 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010815 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10816 nrisToRegister.addAll(
10817 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10818 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010819 }
10820
10821 /**
10822 * All current requests that are tracking the default network need to be assessed as to whether
10823 * or not the current set of per-application default requests will be changing their default
10824 * network. If so, those requests will need to be updated so that they will send callbacks for
10825 * default network changes at the appropriate time. Additionally, those requests tracking the
10826 * default that were previously updated by this flow will need to be reassessed.
10827 * @return the nris which will need to be updated.
10828 */
10829 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10830 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10831 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10832 // same nri in the map's values for each of its NetworkRequest objects.
10833 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010834 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010835 // Include this nri if it is currently being tracked.
10836 if (isPerAppTrackedNri(nri)) {
10837 defaultCallbackRequests.add(nri);
10838 continue;
10839 }
10840 // We only track callbacks for requests tracking the default.
10841 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10842 continue;
10843 }
10844 // Include this nri if it will be tracked by the new per-app default requests.
10845 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010846 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010847 if (isNriGoingToBeTracked) {
10848 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010849 }
10850 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010851 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010852 }
10853
James Mattis3ce3d3c2021-02-09 18:18:28 -080010854 /**
10855 * Create nris for those network requests that are currently tracking the default network that
10856 * are being controlled by a per-application default.
10857 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10858 * foundation when creating the nri. Important items include the calling uid's original
10859 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10860 * requests are assumed to have already been validated as needing to be updated.
10861 * @return the Set of nris to use when registering network requests.
10862 */
10863 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10864 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10865 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10866 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10867 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010868 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010869
Chalard Jean9473c982021-07-29 20:03:04 +090010870 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010871 if (trackingNri == mDefaultRequest) {
10872 callbackRequestsToRegister.add(new NetworkRequestInfo(
10873 callbackRequest,
10874 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10875 continue;
10876 }
10877
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010878 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010879 callbackRequestsToRegister.add(new NetworkRequestInfo(
10880 callbackRequest,
10881 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010882 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010883 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010884 }
10885 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010886 }
10887
Chalard Jean17215832021-03-01 14:06:28 +090010888 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10889 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010890 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010891 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010892 }
10893 }
10894
James Mattis45d81842021-01-10 14:24:24 -080010895 /**
10896 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10897 */
10898 @VisibleForTesting
10899 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010900 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010901 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010902 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010903 final SparseArray<Set<Integer>> uids =
10904 createUidsFromOemNetworkPreferences(preference);
10905 for (int i = 0; i < uids.size(); i++) {
10906 final int key = uids.keyAt(i);
10907 final Set<Integer> value = uids.valueAt(i);
10908 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10909 // No need to add an nri without any requests.
10910 if (0 == nri.mRequests.size()) {
10911 continue;
10912 }
10913 nris.add(nri);
10914 }
10915
10916 return nris;
10917 }
10918
10919 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10920 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010921 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010922 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010923 final List<UserHandle> users =
10924 mContext.getSystemService(UserManager.class).getUserHandles(true);
10925 if (null == users || users.size() == 0) {
10926 if (VDBG || DDBG) {
10927 log("No users currently available for setting the OEM network preference.");
10928 }
James Mattisb6b6a432021-06-01 22:30:36 -070010929 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010930 }
James Mattis45d81842021-01-10 14:24:24 -080010931 for (final Map.Entry<String, Integer> entry :
10932 preference.getNetworkPreferences().entrySet()) {
10933 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010934 // Add the rules for all users as this policy is device wide.
10935 for (final UserHandle user : users) {
10936 try {
10937 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10938 if (!prefToUids.contains(pref)) {
10939 prefToUids.put(pref, new ArraySet<>());
10940 }
10941 prefToUids.get(pref).add(uid);
10942 } catch (PackageManager.NameNotFoundException e) {
10943 // Although this may seem like an error scenario, it is ok that uninstalled
10944 // packages are sent on a network preference as the system will watch for
10945 // package installations associated with this network preference and update
10946 // accordingly. This is done to minimize race conditions on app install.
10947 continue;
James Mattis45d81842021-01-10 14:24:24 -080010948 }
James Mattis45d81842021-01-10 14:24:24 -080010949 }
10950 }
James Mattisb6b6a432021-06-01 22:30:36 -070010951 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010952 }
10953
10954 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10955 @OemNetworkPreferences.OemNetworkPreference final int preference,
10956 @NonNull final Set<Integer> uids) {
10957 final List<NetworkRequest> requests = new ArrayList<>();
10958 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10959 switch (preference) {
10960 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10961 requests.add(createUnmeteredNetworkRequest());
10962 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010963 requests.add(createDefaultInternetRequestForTransport(
10964 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010965 break;
10966 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10967 requests.add(createUnmeteredNetworkRequest());
10968 requests.add(createOemPaidNetworkRequest());
10969 break;
10970 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10971 requests.add(createOemPaidNetworkRequest());
10972 break;
10973 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10974 requests.add(createOemPrivateNetworkRequest());
10975 break;
James Mattisfa270db2021-05-31 17:11:10 -070010976 case OEM_NETWORK_PREFERENCE_TEST:
10977 requests.add(createUnmeteredNetworkRequest());
10978 requests.add(createTestNetworkRequest());
10979 requests.add(createDefaultRequest());
10980 break;
10981 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10982 requests.add(createTestNetworkRequest());
10983 break;
James Mattis45d81842021-01-10 14:24:24 -080010984 default:
10985 // This should never happen.
10986 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10987 + " called with invalid preference of " + preference);
10988 }
10989
James Mattisfa270db2021-05-31 17:11:10 -070010990 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010991 for (final int uid : uids) {
10992 ranges.add(new UidRange(uid, uid));
10993 }
10994 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010995 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010996 }
10997
10998 private NetworkRequest createUnmeteredNetworkRequest() {
10999 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11000 .addCapability(NET_CAPABILITY_NOT_METERED)
11001 .addCapability(NET_CAPABILITY_VALIDATED);
11002 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11003 }
11004
11005 private NetworkRequest createOemPaidNetworkRequest() {
11006 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11007 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11008 .addCapability(NET_CAPABILITY_OEM_PAID)
11009 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11010 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11011 }
11012
11013 private NetworkRequest createOemPrivateNetworkRequest() {
11014 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11015 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11016 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11017 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11018 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11019 }
11020
11021 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011022 final NetworkCapabilities netcap = new NetworkCapabilities();
11023 netcap.addCapability(NET_CAPABILITY_INTERNET);
11024 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11025 return netcap;
11026 }
11027
11028 private NetworkRequest createTestNetworkRequest() {
11029 final NetworkCapabilities netcap = new NetworkCapabilities();
11030 netcap.clearAll();
11031 netcap.addTransportType(TRANSPORT_TEST);
11032 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011033 }
James Mattis47db0582021-01-01 14:13:35 -080011034 }
markchien738ad912021-12-09 18:15:45 +080011035
11036 @Override
11037 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11038 enforceNetworkStackOrSettingsPermission();
11039
11040 try {
11041 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011042 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011043 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011044 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011045 }
Ken Chenf5f51332022-01-28 10:08:16 +080011046 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011047 throw new IllegalStateException(e);
11048 }
11049 }
11050
11051 @Override
11052 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11053 enforceNetworkStackOrSettingsPermission();
11054
11055 try {
11056 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011057 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011058 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011059 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011060 }
Ken Chenf5f51332022-01-28 10:08:16 +080011061 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011062 throw new IllegalStateException(e);
11063 }
11064 }
markchiene1561fa2021-12-09 22:00:56 +080011065
11066 @Override
11067 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
11068 enforceNetworkStackOrSettingsPermission();
11069
11070 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011071 mBpfNetMaps.setUidRule(chain, uid,
markchiene1561fa2021-12-09 22:00:56 +080011072 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
Ken Chenf5f51332022-01-28 10:08:16 +080011073 } catch (RemoteException | ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011074 throw new IllegalStateException(e);
11075 }
11076 }
markchien98a6f952022-01-13 23:43:53 +080011077
11078 @Override
11079 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11080 enforceNetworkStackOrSettingsPermission();
11081
11082 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011083 mBpfNetMaps.setChildChain(chain, enable);
Ken Chenf5f51332022-01-28 10:08:16 +080011084 } catch (RemoteException | ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011085 throw new IllegalStateException(e);
11086 }
11087 }
11088
markchien00a0bed2022-01-13 23:46:13 +080011089 @Override
11090 public void replaceFirewallChain(final int chain, final int[] uids) {
11091 enforceNetworkStackOrSettingsPermission();
11092
11093 try {
11094 switch (chain) {
11095 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011096 mBpfNetMaps.replaceUidChain("fw_dozable", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011097 break;
11098 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011099 mBpfNetMaps.replaceUidChain("fw_standby", false /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011100 break;
11101 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011102 mBpfNetMaps.replaceUidChain("fw_powersave", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011103 break;
11104 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
Wayne Ma2fde98c2022-01-17 18:04:05 +080011105 mBpfNetMaps.replaceUidChain("fw_restricted", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080011106 break;
Robert Horvath1db49e12022-01-27 19:54:29 +010011107 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11108 mBpfNetMaps.replaceUidChain("fw_low_power_standby", true /* isAllowList */,
11109 uids);
11110 break;
markchien00a0bed2022-01-13 23:46:13 +080011111 default:
11112 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
11113 + chain);
11114 }
Ken Chenf5f51332022-01-28 10:08:16 +080011115 } catch (RemoteException | ServiceSpecificException e) {
markchien00a0bed2022-01-13 23:46:13 +080011116 throw new IllegalStateException(e);
11117 }
11118 }
markchien9c806112022-01-11 23:28:23 +080011119
11120 @Override
11121 public void swapActiveStatsMap() {
11122 enforceNetworkStackOrSettingsPermission();
11123 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011124 mBpfNetMaps.swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +080011125 } catch (RemoteException | ServiceSpecificException e) {
markchien9c806112022-01-11 23:28:23 +080011126 throw new IllegalStateException(e);
11127 }
11128 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011129}