blob: 8bcbe904f9f87c7629c99e84b2dc342c3eda4cea [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;
lucaslin30779882021-04-23 21:03:39 +080018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Remi NGUYEN VAN9f992282021-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 Jean88953062018-02-21 18:43:54 +090024import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VANe15e61e2020-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 Colitti60104f52021-03-18 00:54:57 +090033import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka457dfd52021-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 VAN9f992282021-03-09 13:35:25 +090037import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti4c535bc2017-08-24 22:35:10 +090038import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN9f992282021-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 Greenwalt54d534f2014-05-13 21:41:06 -070049import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +090050import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandran1d450432014-10-30 14:55:29 -070051import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN9f992282021-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;
lucaslin30779882021-04-23 21:03:39 +080056import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucaslin8cf57f52019-10-22 18:27:33 +080057import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wang9cfa6fe2019-05-23 16:29:30 +080058import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
59import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen783c0e02015-06-16 14:27:36 -040060import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jean9d968182021-02-25 21:46:34 +090061import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti32237c72016-07-18 18:40:42 +090062import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittid21a5262015-05-14 17:07:20 +090063import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +090064import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittid21a5262015-05-14 17:07:20 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
66import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey1a1cba82017-10-27 17:22:59 -060067import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai71d157f2021-01-13 18:13:11 +080069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeane3c1bfd2018-01-10 21:19:32 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis6e6fabf2021-01-10 14:24:24 -080071import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
72import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin25a50472019-03-12 13:08:03 +080073import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittid21a5262015-05-14 17:07:20 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Roshan Pius332e7a22021-03-21 17:55:29 +000075import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
76import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
77import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeanfa33a752020-01-14 22:46:36 +090078import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jeanb5b172f2020-03-09 21:25:37 +090079import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey1a1cba82017-10-27 17:22:59 -060080import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai8cae3c72021-03-12 20:05:08 +080081import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Lorenzo Colittiac456b22019-03-22 00:28:28 +090082import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070083import static android.os.Process.INVALID_UID;
Ken Chenb8e4bc92020-12-24 12:59:10 +080084import static android.os.Process.VPN_UID;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -070085import static android.system.OsConstants.IPPROTO_TCP;
86import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey1a1cba82017-10-27 17:22:59 -060087
Cody Kestingd292a332020-01-05 14:06:39 -080088import static java.util.Map.Entry;
89
Chalard Jeanb5b172f2020-03-09 21:25:37 +090090import android.Manifest;
Lorenzo Colittiee6a6302019-04-12 10:48:06 +000091import android.annotation.NonNull;
Wenchao Tongae7e9fb2015-03-04 13:26:38 -080092import android.annotation.Nullable;
Cody Kestingd292a332020-01-05 14:06:39 -080093import android.app.AppOpsManager;
Dianne Hackborn6782e222015-12-09 17:22:26 -080094import android.app.BroadcastOptions;
Wink Saville690cb182013-06-29 21:10:57 -070095import android.app.PendingIntent;
junyulaic9a235a2021-01-26 15:29:15 +080096import android.app.usage.NetworkStatsManager;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070097import android.content.BroadcastReceiver;
paulhu68426192020-06-09 19:07:03 +080098import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -080099import android.content.ContentResolver;
100import android.content.Context;
101import android.content.Intent;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700102import android.content.IntentFilter;
markchien7fae6ea2020-03-27 18:12:39 +0800103import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700104import android.database.ContentObserver;
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +0900105import android.net.CaptivePortal;
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +0900106import android.net.CaptivePortalData;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -0700107import android.net.ConnectionInfo;
Cody Kestingd292a332020-01-05 14:06:39 -0800108import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kesting1d326382020-01-06 16:55:35 -0800109import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800110import android.net.ConnectivityManager;
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900111import android.net.ConnectivityManager.BlockedReason;
Roshan Pius7992afd2020-12-22 15:10:42 -0800112import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +0900113import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN8ffe4eb2021-02-19 12:53:54 +0900114import android.net.ConnectivityResources;
paulhu1510c9c2021-03-17 17:19:09 +0800115import android.net.ConnectivitySettingsManager;
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +0900116import android.net.DataStallReportParcelable;
paulhufe746bc2020-11-10 15:32:56 +0800117import android.net.DnsResolverServiceManager;
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +0900118import android.net.ICaptivePortal;
Cody Kesting9c69dd42019-12-17 12:55:28 -0800119import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120import android.net.IConnectivityManager;
Luke Huange3d6a792019-03-16 00:31:46 +0800121import android.net.IDnsResolver;
Luke Huang358aa262018-09-27 19:33:11 +0800122import android.net.INetd;
Chiachang Wange9bc1632021-02-04 17:29:59 +0800123import android.net.INetworkActivityListener;
Remi NGUYEN VAN8ffe4eb2021-02-19 12:53:54 +0900124import android.net.INetworkAgent;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900125import android.net.INetworkMonitor;
126import android.net.INetworkMonitorCallbacks;
Chalard Jean1ef1d902021-01-05 08:40:09 +0900127import android.net.INetworkOfferCallback;
Chalard Jean03433052021-02-25 17:23:40 +0900128import android.net.IOnCompleteListener;
Daniel Bright60f02ed2020-06-15 16:10:01 -0700129import android.net.IQosCallback;
junyulai9f872232019-01-16 20:23:34 +0800130import android.net.ISocketKeepaliveCallback;
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +0900131import android.net.InetAddresses;
Xiao Ma51410062019-04-10 19:01:52 +0900132import android.net.IpMemoryStore;
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +0900133import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800134import android.net.LinkProperties;
Charles He729f0b42017-05-15 17:07:18 +0100135import android.net.MatchAllNetworkSpecifier;
Ken Chende5e7aa2021-04-09 15:08:42 +0800136import android.net.NativeNetworkConfig;
137import android.net.NativeNetworkType;
junyulai48a59382019-01-15 11:32:44 +0800138import android.net.NattSocketKeepalive;
Robert Greenwalta1402df2014-03-19 17:56:12 -0700139import android.net.Network;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -0700140import android.net.NetworkAgent;
Lorenzo Colitticf595362020-01-12 22:28:37 +0900141import android.net.NetworkAgentConfig;
Robert Greenwalt948aea52014-04-11 15:53:27 -0700142import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800143import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700144import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti260d9982019-05-31 15:41:29 +0900145import android.net.NetworkMonitorManager;
Jeff Sharkey01ee4032018-01-18 22:01:59 +0900146import android.net.NetworkPolicyManager;
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +0000147import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +0900148import android.net.NetworkProvider;
Robert Greenwalt948aea52014-04-11 15:53:27 -0700149import android.net.NetworkRequest;
Chalard Jeandd753522020-12-21 18:36:52 +0900150import android.net.NetworkScore;
Etan Cohenb184cba2017-04-03 17:42:34 -0700151import android.net.NetworkSpecifier;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900152import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700153import android.net.NetworkState;
junyulai527859f2021-01-22 22:46:01 +0800154import android.net.NetworkStateSnapshot;
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +0900155import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700156import android.net.NetworkUtils;
Ricky Waid53cf002018-01-23 04:09:45 +0000157import android.net.NetworkWatchlistManager;
James Mattised87a672021-01-01 14:13:35 -0800158import android.net.OemNetworkPreferences;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900159import android.net.PrivateDnsConfigParcel;
Jason Monk1e3df5d2014-04-25 15:00:09 -0400160import android.net.ProxyInfo;
Daniel Bright60f02ed2020-06-15 16:10:01 -0700161import android.net.QosCallbackException;
162import android.net.QosFilter;
163import android.net.QosSocketFilter;
164import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700165import android.net.RouteInfo;
Tyler Weara8978d42019-12-05 14:55:30 -0800166import android.net.RouteInfoParcel;
junyulai21c06d02019-01-03 18:50:15 +0800167import android.net.SocketKeepalive;
markchien497a0622019-09-30 14:40:57 +0800168import android.net.TetheringManager;
Lorenzo Colittibd015f42021-02-04 00:18:27 +0900169import android.net.TransportInfo;
Paul Jensena8a49e02014-05-07 15:27:40 -0400170import android.net.UidRange;
Chiachang Wang1f50ae52020-12-10 22:24:47 +0800171import android.net.UidRangeParcel;
junyulai62d35f72021-01-23 09:46:34 +0800172import android.net.UnderlyingNetworkInfo;
Jason Monk43324ee2013-07-03 17:04:33 -0400173import android.net.Uri;
Benedict Wong6458ddf2019-11-06 00:20:15 -0800174import android.net.VpnManager;
Lorenzo Colittibd015f42021-02-04 00:18:27 +0900175import android.net.VpnTransportInfo;
Hugo Benichi3bdc8352016-05-31 16:28:06 +0900176import android.net.metrics.IpConnectivityLog;
Hugo Benichia616d962016-04-21 15:02:38 +0900177import android.net.metrics.NetworkEvent;
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -0700178import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe58b2002021-03-06 00:26:43 +0900179import android.net.networkstack.ModuleNetworkStackClient;
180import android.net.networkstack.NetworkStackClientBase;
paulhu0a2aa802021-01-08 00:51:49 +0800181import android.net.resolv.aidl.DnsHealthEventParcel;
182import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
183import android.net.resolv.aidl.Nat64PrefixEventParcel;
184import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900185import android.net.shared.PrivateDnsConfig;
Lorenzo Colittib8dfec42017-01-24 09:41:36 +0900186import android.net.util.MultinetworkPolicyTracker;
lucaslin32028e02021-01-21 02:03:17 +0800187import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800188import android.os.Binder;
Dianne Hackborn6782e222015-12-09 17:22:26 -0800189import android.os.Build;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -0700190import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800191import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700192import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700193import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800194import android.os.Looper;
195import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -0700196import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700197import android.os.ParcelFileDescriptor;
Hugo Benichi4802c802017-03-23 22:40:44 +0900198import android.os.Parcelable;
Cody Kestingd292a332020-01-05 14:06:39 -0800199import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700200import android.os.PowerManager;
Jeff Sharkey5663b6e2012-09-06 17:54:29 -0700201import android.os.Process;
lucaslina5e9bdb2021-01-21 02:04:15 +0800202import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700203import android.os.RemoteException;
Hugo Benichi145e3792017-05-11 13:16:17 +0900204import android.os.ServiceSpecificException;
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +0900205import android.os.SystemClock;
Anil Admal6d761f92019-04-05 10:06:37 -0700206import android.os.SystemProperties;
Dianne Hackbornbc55bd12012-08-29 18:32:08 -0700207import android.os.UserHandle;
Julia Reynolds5cec5382014-06-24 10:56:55 -0400208import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800209import android.provider.Settings;
Lorenzo Colitti4c9e2022021-03-10 16:39:18 +0900210import android.sysprop.NetworkProperties;
Wink Saville690cb182013-06-29 21:10:57 -0700211import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700212import android.text.TextUtils;
lucaslina5e9bdb2021-01-21 02:04:15 +0800213import android.util.ArrayMap;
Chalard Jeana39c91c2018-01-16 18:43:05 +0900214import android.util.ArraySet;
Serik Beketayev5b490472021-02-06 09:19:47 +0000215import android.util.LocalLog;
Jeff Sharkey833c35b2016-04-28 15:33:18 -0600216import android.util.Log;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900217import android.util.Pair;
Chad Brubakerccae0d32013-06-14 11:16:51 -0700218import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700219import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +0900221import com.android.connectivity.resources.R;
Jason Monk43324ee2013-07-03 17:04:33 -0400222import com.android.internal.annotations.GuardedBy;
Paul Jensena02ec162015-06-10 11:22:17 -0400223import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -0700224import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittif0461852016-04-05 17:52:16 +0900225import com.android.internal.util.MessageUtils;
Chiachang Wang2d7e03c2020-11-02 16:51:24 +0800226import com.android.modules.utils.BasicShellCommandHandler;
lucaslindb201da2021-02-23 01:12:55 +0800227import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +0900228import com.android.net.module.util.CollectionUtils;
Chalard Jeanfa159c12020-08-19 16:07:22 +0900229import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
230import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN9090c9e2021-03-04 17:46:46 +0900231import com.android.net.module.util.LocationPermissionChecker;
lifrc33ea4d2021-03-04 14:08:08 +0800232import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhu5e094422021-01-25 18:53:17 +0800233import com.android.net.module.util.PermissionUtils;
Chalard Jean15347192019-05-30 14:58:29 +0900234import com.android.server.connectivity.AutodestructReference;
Erik Klinecca88b02017-12-13 19:40:49 +0900235import com.android.server.connectivity.DnsManager;
dalykf4977492018-03-05 12:42:22 -0500236import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Chalard Jean1ef1d902021-01-05 08:40:09 +0900237import com.android.server.connectivity.FullScore;
Lorenzo Colittid1039d12015-06-15 14:29:22 +0900238import com.android.server.connectivity.KeepaliveTracker;
Charles He729f0b42017-05-15 17:07:18 +0100239import com.android.server.connectivity.LingerMonitor;
Christopher Wileya28f7562016-10-11 13:26:03 -0700240import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -0700241import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey833c35b2016-04-28 15:33:18 -0600242import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti7d31cc02016-08-22 16:30:00 +0900243import com.android.server.connectivity.NetworkNotificationManager;
244import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jean1ef1d902021-01-05 08:40:09 +0900245import com.android.server.connectivity.NetworkOffer;
Chalard Jean58d486c2019-12-10 22:16:53 +0900246import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranc5756e42014-09-24 09:16:19 -0700247import com.android.server.connectivity.PermissionMonitor;
Chalard Jean9d968182021-02-25 21:46:34 +0900248import com.android.server.connectivity.ProfileNetworkPreferences;
Chalard Jeanfa4c8622018-06-07 16:44:04 +0900249import com.android.server.connectivity.ProxyTracker;
Daniel Bright60f02ed2020-06-15 16:10:01 -0700250import com.android.server.connectivity.QosCallbackTracker;
Jeff Sharkey833c35b2016-04-28 15:33:18 -0600251
Josh Gaobd97cc82020-06-16 15:58:11 -0700252import libcore.io.IoUtils;
253
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254import java.io.FileDescriptor;
255import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700256import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700257import java.net.InetAddress;
Lorenzo Colittidbcd5d62021-02-04 01:47:38 +0900258import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700259import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700260import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700261import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700262import java.util.Collection;
James Mattis7835f742020-11-03 15:54:33 -0800263import java.util.Collections;
Hugo Benichi821785c2018-09-03 08:19:02 +0900264import java.util.Comparator;
junyulai5ab727b2018-08-07 19:50:45 +0800265import java.util.ConcurrentModificationException;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700266import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700267import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700268import java.util.List;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700269import java.util.Map;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -0700270import java.util.Objects;
Chalard Jeana39c91c2018-01-16 18:43:05 +0900271import java.util.Set;
Jeff Sharkey833c35b2016-04-28 15:33:18 -0600272import java.util.SortedSet;
Chalard Jean373391b2019-12-10 21:07:02 +0900273import java.util.StringJoiner;
Jeff Sharkey833c35b2016-04-28 15:33:18 -0600274import java.util.TreeSet;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +0900275import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800276
277/**
278 * @hide
279 */
Jeremy Joslin94c30992014-11-05 10:32:09 -0800280public class ConnectivityService extends IConnectivityManager.Stub
281 implements PendingIntent.OnFinished {
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +0900282 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800283
Chalard Jean4ec33bf2018-06-04 13:33:12 +0900284 private static final String DIAG_ARG = "--diag";
Erik Klineef8bd292017-05-12 16:52:48 +0900285 public static final String SHORT_ARG = "--short";
Hugo Benichif93f4482018-09-03 08:32:56 +0900286 private static final String NETWORK_ARG = "networks";
287 private static final String REQUEST_ARG = "requests";
Erik Klineef8bd292017-05-12 16:52:48 +0900288
Lorenzo Colittid0a7a792016-04-08 23:09:09 +0900289 private static final boolean DBG = true;
hiroaki.yokoyamac510b272018-10-16 12:50:33 +0900290 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
291 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800292
Lorenzo Colitti600e9a22016-01-22 04:04:57 +0900293 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700294
Niklas Lindgren741013d2018-12-07 11:08:04 +0100295 /**
296 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
297 * by OEMs for configuration purposes, as this value is overridden by
paulhu79260c22021-03-17 20:30:33 +0800298 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgren741013d2018-12-07 11:08:04 +0100299 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
300 * (preferably via runtime resource overlays).
301 */
302 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
303 "http://connectivitycheck.gstatic.com/generate_204";
304
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700305 // TODO: create better separation between radio types and network types
306
Robert Greenwalt2034b912009-08-12 16:08:25 -0700307 // how long to wait before switching back to a radio's default network
308 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
309 // system property that can override the above value
310 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
311 "android.telephony.apn-restore";
312
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900313 // How long to wait before putting up a "This network doesn't have an Internet connection,
314 // connect anyway?" dialog after the user selects a network that doesn't validate.
315 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
316
junyulaif6d98ec2020-12-14 18:41:52 +0800317 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +0900318 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
319 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulaif6d98ec2020-12-14 18:41:52 +0800320 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Bright60f02ed2020-06-15 16:10:01 -0700321
322 // The maximum number of network request allowed per uid before an exception is thrown.
323 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
324
Lorenzo Colittib4f8d8e2021-03-30 19:29:00 +0900325 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattisfff0b7c2021-03-28 17:41:09 -0700326 @VisibleForTesting
327 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colittib4f8d8e2021-03-30 19:29:00 +0900328
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +0900329 @VisibleForTesting
330 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulaif6d98ec2020-12-14 18:41:52 +0800331 @VisibleForTesting
332 protected int mNascentDelayMs;
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +0900333
Jeremy Joslinb9846d02014-12-03 17:15:28 -0800334 // How long to delay to removal of a pending intent based request.
paulhu79260c22021-03-17 20:30:33 +0800335 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslinb9846d02014-12-03 17:15:28 -0800336 private final int mReleasePendingIntentDelayMs;
337
Lorenzo Colitti756a0222017-03-21 18:54:11 +0900338 private MockableSystemProperties mSystemProperties;
339
Lorenzo Colittiee6a6302019-04-12 10:48:06 +0000340 @VisibleForTesting
341 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranc5756e42014-09-24 09:16:19 -0700342
Daniel Bright60f02ed2020-06-15 16:10:01 -0700343 private final PerUidCounter mNetworkRequestCounter;
James Mattisfff0b7c2021-03-28 17:41:09 -0700344 @VisibleForTesting
345 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Bright60f02ed2020-06-15 16:10:01 -0700346
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +0900347 private volatile boolean mLockdownEnabled;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700348
junyulai5ab727b2018-08-07 19:50:45 +0800349 /**
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +0000350 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
351 * internal handler thread, they don't need a lock.
junyulai5ab727b2018-08-07 19:50:45 +0800352 */
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +0000353 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulai5ab727b2018-08-07 19:50:45 +0800354
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +0900355 private final Context mContext;
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +0900356 private final ConnectivityResources mResources;
Paul Hu32fd2082021-01-26 02:53:06 +0000357 // The Context is created for UserHandle.ALL.
358 private final Context mUserAllContext;
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +0900359 private final Dependencies mDeps;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700360 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700361 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800362
Chenbo Feng3d9b4902018-11-08 17:36:21 -0800363 @VisibleForTesting
Luke Huange3d6a792019-03-16 00:31:46 +0800364 protected IDnsResolver mDnsResolver;
365 @VisibleForTesting
Chenbo Feng3d9b4902018-11-08 17:36:21 -0800366 protected INetd mNetd;
junyulaic9a235a2021-01-26 15:29:15 +0800367 private NetworkStatsManager mStatsManager;
paulhu7121b5e2020-12-29 18:15:13 +0800368 private NetworkPolicyManager mPolicyManager;
lucaslindb201da2021-02-23 01:12:55 +0800369 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700370
Benedict Wong7f6071d2018-11-09 14:45:34 -0800371 /**
372 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
373 * instances.
374 */
375 @GuardedBy("mTNSLock")
376 private TestNetworkService mTNS;
377
378 private final Object mTNSLock = new Object();
379
Robert Greenwalt03806862014-08-06 12:00:25 -0700380 private String mCurrentTcpBufferSizes;
381
Lorenzo Colittif0461852016-04-05 17:52:16 +0900382 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifr1c0d9b22021-03-10 13:58:14 +0800383 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittif0461852016-04-05 17:52:16 +0900384
Paul Jensenabda68b2014-11-25 12:33:08 -0500385 private enum ReapUnvalidatedNetworks {
Paul Jensenece7dfa2015-06-25 13:25:07 -0400386 // Tear down networks that have no chance (e.g. even if validated) of becoming
387 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenabda68b2014-11-25 12:33:08 -0500388 // all networks have been rematched against all NetworkRequests.
389 REAP,
Paul Jensenece7dfa2015-06-25 13:25:07 -0400390 // Don't reap networks. This should be passed when some networks have not yet been
391 // rematched against all NetworkRequests.
Paul Jensenabda68b2014-11-25 12:33:08 -0500392 DONT_REAP
Chalard Jean4ec33bf2018-06-04 13:33:12 +0900393 }
Paul Jensenabda68b2014-11-25 12:33:08 -0500394
Lorenzo Colittib5b725d2016-09-09 18:48:56 +0900395 private enum UnneededFor {
396 LINGER, // Determine whether this network is unneeded and should be lingered.
397 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
398 }
399
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700400 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700401 * used internally to clear a wakelock when transitioning
Robert Greenwalt61837eb2014-06-25 16:45:57 -0700402 * from one net to another. Clear happens when we get a new
403 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
404 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700405 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700406 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700407
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700408 /**
409 * used internally to reload global proxy settings
410 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700411 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700412
Robert Greenwalt34848c02011-03-25 13:09:25 -0700413 /**
Jason Monk445cea82013-10-10 14:02:51 -0400414 * PAC manager has received new port.
415 */
416 private static final int EVENT_PROXY_HAS_CHANGED = 16;
417
Robert Greenwalt948aea52014-04-11 15:53:27 -0700418 /**
Lorenzo Colitti94c93142020-01-10 00:40:28 +0900419 * used internally when registering NetworkProviders
420 * obj = NetworkProviderInfo
Robert Greenwalt948aea52014-04-11 15:53:27 -0700421 */
Lorenzo Colitti94c93142020-01-10 00:40:28 +0900422 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt948aea52014-04-11 15:53:27 -0700423
Robert Greenwaltdb6fac52014-04-18 15:25:25 -0700424 /**
425 * used internally when registering NetworkAgents
426 * obj = Messenger
427 */
428 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
429
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -0700430 /**
431 * used to add a network request
432 * includes a NetworkRequestInfo
433 */
434 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
435
436 /**
437 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineaec3f5e2016-07-07 16:50:58 +0900438 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -0700439 * cancel it.
440 * includes a NetworkRequestInfo
441 */
442 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
443
444 /**
445 * used to add a network listener - no request
446 * includes a NetworkRequestInfo
447 */
448 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
449
450 /**
451 * used to remove a network request, either a listener or a real request
Paul Jensenabaa0ed2014-05-16 14:31:12 -0400452 * arg1 = UID of caller
453 * obj = NetworkRequest
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -0700454 */
455 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
456
Robert Greenwalte20d3ec2014-05-16 15:49:14 -0700457 /**
Lorenzo Colitti94c93142020-01-10 00:40:28 +0900458 * used internally when registering NetworkProviders
Robert Greenwalte20d3ec2014-05-16 15:49:14 -0700459 * obj = Messenger
460 */
Lorenzo Colitti94c93142020-01-10 00:40:28 +0900461 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -0700462
Robert Greenwalt61837eb2014-06-25 16:45:57 -0700463 /**
464 * used internally to expire a wakelock when transitioning
465 * from one net to another. Expire happens when we fail to find
466 * a new network (typically after 1 minute) -
467 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
468 * a replacement network.
469 */
470 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
471
Robert Greenwalt61af23a2014-08-13 13:43:32 -0700472 /**
Jeremy Joslin94c30992014-11-05 10:32:09 -0800473 * used to add a network request with a pending intent
Paul Jensen9ceed862015-06-17 14:15:39 -0400474 * obj = NetworkRequestInfo
Jeremy Joslin94c30992014-11-05 10:32:09 -0800475 */
476 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
477
478 /**
479 * used to remove a pending intent and its associated network request.
480 * arg1 = UID of caller
481 * obj = PendingIntent
482 */
483 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
484
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +0900485 /**
486 * used to specify whether a network should be used even if unvalidated.
487 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
488 * arg2 = whether to remember this choice in the future (1 or 0)
489 * obj = network
490 */
491 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
492
493 /**
494 * used to ask the user to confirm a connection to an unvalidated network.
495 * obj = network
496 */
497 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -0700498
Erik Kline74d68ef2015-04-30 12:58:40 +0900499 /**
Leif Hendrik Wildena6521802018-05-02 12:05:24 -0700500 * used internally to (re)configure always-on networks.
Erik Kline74d68ef2015-04-30 12:58:40 +0900501 */
Leif Hendrik Wildena6521802018-05-02 12:05:24 -0700502 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline74d68ef2015-04-30 12:58:40 +0900503
Paul Jensen9ceed862015-06-17 14:15:39 -0400504 /**
505 * used to add a network listener with a pending intent
506 * obj = NetworkRequestInfo
507 */
508 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
509
Hugo Benichi1c7c8d02017-04-06 17:22:18 +0900510 /**
511 * used to specify whether a network should not be penalized when it becomes unvalidated.
512 */
513 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
514
515 /**
516 * used to trigger revalidation of a network.
517 */
518 private static final int EVENT_REVALIDATE_NETWORK = 36;
519
Erik Klinec06d4f92018-01-11 21:07:29 +0900520 // Handle changes in Private DNS settings.
521 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
522
dalykf4977492018-03-05 12:42:22 -0500523 // Handle private DNS validation status updates.
524 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
525
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900526 /**
527 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
528 * been tested.
Cody Kestingd292a332020-01-05 14:06:39 -0800529 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
530 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
531 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900532 */
Chalard Jeanbb3e64f2019-09-26 18:03:47 +0900533 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900534
535 /**
536 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
537 * config was resolved.
538 * obj = PrivateDnsConfig
539 * arg2 = netid
540 */
Chalard Jeanbb3e64f2019-09-26 18:03:47 +0900541 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900542
543 /**
544 * Request ConnectivityService display provisioning notification.
545 * arg1 = Whether to make the notification visible.
546 * arg2 = NetID.
547 * obj = Intent to be launched when notification selected by user, null if !arg1.
548 */
Chalard Jeanbb3e64f2019-09-26 18:03:47 +0900549 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900550
551 /**
lucaslin25a50472019-03-12 13:08:03 +0800552 * Used to specify whether a network should be used even if connectivity is partial.
553 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
554 * false)
555 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
556 * obj = network
557 */
lucaslin5cba3142020-02-20 16:56:59 +0800558 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin25a50472019-03-12 13:08:03 +0800559
560 /**
lucaslin8cf57f52019-10-22 18:27:33 +0800561 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
562 * Both of the arguments are bitmasks, and the value of bits come from
563 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
564 * arg1 = A bitmask to describe which probes are completed.
565 * arg2 = A bitmask to describe which probes are successful.
566 */
lucaslin5cba3142020-02-20 16:56:59 +0800567 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucaslin8cf57f52019-10-22 18:27:33 +0800568
569 /**
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +0900570 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
571 * arg1 = unused
572 * arg2 = netId
573 * obj = captive portal data
574 */
lucaslin5cba3142020-02-20 16:56:59 +0800575 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +0900576
577 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +0900578 * Used by setRequireVpnForUids.
579 * arg1 = whether the specified UID ranges are required to use a VPN.
580 * obj = Array of UidRange objects.
581 */
582 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
583
584 /**
Chalard Jean9d968182021-02-25 21:46:34 +0900585 * Used internally when setting the default networks for OemNetworkPreferences.
586 * obj = Pair<OemNetworkPreferences, listener>
James Mattis6e6fabf2021-01-10 14:24:24 -0800587 */
588 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
589
590 /**
lucaslina5e9bdb2021-01-21 02:04:15 +0800591 * Used to indicate the system default network becomes active.
592 */
593 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
594
595 /**
Chalard Jean9d968182021-02-25 21:46:34 +0900596 * Used internally when setting a network preference for a user profile.
597 * obj = Pair<ProfileNetworkPreference, Listener>
598 */
599 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
600
601 /**
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +0000602 * Event to specify that reasons for why an uid is blocked changed.
603 * arg1 = uid
604 * arg2 = blockedReasons
605 */
606 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
607
608 /**
Chalard Jean1ef1d902021-01-05 08:40:09 +0900609 * Event to register a new network offer
610 * obj = NetworkOffer
611 */
612 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
613
614 /**
615 * Event to unregister an existing network offer
616 * obj = INetworkOfferCallback
617 */
618 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
619
620 /**
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900621 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
622 * should be shown.
623 */
Chalard Jeanbb3e64f2019-09-26 18:03:47 +0900624 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900625
626 /**
627 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
628 * should be hidden.
629 */
Chalard Jeanbb3e64f2019-09-26 18:03:47 +0900630 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +0900631
Hugo Benichi23ec1c92017-03-30 10:46:05 +0900632 private static String eventName(int what) {
633 return sMagicDecoderRing.get(what, Integer.toString(what));
634 }
635
paulhufe746bc2020-11-10 15:32:56 +0800636 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colittib35d0382021-04-15 18:03:54 +0900637 final DnsResolverServiceManager dsm = context.getSystemService(
638 DnsResolverServiceManager.class);
639 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huange3d6a792019-03-16 00:31:46 +0800640 }
641
Cody Kesting0ffbf922019-12-18 10:57:50 -0800642 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti1b8b5cd2015-08-07 20:17:27 +0900643 @VisibleForTesting
644 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700645 /** Handler used for internal events. */
Robert Greenwaltdb6fac52014-04-18 15:25:25 -0700646 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700647 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwaltdb6fac52014-04-18 15:25:25 -0700648 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting0ffbf922019-12-18 10:57:50 -0800649 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
650 @VisibleForTesting
651 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
652
Erik Klinecca88b02017-12-13 19:40:49 +0900653 private final DnsManager mDnsManager;
Chalard Jean58d486c2019-12-10 22:16:53 +0900654 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700655
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400656 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800657 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400658
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700659 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin94c30992014-11-05 10:32:09 -0800660 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700661
Chalard Jeanfa4c8622018-06-07 16:44:04 +0900662 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
663 // the world when it changes.
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +0000664 @VisibleForTesting
665 protected final ProxyTracker mProxyTracker;
Jason Monk43324ee2013-07-03 17:04:33 -0400666
Erik Kline74d68ef2015-04-30 12:58:40 +0900667 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700668
Julia Reynolds5cec5382014-06-24 10:56:55 -0400669 private UserManager mUserManager;
670
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700671 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +0900672 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700673
Valentin Iftimea039e572019-09-24 13:32:13 +0200674 private Set<String> mWolSupportedInterfaces;
675
Roshan Pius1cbb1ae2020-01-16 12:17:17 -0800676 private final TelephonyManager mTelephonyManager;
Cody Kestingd292a332020-01-05 14:06:39 -0800677 private final AppOpsManager mAppOpsManager;
678
679 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock4ba7e412013-06-24 14:20:23 -0400680
Lorenzo Colittid1039d12015-06-15 14:29:22 +0900681 private KeepaliveTracker mKeepaliveTracker;
Daniel Bright60f02ed2020-06-15 16:10:01 -0700682 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti7d31cc02016-08-22 16:30:00 +0900683 private NetworkNotificationManager mNotifier;
Lorenzo Colittib268f9f2016-08-22 16:46:40 +0900684 private LingerMonitor mLingerMonitor;
Lorenzo Colittid1039d12015-06-15 14:29:22 +0900685
Robert Greenwalt469fa2a2014-05-18 16:22:10 -0700686 // sequence number of NetworkRequests
junyulai5ef392c2020-12-14 18:51:02 +0800687 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt469fa2a2014-05-18 16:22:10 -0700688
Lorenzo Colitti92e6c272020-01-08 00:04:09 +0900689 // Sequence number for NetworkProvider IDs.
690 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
691 NetworkProvider.FIRST_PROVIDER_ID);
692
Erik Kline47401fa2015-07-09 18:24:03 +0900693 // NetworkRequest activity String log entries.
694 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
695 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
696
Hugo Benichi7b3bf372016-07-11 11:05:12 +0900697 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi23ec1c92017-03-30 10:46:05 +0900698 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichi7b3bf372016-07-11 11:05:12 +0900699 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
700
Hugo Benichi23ec1c92017-03-30 10:46:05 +0900701 private static final int MAX_WAKELOCK_LOGS = 20;
702 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi3ac913c2017-09-05 13:25:07 +0900703 private int mTotalWakelockAcquisitions = 0;
704 private int mTotalWakelockReleases = 0;
705 private long mTotalWakelockDurationMs = 0;
706 private long mMaxWakelockDurationMs = 0;
707 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi23ec1c92017-03-30 10:46:05 +0900708
Hugo Benichi638621a2016-07-28 17:53:06 +0900709 private final IpConnectivityLog mMetricsLog;
Hugo Benichi3bdc8352016-05-31 16:28:06 +0900710
Nathan Harold6179b142018-07-30 13:38:01 -0700711 @GuardedBy("mBandwidthRequests")
712 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
713
Erik Klinefc52be92016-10-02 18:02:14 +0900714 @VisibleForTesting
Lorenzo Colittib8dfec42017-01-24 09:41:36 +0900715 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Klinefc52be92016-10-02 18:02:14 +0900716
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +0900717 @VisibleForTesting
Cody Kesting0c55a302020-03-05 10:46:02 -0800718 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
719 new HashMap<>();
Cody Kesting0ffbf922019-12-18 10:57:50 -0800720
Robert Greenwalt5a367872014-06-02 15:32:02 -0700721 /**
722 * Implements support for the legacy "one network per network type" model.
723 *
724 * We used to have a static array of NetworkStateTrackers, one for each
725 * network type, but that doesn't work any more now that we can have,
726 * for example, more that one wifi network. This class stores all the
727 * NetworkAgentInfo objects that support a given type, but the legacy
728 * API will only see the first one.
729 *
730 * It serves two main purposes:
731 *
732 * 1. Provide information about "the network for a given type" (since this
733 * API only supports one).
734 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
735 * the first network for a given type changes, or if the default network
736 * changes.
737 */
Chalard Jean8cc4e872019-04-10 23:07:55 +0900738 @VisibleForTesting
739 static class LegacyTypeTracker {
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900740
Lorenzo Colittid0a7a792016-04-08 23:09:09 +0900741 private static final boolean DBG = true;
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900742 private static final boolean VDBG = false;
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900743
Robert Greenwalt5a367872014-06-02 15:32:02 -0700744 /**
745 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
746 * Each list holds references to all NetworkAgentInfos that are used to
747 * satisfy requests for that network type.
748 *
749 * This array is built out at startup such that an unsupported network
750 * doesn't get an ArrayList instance, making this a tristate:
751 * unsupported, supported but not active and active.
752 *
753 * The actual lists are populated when we scan the network types that
754 * are supported on this device.
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900755 *
756 * Threading model:
757 * - addSupportedType() is only called in the constructor
758 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
759 * They are therefore not thread-safe with respect to each other.
760 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
761 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +0900762 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900763 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt5a367872014-06-02 15:32:02 -0700764 */
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900765 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean8cc4e872019-04-10 23:07:55 +0900766 @NonNull
767 private final ConnectivityService mService;
Robert Greenwalt5a367872014-06-02 15:32:02 -0700768
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +0900769 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
770 // an entry have no timer (equivalent to -1). Lazily loaded.
771 @NonNull
772 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
773
Chalard Jean8cc4e872019-04-10 23:07:55 +0900774 LegacyTypeTracker(@NonNull ConnectivityService service) {
775 mService = service;
776 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt5a367872014-06-02 15:32:02 -0700777 }
778
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +0900779 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
780 final PackageManager pm = ctx.getPackageManager();
781 if (pm.hasSystemFeature(FEATURE_WIFI)) {
782 addSupportedType(TYPE_WIFI);
783 }
784 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
785 addSupportedType(TYPE_WIFI_P2P);
786 }
787 if (tm.isDataCapable()) {
788 // Telephony does not have granular support for these types: they are either all
789 // supported, or none is supported
790 addSupportedType(TYPE_MOBILE);
791 addSupportedType(TYPE_MOBILE_MMS);
792 addSupportedType(TYPE_MOBILE_SUPL);
793 addSupportedType(TYPE_MOBILE_DUN);
794 addSupportedType(TYPE_MOBILE_HIPRI);
795 addSupportedType(TYPE_MOBILE_FOTA);
796 addSupportedType(TYPE_MOBILE_IMS);
797 addSupportedType(TYPE_MOBILE_CBS);
798 addSupportedType(TYPE_MOBILE_IA);
799 addSupportedType(TYPE_MOBILE_EMERGENCY);
800 }
801 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
802 addSupportedType(TYPE_BLUETOOTH);
803 }
804 if (pm.hasSystemFeature(FEATURE_WATCH)) {
805 // TYPE_PROXY is only used on Wear
806 addSupportedType(TYPE_PROXY);
807 }
808 // Ethernet is often not specified in the configs, although many devices can use it via
809 // USB host adapters. Add it as long as the ethernet service is here.
810 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
811 addSupportedType(TYPE_ETHERNET);
812 }
813
814 // Always add TYPE_VPN as a supported type
815 addSupportedType(TYPE_VPN);
816 }
817
818 private void addSupportedType(int type) {
Robert Greenwalt5a367872014-06-02 15:32:02 -0700819 if (mTypeLists[type] != null) {
820 throw new IllegalStateException(
821 "legacy list for type " + type + "already initialized");
822 }
Chalard Jean4ec33bf2018-06-04 13:33:12 +0900823 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt5a367872014-06-02 15:32:02 -0700824 }
825
Robert Greenwalt5a367872014-06-02 15:32:02 -0700826 public boolean isTypeSupported(int type) {
827 return isNetworkTypeValid(type) && mTypeLists[type] != null;
828 }
829
830 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900831 synchronized (mTypeLists) {
832 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
833 return mTypeLists[type].get(0);
834 }
Robert Greenwalt5a367872014-06-02 15:32:02 -0700835 }
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900836 return null;
Robert Greenwalt5a367872014-06-02 15:32:02 -0700837 }
838
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +0900839 public int getRestoreTimerForType(int type) {
840 synchronized (mTypeLists) {
841 if (mRestoreTimers == null) {
842 mRestoreTimers = loadRestoreTimers();
843 }
844 return mRestoreTimers.getOrDefault(type, -1);
845 }
846 }
847
848 private ArrayMap<Integer, Integer> loadRestoreTimers() {
849 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +0900850 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +0900851 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
852 for (final String config : configs) {
853 final String[] splits = TextUtils.split(config, ",");
854 if (splits.length != 2) {
855 logwtf("Invalid restore timer token count: " + config);
856 continue;
857 }
858 try {
859 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
860 } catch (NumberFormatException e) {
861 logwtf("Invalid restore timer number format: " + config, e);
862 }
863 }
864 return ret;
865 }
866
Robert Greenwalt41c19a02015-06-24 13:23:42 -0700867 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean1bc77a92021-02-04 13:12:59 +0900868 boolean isDefaultNetwork) {
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900869 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +0900870 log("Sending " + state
871 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean1bc77a92021-02-04 13:12:59 +0900872 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900873 }
874 }
875
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +0900876 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
877 // network type, to preserve previous behaviour.
878 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
879 if (vpnNai != mService.getLegacyLockdownNai()) return;
880
881 if (vpnNai.declaredUnderlyingNetworks == null
882 || vpnNai.declaredUnderlyingNetworks.length != 1) {
883 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
884 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
885 return;
886 }
Lorenzo Colittia0473fc2021-02-12 10:14:01 +0900887 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +0900888 vpnNai.declaredUnderlyingNetworks[0]);
889 if (underlyingNai == null) return;
890
891 final int type = underlyingNai.networkInfo.getType();
892 final DetailedState state = DetailedState.CONNECTED;
893 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
894 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
895 }
896
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900897 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt5a367872014-06-02 15:32:02 -0700898 public void add(int type, NetworkAgentInfo nai) {
899 if (!isTypeSupported(type)) {
900 return; // Invalid network type.
901 }
902 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
903
904 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
905 if (list.contains(nai)) {
Robert Greenwalt5a367872014-06-02 15:32:02 -0700906 return;
907 }
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900908 synchronized (mTypeLists) {
909 list.add(nai);
910 }
Lorenzo Colitti497b4b02014-09-28 16:08:06 +0900911
Chalard Jean1bc77a92021-02-04 13:12:59 +0900912 // Send a broadcast if this is the first network of its type or if it's the default.
913 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +0900914
915 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
916 // to preserve previous behaviour.
917 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean1bc77a92021-02-04 13:12:59 +0900918 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +0900919 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
920 mService.sendLegacyNetworkBroadcast(nai, state, type);
921 }
922
923 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
924 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt5a367872014-06-02 15:32:02 -0700925 }
Robert Greenwalt5a367872014-06-02 15:32:02 -0700926 }
927
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900928 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti2e3a9702015-05-01 00:30:10 +0900929 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900930 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
931 if (list == null || list.isEmpty()) {
932 return;
933 }
Lorenzo Colitti2e3a9702015-05-01 00:30:10 +0900934 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900935
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900936 synchronized (mTypeLists) {
937 if (!list.remove(nai)) {
938 return;
939 }
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900940 }
941
Lorenzo Colitti2e3a9702015-05-01 00:30:10 +0900942 if (wasFirstNetwork || wasDefault) {
Chalard Jean24a433a2019-04-11 14:09:07 +0900943 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
944 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900945 }
946
947 if (!list.isEmpty() && wasFirstNetwork) {
948 if (DBG) log("Other network available for type " + type +
949 ", sending connected broadcast");
Lorenzo Colitti2e3a9702015-05-01 00:30:10 +0900950 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean24a433a2019-04-11 14:09:07 +0900951 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean1bc77a92021-02-04 13:12:59 +0900952 mService.isDefaultNetwork(replacement));
Chalard Jean24a433a2019-04-11 14:09:07 +0900953 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colittid55162b2014-07-31 23:20:17 +0900954 }
955 }
956
957 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti2e3a9702015-05-01 00:30:10 +0900958 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
959 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt5a367872014-06-02 15:32:02 -0700960 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti2e3a9702015-05-01 00:30:10 +0900961 remove(type, nai, wasDefault);
Robert Greenwalt5a367872014-06-02 15:32:02 -0700962 }
963 }
Robert Greenwaltdbd5f312014-07-30 16:31:24 -0700964
Robert Greenwalt41c19a02015-06-24 13:23:42 -0700965 // send out another legacy broadcast - currently only used for suspend/unsuspend
966 // toggle
967 public void update(NetworkAgentInfo nai) {
Chalard Jean1bc77a92021-02-04 13:12:59 +0900968 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt41c19a02015-06-24 13:23:42 -0700969 final DetailedState state = nai.networkInfo.getDetailedState();
970 for (int type = 0; type < mTypeLists.length; type++) {
971 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwaltdd1e2232015-07-10 16:00:36 -0700972 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900973 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean1bc77a92021-02-04 13:12:59 +0900974 if (isFirst || contains && isDefault) {
975 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean8cc4e872019-04-10 23:07:55 +0900976 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt41c19a02015-06-24 13:23:42 -0700977 }
978 }
979 }
980
Robert Greenwaltdbd5f312014-07-30 16:31:24 -0700981 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti417c25c2015-06-03 11:18:24 +0900982 pw.println("mLegacyTypeTracker:");
983 pw.increaseIndent();
984 pw.print("Supported types:");
Robert Greenwaltdbd5f312014-07-30 16:31:24 -0700985 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti417c25c2015-06-03 11:18:24 +0900986 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltdbd5f312014-07-30 16:31:24 -0700987 }
Lorenzo Colitti417c25c2015-06-03 11:18:24 +0900988 pw.println();
989 pw.println("Current state:");
990 pw.increaseIndent();
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900991 synchronized (mTypeLists) {
992 for (int type = 0; type < mTypeLists.length; type++) {
993 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
994 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean373391b2019-12-10 21:07:02 +0900995 pw.println(type + " " + nai.toShortString());
Hugo Benichi9c807fd2016-06-21 09:48:07 +0900996 }
Lorenzo Colitti417c25c2015-06-03 11:18:24 +0900997 }
998 }
999 pw.decreaseIndent();
1000 pw.decreaseIndent();
1001 pw.println();
Robert Greenwaltdbd5f312014-07-30 16:31:24 -07001002 }
Robert Greenwalt5a367872014-06-02 15:32:02 -07001003 }
Chalard Jean8cc4e872019-04-10 23:07:55 +09001004 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt5a367872014-06-02 15:32:02 -07001005
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001006 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair9154a422017-10-26 10:08:50 -07001007 /**
1008 * Helper class which parses out priority arguments and dumps sections according to their
1009 * priority. If priority arguments are omitted, function calls the legacy dump command.
1010 */
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001011 private class LocalPriorityDump {
1012 private static final String PRIORITY_ARG = "--dump-priority";
1013 private static final String PRIORITY_ARG_HIGH = "HIGH";
1014 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1015
1016 LocalPriorityDump() {}
1017
1018 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1019 doDump(fd, pw, new String[] {DIAG_ARG});
1020 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair9154a422017-10-26 10:08:50 -07001021 }
1022
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001023 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1024 doDump(fd, pw, args);
Vishnu Nair9154a422017-10-26 10:08:50 -07001025 }
1026
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001027 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1028 if (args == null) {
1029 dumpNormal(fd, pw, args);
1030 return;
1031 }
1032
1033 String priority = null;
1034 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1035 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1036 argIndex++;
1037 priority = args[argIndex];
1038 }
1039 }
1040
1041 if (PRIORITY_ARG_HIGH.equals(priority)) {
1042 dumpHigh(fd, pw);
1043 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1044 dumpNormal(fd, pw, args);
1045 } else {
1046 // ConnectivityService publishes binder service using publishBinderService() with
1047 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
1048 // "--dump-priority" arguments to the service. Thus, dump both NORMAL and HIGH to
1049 // align the legacy design.
1050 // TODO: Integrate into signal dump.
1051 dumpNormal(fd, pw, args);
1052 pw.println();
1053 pw.println("DUMP OF SERVICE HIGH connectivity");
1054 pw.println();
1055 dumpHigh(fd, pw);
1056 }
Vishnu Nair9154a422017-10-26 10:08:50 -07001057 }
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001058 }
Vishnu Nair9154a422017-10-26 10:08:50 -07001059
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001060 /**
Daniel Bright60f02ed2020-06-15 16:10:01 -07001061 * Keeps track of the number of requests made under different uids.
1062 */
1063 public static class PerUidCounter {
1064 private final int mMaxCountPerUid;
1065
1066 // Map from UID to number of NetworkRequests that UID has filed.
James Mattisfff0b7c2021-03-28 17:41:09 -07001067 @VisibleForTesting
Daniel Bright60f02ed2020-06-15 16:10:01 -07001068 @GuardedBy("mUidToNetworkRequestCount")
James Mattisfff0b7c2021-03-28 17:41:09 -07001069 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Bright60f02ed2020-06-15 16:10:01 -07001070
1071 /**
1072 * Constructor
1073 *
1074 * @param maxCountPerUid the maximum count per uid allowed
1075 */
1076 public PerUidCounter(final int maxCountPerUid) {
1077 mMaxCountPerUid = maxCountPerUid;
1078 }
1079
1080 /**
1081 * Increments the request count of the given uid. Throws an exception if the number
1082 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1083 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1084 *
1085 * @throws ServiceSpecificException with
1086 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1087 * the uid exceed the allowed number.
1088 *
1089 * @param uid the uid that the request was made under
1090 */
1091 public void incrementCountOrThrow(final int uid) {
1092 synchronized (mUidToNetworkRequestCount) {
James Mattisfff0b7c2021-03-28 17:41:09 -07001093 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001094 }
1095 }
1096
James Mattisfff0b7c2021-03-28 17:41:09 -07001097 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1098 final int newRequestCount =
1099 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1100 if (newRequestCount >= mMaxCountPerUid) {
1101 throw new ServiceSpecificException(
1102 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1103 }
1104 mUidToNetworkRequestCount.put(uid, newRequestCount);
1105 }
1106
Daniel Bright60f02ed2020-06-15 16:10:01 -07001107 /**
1108 * Decrements the request count of the given uid.
1109 *
1110 * @param uid the uid that the request was made under
1111 */
1112 public void decrementCount(final int uid) {
1113 synchronized (mUidToNetworkRequestCount) {
James Mattisfff0b7c2021-03-28 17:41:09 -07001114 decrementCount(uid, 1 /* numToDecrement */);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001115 }
1116 }
James Mattisfff0b7c2021-03-28 17:41:09 -07001117
1118 private void decrementCount(final int uid, final int numToDecrement) {
1119 final int newRequestCount =
1120 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1121 if (newRequestCount < 0) {
1122 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1123 } else if (newRequestCount == 0) {
1124 mUidToNetworkRequestCount.delete(uid);
1125 } else {
1126 mUidToNetworkRequestCount.put(uid, newRequestCount);
1127 }
1128 }
1129
1130 /**
1131 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1132 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1133 * are used to create the new nris upon set. Therefore the request count limit can be
1134 * artificially hit. This method is used as a workaround for this particular case so that
1135 * the request counts are accounted for correctly.
1136 * @param uid the uid to adjust counts for
1137 * @param numOfNewRequests the new request count to account for
1138 * @param r the runnable to execute
1139 */
1140 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1141 // This should only be used on the handler thread as per all current and foreseen
1142 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1143 // no ref to the outer ConnectivityService.
1144 synchronized (mUidToNetworkRequestCount) {
1145 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1146 decrementCount(uid, reqCountOverage);
1147 r.run();
1148 incrementCountOrThrow(uid, reqCountOverage);
1149 }
1150 }
1151
1152 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1153 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1154 + numOfNewRequests;
1155 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1156 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1157 }
Daniel Bright60f02ed2020-06-15 16:10:01 -07001158 }
1159
1160 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001161 * Dependencies of ConnectivityService, for injection in tests.
1162 */
1163 @VisibleForTesting
1164 public static class Dependencies {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001165 public int getCallingUid() {
1166 return Binder.getCallingUid();
1167 }
1168
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001169 /**
1170 * Get system properties to use in ConnectivityService.
1171 */
1172 public MockableSystemProperties getSystemProperties() {
1173 return new MockableSystemProperties();
1174 }
1175
1176 /**
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09001177 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1178 */
1179 public ConnectivityResources getResources(@NonNull Context ctx) {
1180 return new ConnectivityResources(ctx);
1181 }
1182
1183 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001184 * Create a HandlerThread to use in ConnectivityService.
1185 */
1186 public HandlerThread makeHandlerThread() {
1187 return new HandlerThread("ConnectivityServiceThread");
1188 }
1189
1190 /**
Remi NGUYEN VANe58b2002021-03-06 00:26:43 +09001191 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001192 */
Remi NGUYEN VANe58b2002021-03-06 00:26:43 +09001193 public NetworkStackClientBase getNetworkStack() {
1194 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001195 }
1196
1197 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001198 * @see ProxyTracker
1199 */
1200 public ProxyTracker makeProxyTracker(@NonNull Context context,
1201 @NonNull Handler connServiceHandler) {
1202 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1203 }
1204
1205 /**
1206 * @see NetIdManager
1207 */
1208 public NetIdManager makeNetIdManager() {
1209 return new NetIdManager();
1210 }
1211
1212 /**
1213 * @see NetworkUtils#queryUserAccess(int, int)
1214 */
Lorenzo Colittid81932b2021-03-23 21:01:07 +09001215 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1216 return cs.queryUserAccess(uid, network);
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001217 }
1218
1219 /**
Lorenzo Colittidbcd5d62021-02-04 01:47:38 +09001220 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1221 * requires CAP_NET_ADMIN, which the unit tests do not have.
1222 */
1223 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1224 InetSocketAddress remote) {
1225 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1226 }
1227
1228 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001229 * @see MultinetworkPolicyTracker
1230 */
1231 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1232 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1233 return new MultinetworkPolicyTracker(c, h, r);
1234 }
1235
Aaron Huange044c462020-10-27 03:36:19 +08001236 /**
1237 * @see BatteryStatsManager
1238 */
1239 public void reportNetworkInterfaceForTransports(Context context, String iface,
1240 int[] transportTypes) {
Lorenzo Colitti4c9e2022021-03-10 16:39:18 +09001241 final BatteryStatsManager batteryStats =
Aaron Huange044c462020-10-27 03:36:19 +08001242 context.getSystemService(BatteryStatsManager.class);
1243 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1244 }
Lorenzo Colitti4c9e2022021-03-10 16:39:18 +09001245
1246 public boolean getCellular464XlatEnabled() {
1247 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1248 }
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001249 }
1250
junyulaic9a235a2021-01-26 15:29:15 +08001251 public ConnectivityService(Context context) {
1252 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VANe58b2002021-03-06 00:26:43 +09001253 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1254 new Dependencies());
Hugo Benichi638621a2016-07-28 17:53:06 +09001255 }
1256
1257 @VisibleForTesting
junyulaic9a235a2021-01-26 15:29:15 +08001258 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1259 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001260 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001261
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00001262 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001263 mSystemProperties = mDeps.getSystemProperties();
1264 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00001265 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09001266 mResources = deps.getResources(mContext);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001267 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colittib4f8d8e2021-03-30 19:29:00 +09001268 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitti756a0222017-03-21 18:54:11 +09001269
Hugo Benichi638621a2016-07-28 17:53:06 +09001270 mMetricsLog = logger;
Chalard Jean58d486c2019-12-10 22:16:53 +09001271 mNetworkRanker = new NetworkRanker();
James Mattis6e6fabf2021-01-10 14:24:24 -08001272 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1273 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colittif2514122021-03-12 22:50:57 +09001274 Process.myUid(), defaultInternetRequest, null,
Roshan Pius7992afd2020-12-22 15:10:42 -08001275 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis6e6fabf2021-01-10 14:24:24 -08001276 null /* attributionTags */);
Chalard Jean1bc77a92021-02-04 13:12:59 +09001277 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1278 mDefaultNetworkRequests.add(mDefaultRequest);
1279 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline74d68ef2015-04-30 12:58:40 +09001280
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09001281 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09001282 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt948aea52014-04-11 15:53:27 -07001283
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001284 // The default WiFi request is a background request so that apps using WiFi are
1285 // migrated to a better network (typically ethernet) when one comes up, instead
1286 // of staying on WiFi forever.
1287 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1288 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1289
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001290 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1291 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1292 NetworkRequest.Type.BACKGROUND_REQUEST);
1293
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001294 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti1b8b5cd2015-08-07 20:17:27 +09001295 mHandlerThread.start();
1296 mHandler = new InternalHandler(mHandlerThread.getLooper());
1297 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting0ffbf922019-12-18 10:57:50 -08001298 mConnectivityDiagnosticsHandler =
1299 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001300
Jeremy Joslinb9846d02014-12-03 17:15:28 -08001301 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08001302 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslinb9846d02014-12-03 17:15:28 -08001303
Lorenzo Colitti756a0222017-03-21 18:54:11 +09001304 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
junyulaif6d98ec2020-12-14 18:41:52 +08001305 // TODO: Consider making the timer customizable.
1306 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09001307
junyulaic9a235a2021-01-26 15:29:15 +08001308 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu7121b5e2020-12-29 18:15:13 +08001309 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00001310 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001311 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi0a28d302017-02-11 17:04:43 +09001312
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00001313 mNetd = netd;
Wink Saville690cb182013-06-29 21:10:57 -07001314 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kestingd292a332020-01-05 14:06:39 -08001315 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1316 mLocationPermissionChecker = new LocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001317
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00001318 // To ensure uid state is synchronized with Network Policy, register for
junyulai5ab727b2018-08-07 19:50:45 +08001319 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1320 // reading existing policy from disk.
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00001321 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001322
1323 final PowerManager powerManager = (PowerManager) context.getSystemService(
1324 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001325 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin94c30992014-11-05 10:32:09 -08001326 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001327
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09001328 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1329 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09001330 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001331 for (int p : protectedNetworks) {
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09001332 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001333 mProtectedNetworks.add(p);
1334 } else {
1335 if (DBG) loge("Ignoring protectedNetwork " + p);
1336 }
1337 }
1338
soma, kawata90913e92019-05-23 09:30:40 +09001339 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1340
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00001341 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranc5756e42014-09-24 09:16:19 -07001342
James Mattisbd275dc2021-03-13 19:27:21 -08001343 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09001344 // Listen for user add/removes to inform PermissionMonitor.
Varun Anand273f9002019-02-06 10:13:38 -08001345 // Should run on mHandler to avoid any races.
James Mattisbd275dc2021-03-13 19:27:21 -08001346 final IntentFilter userIntentFilter = new IntentFilter();
1347 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1348 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1349 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1350 null /* broadcastPermission */, mHandler);
paulhufa229ae2020-10-13 15:56:13 +08001351
James Mattisbd275dc2021-03-13 19:27:21 -08001352 // Listen to package add/removes for netd
1353 final IntentFilter packageIntentFilter = new IntentFilter();
1354 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1355 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1356 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1357 packageIntentFilter.addDataScheme("package");
1358 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09001359 null /* broadcastPermission */, mHandler);
junyulaib56dc512020-08-28 13:44:33 +08001360
lucaslinea5378c2021-02-20 18:59:47 +08001361 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001362
lucaslindb201da2021-02-23 01:12:55 +08001363 mNetdCallback = new NetdCallback();
1364 try {
1365 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1366 } catch (RemoteException | ServiceSpecificException e) {
1367 loge("Error registering event listener :" + e);
1368 }
1369
Erik Kline74d68ef2015-04-30 12:58:40 +09001370 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1371 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001372
junyulai61143782019-03-04 22:45:36 +08001373 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu13cafd92020-10-14 09:51:54 +08001374 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001375 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colittie5ebb712016-08-29 14:03:11 +09001376
1377 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08001378 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colittie5ebb712016-08-29 14:03:11 +09001379 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1380 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08001381 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colittie5ebb712016-08-29 14:03:11 +09001382 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1383 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti49d32fe2016-09-16 23:43:38 +09001384
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001385 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jean78515442021-03-19 13:49:56 +09001386 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09001387 mMultinetworkPolicyTracker.start();
Erik Klinecca88b02017-12-13 19:40:49 +09001388
Chiachang Wang67106862020-10-20 15:38:58 +08001389 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Klinec06d4f92018-01-11 21:07:29 +09001390 registerPrivateDnsSettingsCallbacks();
James Mattis1238af22020-12-23 16:37:26 -08001391
Chalard Jeandd753522020-12-21 18:36:52 +09001392 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1393 // request that doesn't allow fallback to the default network. It should never be visible
1394 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1395 // arguments like the handler or the DnsResolver.
1396 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslinea5378c2021-02-20 18:59:47 +08001397 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen69ed8432021-05-14 14:30:43 +08001398 new Network(INetd.UNREACHABLE_NET_ID),
James Mattis1238af22020-12-23 16:37:26 -08001399 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeandd753522020-12-21 18:36:52 +09001400 new LinkProperties(), new NetworkCapabilities(),
1401 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jeane634b282021-03-05 23:07:53 +09001402 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1403 mLingerDelayMs, mQosCallbackTracker, mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001404 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001405
Chalard Jeand9605fb2018-04-18 20:18:38 +09001406 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Chalard Jean9d968182021-02-25 21:46:34 +09001407 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1408 }
1409
1410 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1411 @NonNull final UidRange uids) {
Chalard Jeand9605fb2018-04-18 20:18:38 +09001412 final NetworkCapabilities netCap = new NetworkCapabilities();
1413 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai71d157f2021-01-13 18:13:11 +08001414 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jeand9605fb2018-04-18 20:18:38 +09001415 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Chiachang Wangd5034c72021-02-22 18:36:38 +08001416 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
Chalard Jeand9605fb2018-04-18 20:18:38 +09001417 return netCap;
1418 }
1419
James Mattis6e6fabf2021-01-10 14:24:24 -08001420 private NetworkRequest createDefaultRequest() {
1421 return createDefaultInternetRequestForTransport(
1422 TYPE_NONE, NetworkRequest.Type.REQUEST);
1423 }
1424
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09001425 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09001426 int transportType, NetworkRequest.Type type) {
Erik Kline72306522018-06-14 17:36:40 +09001427 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittid21a5262015-05-14 17:07:20 +09001428 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai71d157f2021-01-13 18:13:11 +08001429 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08001430 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis6e6fabf2021-01-10 14:24:24 -08001431 if (transportType > TYPE_NONE) {
Erik Kline74d68ef2015-04-30 12:58:40 +09001432 netCap.addTransportType(transportType);
1433 }
James Mattis6e6fabf2021-01-10 14:24:24 -08001434 return createNetworkRequest(type, netCap);
1435 }
1436
1437 private NetworkRequest createNetworkRequest(
1438 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09001439 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline74d68ef2015-04-30 12:58:40 +09001440 }
1441
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001442 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1443 NetworkRequest.Type type) {
1444 final NetworkCapabilities netCap = new NetworkCapabilities();
1445 netCap.clearAll();
1446 netCap.addCapability(capability);
1447 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1448 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1449 }
1450
Lorenzo Colitti6caa9fe2016-06-05 21:00:23 +09001451 // Used only for testing.
1452 // TODO: Delete this and either:
Erik Kline076bd3d2018-03-21 07:18:33 -07001453 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti6caa9fe2016-06-05 21:00:23 +09001454 // changing ContentResolver to make registerContentObserver non-final).
1455 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1456 // by subclassing SettingsObserver.
1457 @VisibleForTesting
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001458 void updateAlwaysOnNetworks() {
1459 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti6caa9fe2016-06-05 21:00:23 +09001460 }
1461
Erik Kline076bd3d2018-03-21 07:18:33 -07001462 // See FakeSettingsProvider comment above.
1463 @VisibleForTesting
1464 void updatePrivateDnsSettings() {
1465 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1466 }
1467
Remi NGUYEN VAN52950ed2021-03-06 00:11:24 +09001468 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001469 final boolean enable = mContext.getResources().getBoolean(id);
1470 handleAlwaysOnNetworkRequest(networkRequest, enable);
1471 }
1472
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001473 private void handleAlwaysOnNetworkRequest(
1474 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09001475 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001476 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001477 handleAlwaysOnNetworkRequest(networkRequest, enable);
1478 }
1479
1480 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001481 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline74d68ef2015-04-30 12:58:40 +09001482 if (enable == isEnabled) {
1483 return; // Nothing to do.
1484 }
1485
1486 if (enable) {
1487 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittif2514122021-03-12 22:50:57 +09001488 Process.myUid(), networkRequest, null, new Binder(),
Roshan Pius7992afd2020-12-22 15:10:42 -08001489 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis6e6fabf2021-01-10 14:24:24 -08001490 null /* attributionTags */));
Erik Kline74d68ef2015-04-30 12:58:40 +09001491 } else {
Etan Cohen06633de2019-01-08 12:09:18 -08001492 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1493 /* callOnUnavailable */ false);
Erik Kline74d68ef2015-04-30 12:58:40 +09001494 }
1495 }
1496
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001497 private void handleConfigureAlwaysOnNetworks() {
paulhu79260c22021-03-17 20:30:33 +08001498 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1499 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1500 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1501 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09001502 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1503 R.bool.config_vehicleInternalNetworkAlwaysRequested);
1504 // TODO (b/183076074): remove legacy fallback after migrating overlays
1505 final boolean legacyAlwaysRequested = mContext.getResources().getBoolean(
1506 mContext.getResources().getIdentifier(
1507 "config_vehicleInternalNetworkAlwaysRequested", "bool", "android"));
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001508 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09001509 vehicleAlwaysRequested || legacyAlwaysRequested);
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001510 }
1511
Erik Kline74d68ef2015-04-30 12:58:40 +09001512 private void registerSettingsCallbacks() {
1513 // Watch for global HTTP proxy changes.
1514 mSettingsObserver.observe(
1515 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1516 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1517
1518 // Watch for whether or not to keep mobile data always on.
1519 mSettingsObserver.observe(
paulhu79260c22021-03-17 20:30:33 +08001520 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001521 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1522
1523 // Watch for whether or not to keep wifi always on.
1524 mSettingsObserver.observe(
paulhu79260c22021-03-17 20:30:33 +08001525 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001526 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Kline74d68ef2015-04-30 12:58:40 +09001527 }
1528
Erik Klinec06d4f92018-01-11 21:07:29 +09001529 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline076bd3d2018-03-21 07:18:33 -07001530 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1531 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinec06d4f92018-01-11 21:07:29 +09001532 }
1533 }
1534
Robert Greenwalt469fa2a2014-05-18 16:22:10 -07001535 private synchronized int nextNetworkRequestId() {
junyulai5ef392c2020-12-14 18:51:02 +08001536 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1537 // doing that.
Robert Greenwalt469fa2a2014-05-18 16:22:10 -07001538 return mNextNetworkRequestId++;
1539 }
1540
junyulaica1fbb62018-06-13 15:00:37 +08001541 @VisibleForTesting
1542 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001543 if (network == null) {
1544 return null;
1545 }
Serik Beketayev284cb872020-12-07 22:43:07 -08001546 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline076bd3d2018-03-21 07:18:33 -07001547 }
1548
1549 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001550 synchronized (mNetworkForNetId) {
Erik Kline076bd3d2018-03-21 07:18:33 -07001551 return mNetworkForNetId.get(netId);
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001552 }
Jeff Sharkeyea403782016-04-22 09:50:16 -06001553 }
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001554
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001555 // TODO: determine what to do when more than one VPN applies to |uid|.
1556 private NetworkAgentInfo getVpnForUid(int uid) {
1557 synchronized (mNetworkForNetId) {
1558 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1559 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1560 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1561 return nai;
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001562 }
1563 }
1564 }
1565 return null;
1566 }
1567
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001568 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09001569 if (mLockdownEnabled) return null;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001570 final NetworkAgentInfo nai = getVpnForUid(uid);
1571 if (nai != null) return nai.declaredUnderlyingNetworks;
1572 return null;
1573 }
1574
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001575 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattisf61f7be2021-01-31 17:06:19 -08001576 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandranaf655d92014-11-11 16:09:21 -08001577
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001578 final Network[] networks = getVpnUnderlyingNetworks(uid);
1579 if (networks != null) {
1580 // getUnderlyingNetworks() returns:
1581 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1582 // empty array => the VPN explicitly said "no default network".
1583 // non-empty array => the VPN specified one or more default networks; we use the
1584 // first one.
1585 if (networks.length > 0) {
1586 nai = getNetworkAgentInfoForNetwork(networks[0]);
1587 } else {
1588 nai = null;
Sreeram Ramachandranaf655d92014-11-11 16:09:21 -08001589 }
1590 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001591 return nai;
Paul Jensen57d231c2014-08-29 09:54:01 -04001592 }
1593
1594 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001595 * Check if UID should be blocked from using the specified network.
Paul Jensen57d231c2014-08-29 09:54:01 -04001596 */
paulhu3b063e32020-12-30 00:42:19 +08001597 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1598 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001599 // Networks aren't blocked when ignoring blocked status
Hugo Benichi0a28d302017-02-11 17:04:43 +09001600 if (ignoreBlocked) {
1601 return false;
1602 }
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001603 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu3b063e32020-12-30 00:42:19 +08001604 final long ident = Binder.clearCallingIdentity();
1605 try {
1606 final boolean metered = nc == null ? true : nc.isMetered();
1607 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1608 } finally {
1609 Binder.restoreCallingIdentity(ident);
1610 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001611 }
1612
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001613 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichi7b3bf372016-07-11 11:05:12 +09001614 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1615 return;
1616 }
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001617 final boolean blocked;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001618 synchronized (mBlockedAppUids) {
1619 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001620 blocked = true;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001621 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001622 blocked = false;
1623 } else {
1624 return;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001625 }
1626 }
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001627 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1628 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1629 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001630 }
1631
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001632 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulai5ab727b2018-08-07 19:50:45 +08001633 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1634 return;
1635 }
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001636 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattis622428c2020-12-02 14:12:41 -08001637 final int requestId = nri.getActiveRequest() != null
1638 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai02025672020-05-29 14:44:42 +08001639 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001640 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankab9c396e2021-04-21 07:23:54 +00001641 Integer.toHexString(blocked)));
junyulai5ab727b2018-08-07 19:50:45 +08001642 }
1643
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001644 /**
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001645 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkeyea403782016-04-22 09:50:16 -06001646 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu3b063e32020-12-30 00:42:19 +08001647 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001648 */
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001649 @NonNull
1650 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1651 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti36567092021-03-03 14:39:04 +09001652 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1653 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1654 // but only exists if an app asks about them or requests them. Ensure the requesting app
1655 // gets the type it asks for.
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001656 filtered.setType(type);
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09001657 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1658 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1659 null /* extraInfo */);
1660 }
1661 filterForLegacyLockdown(filtered);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001662 return filtered;
1663 }
1664
1665 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1666 boolean ignoreBlocked) {
1667 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1668 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001669 }
1670
1671 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672 * Return NetworkInfo for the active (i.e., connected) network interface.
1673 * It is assumed that at most one network is active at a time. If more
1674 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001675 * @return the info for the active network, or {@code null} if none is
1676 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001677 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001678 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001679 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001680 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001681 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001682 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1683 if (nai == null) return null;
1684 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1685 maybeLogBlockedNetworkInfo(networkInfo, uid);
1686 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001687 }
1688
Paul Jensenc2569432015-02-13 14:18:39 -05001689 @Override
1690 public Network getActiveNetwork() {
1691 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001692 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Leeda4d2e22016-03-24 12:07:00 +00001693 }
1694
1695 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001696 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu5e094422021-01-25 18:53:17 +08001697 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001698 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001699 }
1700
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001701 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001702 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1703 if (vpnNai != null) {
1704 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1705 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1706 return vpnNai.network;
Chalard Jeand9605fb2018-04-18 20:18:38 +09001707 }
Paul Jensenc2569432015-02-13 14:18:39 -05001708 }
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001709
James Mattisf61f7be2021-01-31 17:06:19 -08001710 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001711 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1712 ignoreBlocked)) {
1713 return null;
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001714 }
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001715 return nai.network;
Paul Jensenc2569432015-02-13 14:18:39 -05001716 }
1717
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001718 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001719 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu5e094422021-01-25 18:53:17 +08001720 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001721 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1722 if (nai == null) return null;
1723 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001724 }
1725
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001726 /** Returns a NetworkInfo object for a network that doesn't exist. */
1727 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1728 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1729 getNetworkTypeName(networkType), "" /* subtypeName */);
1730 info.setIsAvailable(true);
1731 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1732 // background data is restricted.
1733 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1734 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1735 ? DetailedState.BLOCKED
1736 : DetailedState.DISCONNECTED;
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09001737 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1738 filterForLegacyLockdown(info);
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001739 return info;
1740 }
1741
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001742 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001743 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1744 return null;
1745 }
1746 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001747 if (nai == null) {
1748 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001749 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001750 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1751 false);
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001752 }
1753
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001754 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001755 public NetworkInfo getNetworkInfo(int networkType) {
1756 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001757 final int uid = mDeps.getCallingUid();
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001758 if (getVpnUnderlyingNetworks(uid) != null) {
1759 // A VPN is active, so we may need to return one of its underlying networks. This
1760 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001761 // getNetworkAgentInfoForUid.
1762 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1763 if (nai == null) return null;
1764 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1765 if (networkInfo.getType() == networkType) {
1766 return networkInfo;
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001767 }
1768 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001769 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001770 }
1771
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001772 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001773 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001774 enforceAccessPermission();
Jeff Sharkeyea403782016-04-22 09:50:16 -06001775 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001776 if (nai == null) return null;
1777 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001778 }
1779
1780 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001781 public NetworkInfo[] getAllNetworkInfo() {
1782 enforceAccessPermission();
Serik Beketayeveb7e8c62021-01-15 16:47:25 -08001783 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensene8015422014-09-19 11:14:12 -04001784 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1785 networkType++) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001786 NetworkInfo info = getNetworkInfo(networkType);
1787 if (info != null) {
1788 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001789 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001790 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001791 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001792 }
1793
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001794 @Override
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001795 public Network getNetworkForType(int networkType) {
1796 enforceAccessPermission();
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001797 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1798 return null;
1799 }
1800 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1801 if (nai == null) {
1802 return null;
1803 }
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001804 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001805 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1806 return null;
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001807 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001808 return nai.network;
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001809 }
1810
1811 @Override
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001812 public Network[] getAllNetworks() {
1813 enforceAccessPermission();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001814 synchronized (mNetworkForNetId) {
Paul Jensen71299dd2015-04-06 11:54:53 -04001815 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001816 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensen71299dd2015-04-06 11:54:53 -04001817 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001818 }
Paul Jensen71299dd2015-04-06 11:54:53 -04001819 return result;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001820 }
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001821 }
1822
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001823 @Override
Qingxi Libf6bf082020-01-08 12:51:49 -08001824 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001825 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001826 // The basic principle is: if an app's traffic could possibly go over a
1827 // network, without the app doing anything multinetwork-specific,
1828 // (hence, by "default"), then include that network's capabilities in
1829 // the array.
1830 //
1831 // In the normal case, app traffic only goes over the system's default
1832 // network connection, so that's the only network returned.
1833 //
1834 // With a VPN in force, some app traffic may go into the VPN, and thus
1835 // over whatever underlying networks the VPN specifies, while other app
1836 // traffic may go over the system default network (e.g.: a split-tunnel
1837 // VPN, or an app disallowed by the VPN), so the set of networks
1838 // returned includes the VPN's underlying networks and the system
1839 // default.
1840 enforceAccessPermission();
1841
Chalard Jean4ec33bf2018-06-04 13:33:12 +09001842 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001843
James Mattisf61f7be2021-01-31 17:06:19 -08001844 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1845 if (!nri.isBeingSatisfied()) {
1846 continue;
1847 }
1848 final NetworkAgentInfo nai = nri.getSatisfier();
1849 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1850 if (null != nc
1851 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1852 && !result.containsKey(nai.network)) {
1853 result.put(
1854 nai.network,
1855 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08001856 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001857 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1858 callingAttributionTag));
James Mattisf61f7be2021-01-31 17:06:19 -08001859 }
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001860 }
1861
Lorenzo Colitti011f29d2020-12-15 00:49:41 +09001862 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colittie0857092021-03-12 22:39:08 +09001863 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattisf61f7be2021-01-31 17:06:19 -08001864 if (null != networks) {
1865 for (final Network network : networks) {
1866 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1867 if (null != nc) {
Roshan Pius423fff62020-12-28 09:01:49 -08001868 result.put(
1869 network,
1870 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08001871 nc,
1872 false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001873 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08001874 callingAttributionTag));
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001875 }
1876 }
1877 }
1878
1879 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1880 out = result.values().toArray(out);
1881 return out;
1882 }
1883
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001884 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001885 public boolean isNetworkSupported(int networkType) {
1886 enforceAccessPermission();
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001887 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001888 }
1889
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001890 /**
1891 * Return LinkProperties for the active (i.e., connected) default
James Mattisf61f7be2021-01-31 17:06:19 -08001892 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001893 * @return the ip properties for the active network, or {@code null} if
1894 * none is active
1895 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001896 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001897 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001898 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001899 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001900 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1901 if (nai == null) return null;
1902 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001903 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001904 }
1905
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001906 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001907 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001908 enforceAccessPermission();
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001909 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001910 final LinkProperties lp = getLinkProperties(nai);
1911 if (lp == null) return null;
1912 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001913 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001914 }
1915
Robert Greenwalt54d534f2014-05-13 21:41:06 -07001916 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07001917 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001918 public LinkProperties getLinkProperties(Network network) {
1919 enforceAccessPermission();
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001920 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1921 if (lp == null) return null;
1922 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001923 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9a35d82017-04-06 16:01:44 +09001924 }
1925
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001926 @Nullable
1927 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09001928 if (nai == null) {
1929 return null;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001930 }
Hugo Benichie9a35d82017-04-06 16:01:44 +09001931 synchronized (nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001932 return nai.linkProperties;
Hugo Benichie9a35d82017-04-06 16:01:44 +09001933 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001934 }
1935
Qingxi Libf6bf082020-01-08 12:51:49 -08001936 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1937 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1938 }
1939
Lorenzo Colitti98097292015-05-14 17:28:27 +09001940 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001941 if (nai == null) return null;
1942 synchronized (nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001943 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001944 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001945 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001946 }
1947
1948 @Override
Roshan Piusc97d8062020-12-17 14:53:09 -08001949 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1950 @Nullable String callingAttributionTag) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001951 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colitti98097292015-05-14 17:28:27 +09001952 enforceAccessPermission();
Roshan Pius423fff62020-12-28 09:01:49 -08001953 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Libf6bf082020-01-08 12:51:49 -08001954 getNetworkCapabilitiesInternal(network),
Roshan Pius7992afd2020-12-22 15:10:42 -08001955 false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001956 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colitti98097292015-05-14 17:28:27 +09001957 }
1958
Qingxi Libb3347b2020-01-17 17:54:27 -08001959 @VisibleForTesting
1960 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean88953062018-02-21 18:43:54 +09001961 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean058cd312018-04-11 21:09:10 +09001962 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jeand9605fb2018-04-18 20:18:38 +09001963 if (!checkSettingsPermission(callerPid, callerUid)) {
1964 newNc.setUids(null);
1965 newNc.setSSID(null);
1966 }
Etan Cohenc069b062018-12-30 17:59:59 -08001967 if (newNc.getNetworkSpecifier() != null) {
1968 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1969 }
Cody Kestingc5cadf62020-03-16 18:15:28 -07001970 newNc.setAdministratorUids(new int[0]);
Benedict Wong4310e452021-03-24 14:01:51 -07001971 if (!checkAnyPermissionOf(
1972 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai58153cc2021-04-14 23:33:31 +08001973 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong4310e452021-03-24 14:01:51 -07001974 }
Qingxi Libb3347b2020-01-17 17:54:27 -08001975
Chalard Jean058cd312018-04-11 21:09:10 +09001976 return newNc;
Chalard Jeanb70f7cc2018-01-26 19:24:40 +09001977 }
1978
Roshan Pius332e7a22021-03-21 17:55:29 +00001979 /**
1980 * Wrapper used to cache the permission check results performed for the corresponding
1981 * app. This avoid performing multiple permission checks for different fields in
1982 * NetworkCapabilities.
1983 * Note: This wrapper does not support any sort of invalidation and thus must not be
1984 * persistent or long-lived. It may only be used for the time necessary to
1985 * compute the redactions required by one particular NetworkCallback or
1986 * synchronous call.
1987 */
1988 private class RedactionPermissionChecker {
1989 private final int mCallingPid;
1990 private final int mCallingUid;
1991 @NonNull private final String mCallingPackageName;
1992 @Nullable private final String mCallingAttributionTag;
1993
1994 private Boolean mHasLocationPermission = null;
1995 private Boolean mHasLocalMacAddressPermission = null;
1996 private Boolean mHasSettingsPermission = null;
1997
1998 RedactionPermissionChecker(int callingPid, int callingUid,
1999 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2000 mCallingPid = callingPid;
2001 mCallingUid = callingUid;
2002 mCallingPackageName = callingPackageName;
2003 mCallingAttributionTag = callingAttributionTag;
Roshan Pius423fff62020-12-28 09:01:49 -08002004 }
Roshan Pius332e7a22021-03-21 17:55:29 +00002005
2006 private boolean hasLocationPermissionInternal() {
2007 final long token = Binder.clearCallingIdentity();
2008 try {
2009 return mLocationPermissionChecker.checkLocationPermission(
2010 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2011 null /* message */);
2012 } finally {
2013 Binder.restoreCallingIdentity(token);
2014 }
2015 }
2016
2017 /**
2018 * Returns whether the app holds location permission or not (might return cached result
2019 * if the permission was already checked before).
2020 */
2021 public boolean hasLocationPermission() {
2022 if (mHasLocationPermission == null) {
2023 // If there is no cached result, perform the check now.
2024 mHasLocationPermission = hasLocationPermissionInternal();
2025 }
2026 return mHasLocationPermission;
2027 }
2028
2029 /**
2030 * Returns whether the app holds local mac address permission or not (might return cached
2031 * result if the permission was already checked before).
2032 */
2033 public boolean hasLocalMacAddressPermission() {
2034 if (mHasLocalMacAddressPermission == null) {
2035 // If there is no cached result, perform the check now.
2036 mHasLocalMacAddressPermission =
2037 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2038 }
2039 return mHasLocalMacAddressPermission;
2040 }
2041
2042 /**
2043 * Returns whether the app holds settings permission or not (might return cached
2044 * result if the permission was already checked before).
2045 */
2046 public boolean hasSettingsPermission() {
2047 if (mHasSettingsPermission == null) {
2048 // If there is no cached result, perform the check now.
2049 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2050 }
2051 return mHasSettingsPermission;
2052 }
2053 }
2054
2055 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2056 @NetworkCapabilities.NetCapability long redaction) {
2057 return (redactions & redaction) != 0;
2058 }
2059
2060 /**
2061 * Use the provided |applicableRedactions| to check the receiving app's
2062 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2063 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2064 * before being sent to the corresponding app.
2065 */
2066 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2067 @NetworkCapabilities.RedactionType long applicableRedactions,
2068 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2069 boolean includeLocationSensitiveInfo) {
2070 long redactions = applicableRedactions;
2071 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2072 if (includeLocationSensitiveInfo
2073 && redactionPermissionChecker.hasLocationPermission()) {
2074 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2075 }
2076 }
2077 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2078 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2079 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2080 }
2081 }
2082 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2083 if (redactionPermissionChecker.hasSettingsPermission()) {
2084 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2085 }
2086 }
2087 return redactions;
Roshan Pius423fff62020-12-28 09:01:49 -08002088 }
2089
Qingxi Libf6bf082020-01-08 12:51:49 -08002090 @VisibleForTesting
2091 @Nullable
Roshan Pius423fff62020-12-28 09:01:49 -08002092 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08002093 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius332e7a22021-03-21 17:55:29 +00002094 int callingPid, int callingUid, @NonNull String callingPkgName,
2095 @Nullable String callingAttributionTag) {
Qingxi Libf6bf082020-01-08 12:51:49 -08002096 if (nc == null) {
2097 return null;
2098 }
Roshan Pius423fff62020-12-28 09:01:49 -08002099 // Avoid doing location permission check if the transport info has no location sensitive
2100 // data.
Roshan Pius332e7a22021-03-21 17:55:29 +00002101 final RedactionPermissionChecker redactionPermissionChecker =
2102 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2103 callingAttributionTag);
2104 final long redactions = retrieveRequiredRedactions(
2105 nc.getApplicableRedactions(), redactionPermissionChecker,
2106 includeLocationSensitiveInfo);
2107 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius423fff62020-12-28 09:01:49 -08002108 // Reset owner uid if not destined for the owner app.
Roshan Pius332e7a22021-03-21 17:55:29 +00002109 if (callingUid != nc.getOwnerUid()) {
Qingxi Libf6bf082020-01-08 12:51:49 -08002110 newNc.setOwnerUid(INVALID_UID);
2111 return newNc;
2112 }
Benedict Wonge3bcbc02020-06-08 11:55:38 -07002113 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2114 if (nc.hasTransport(TRANSPORT_VPN)) {
2115 // Owner UIDs already checked above. No need to re-check.
2116 return newNc;
2117 }
Roshan Pius332e7a22021-03-21 17:55:29 +00002118 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2119 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius7992afd2020-12-22 15:10:42 -08002120 // compatibility for older apps.
2121 if (!includeLocationSensitiveInfo
2122 && isTargetSdkAtleast(
Roshan Pius332e7a22021-03-21 17:55:29 +00002123 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius7992afd2020-12-22 15:10:42 -08002124 newNc.setOwnerUid(INVALID_UID);
2125 return newNc;
2126 }
Roshan Pius423fff62020-12-28 09:01:49 -08002127 // Reset owner uid if the app has no location permission.
Roshan Pius332e7a22021-03-21 17:55:29 +00002128 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius423fff62020-12-28 09:01:49 -08002129 newNc.setOwnerUid(INVALID_UID);
2130 }
Qingxi Libf6bf082020-01-08 12:51:49 -08002131 return newNc;
Qingxi Libb3347b2020-01-17 17:54:27 -08002132 }
2133
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09002134 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2135 LinkProperties lp, int callerPid, int callerUid) {
2136 if (lp == null) return new LinkProperties();
2137
2138 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2139 final boolean needsSanitization =
2140 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2141 if (!needsSanitization) {
2142 return new LinkProperties(lp);
2143 }
2144
2145 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VANc3895462020-03-16 14:48:37 +09002146 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09002147 }
2148
2149 final LinkProperties newLp = new LinkProperties(lp);
2150 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2151 // object gets parceled.
2152 newLp.setCaptivePortalApiUrl(null);
2153 newLp.setCaptivePortalData(null);
2154 return newLp;
2155 }
2156
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002157 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2158 int callerUid, String callerPackageName) {
Chalard Jean88953062018-02-21 18:43:54 +09002159 if (!checkSettingsPermission()) {
Lorenzo Colittif2514122021-03-12 22:50:57 +09002160 // There is no need to track the effective UID of the request here. If the caller lacks
2161 // the settings permission, the effective UID is the same as the calling ID.
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002162 nc.setSingleUid(callerUid);
Chalard Jean88953062018-02-21 18:43:54 +09002163 }
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002164 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kestingc5cadf62020-03-16 18:15:28 -07002165 nc.setAdministratorUids(new int[0]);
Qingxi Libb3347b2020-01-17 17:54:27 -08002166
2167 // Clear owner UID; this can never come from an app.
2168 nc.setOwnerUid(INVALID_UID);
Chalard Jean88953062018-02-21 18:43:54 +09002169 }
2170
Chalard Jeana43eede2018-03-20 19:13:57 +09002171 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002172 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jeana43eede2018-03-20 19:13:57 +09002173 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2174 }
2175 }
2176
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09002177 @Override
2178 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2179 enforceAccessPermission();
2180 final int callerUid = Binder.getCallingUid();
2181 final long token = Binder.clearCallingIdentity();
2182 try {
2183 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2184 } finally {
2185 Binder.restoreCallingIdentity(token);
2186 }
2187 }
2188
junyulai57840802021-03-03 12:09:05 +08002189 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colitti98097292015-05-14 17:28:27 +09002190 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002191 public NetworkState[] getAllNetworkState() {
paulhud70b7dd2019-08-12 16:25:11 +08002192 // This contains IMSI details, so make sure the caller is privileged.
paulhu5e094422021-01-25 18:53:17 +08002193 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfe0b08d2014-12-02 18:30:14 -08002194
Serik Beketayeveb7e8c62021-01-15 16:47:25 -08002195 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huang20605e52021-04-17 13:46:25 +08002196 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulai57840802021-03-03 12:09:05 +08002197 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2198 // NetworkAgentInfo.
Aaron Huangc8081e92021-04-20 17:19:46 +08002199 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaidddf2b62020-12-29 19:17:01 +08002200 if (nai != null && nai.networkInfo.isConnected()) {
junyulai57840802021-03-03 12:09:05 +08002201 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangc8081e92021-04-20 17:19:46 +08002202 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2203 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002204 }
2205 }
2206 return result.toArray(new NetworkState[result.size()]);
2207 }
2208
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002209 @Override
junyulai57840802021-03-03 12:09:05 +08002210 @NonNull
Aaron Huang20605e52021-04-17 13:46:25 +08002211 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulai57840802021-03-03 12:09:05 +08002212 // This contains IMSI details, so make sure the caller is privileged.
2213 PermissionUtils.enforceNetworkStackPermission(mContext);
2214
2215 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2216 for (Network network : getAllNetworks()) {
2217 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2218 // TODO: Consider include SUSPENDED networks, which should be considered as
2219 // temporary shortage of connectivity of a connected network.
2220 if (nai != null && nai.networkInfo.isConnected()) {
2221 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2222 // NetworkCapabilities, which may contain UIDs of apps to which the
2223 // network applies. Should the UIDs be cleared so as not to leak or
2224 // interfere ?
2225 result.add(nai.getNetworkStateSnapshot());
2226 }
2227 }
2228 return result;
2229 }
2230
2231 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002232 public boolean isActiveNetworkMetered() {
2233 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002234
Qingxi Libf6bf082020-01-08 12:51:49 -08002235 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkey41a72692017-07-12 10:50:42 -06002236 if (caps != null) {
2237 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2238 } else {
2239 // Always return the most conservative value
2240 return true;
2241 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002242 }
2243
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002244 /**
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002245 * Ensures that the system cannot call a particular method.
2246 */
2247 private boolean disallowedBecauseSystemCaller() {
2248 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admal6d761f92019-04-05 10:06:37 -07002249 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2250 // for devices launched with Q and above. However, existing devices upgrading to Q and
2251 // above must continued to be supported for few more releases.
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002252 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admal6d761f92019-04-05 10:06:37 -07002253 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002254 log("This method exists only for app backwards compatibility"
2255 + " and must not be called by system services.");
2256 return true;
2257 }
2258 return false;
2259 }
2260
2261 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002262 * Ensure that a network route exists to deliver traffic to the specified
2263 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002264 * @param networkType the type of the network over which traffic to the
2265 * specified host is to be routed
2266 * @param hostAddress the IP address of the host to which the route is
2267 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002268 * @return {@code true} on success, {@code false} on failure
2269 */
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09002270 @Override
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002271 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2272 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002273 if (disallowedBecauseSystemCaller()) {
2274 return false;
2275 }
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002276 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002277 if (mProtectedNetworks.contains(networkType)) {
paulhud70b7dd2019-08-12 16:25:11 +08002278 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002279 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002280
Chad Brubaker83ec7fc2014-02-14 13:24:29 -08002281 InetAddress addr;
2282 try {
2283 addr = InetAddress.getByAddress(hostAddress);
2284 } catch (UnknownHostException e) {
2285 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2286 return false;
2287 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002288
The Android Open Source Project28527d22009-03-03 19:31:44 -08002289 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002290 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002291 return false;
2292 }
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002293
2294 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2295 if (nai == null) {
2296 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2297 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2298 } else {
2299 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2300 }
2301 return false;
Ken Mixter7caa36a2013-11-07 22:08:24 -08002302 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002303
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002304 DetailedState netState;
2305 synchronized (nai) {
2306 netState = nai.networkInfo.getDetailedState();
2307 }
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002308
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002309 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002310 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07002311 log("requestRouteToHostAddress on down network "
2312 + "(" + networkType + ") - dropped"
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002313 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002314 }
2315 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002316 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002317
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002318 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002319 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002320 try {
Paul Jensen8b6260f2014-07-11 08:17:29 -04002321 LinkProperties lp;
2322 int netId;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002323 synchronized (nai) {
2324 lp = nai.linkProperties;
Serik Beketayev284cb872020-12-07 22:43:07 -08002325 netId = nai.network.getNetId();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002326 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002327 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colitti7e27c542021-04-10 01:01:43 +09002328 if (DBG) {
2329 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2330 }
Wink Saville690cb182013-06-29 21:10:57 -07002331 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002332 } finally {
2333 Binder.restoreCallingIdentity(token);
2334 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002335 }
2336
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002337 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002338 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002339 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002340 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002341 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002342 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002343 if (bestRoute.getGateway().equals(addr)) {
2344 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08002345 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002346 } else {
2347 // if we will connect to this through another route, add a direct route
2348 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08002349 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002350 }
2351 }
Lorenzo Colittice3a70b2015-09-04 13:12:42 +09002352 if (DBG) log("Adding legacy route " + bestRoute +
2353 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wangfd3fa0a2020-11-06 14:48:30 +08002354
2355 final String dst = bestRoute.getDestinationLinkAddress().toString();
2356 final String nextHop = bestRoute.hasGateway()
2357 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002358 try {
Chiachang Wangfd3fa0a2020-11-06 14:48:30 +08002359 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2360 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002361 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002362 return false;
2363 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002364 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002365 }
2366
paulhu0a2aa802021-01-08 00:51:49 +08002367 class DnsResolverUnsolicitedEventCallback extends
2368 IDnsResolverUnsolicitedEventListener.Stub {
dalykf4977492018-03-05 12:42:22 -05002369 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002370 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalykf4977492018-03-05 12:42:22 -05002371 try {
2372 mHandler.sendMessage(mHandler.obtainMessage(
2373 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu0a2aa802021-01-08 00:51:49 +08002374 new PrivateDnsValidationUpdate(event.netId,
2375 InetAddresses.parseNumericAddress(event.ipAddress),
2376 event.hostname, event.validation)));
dalykf4977492018-03-05 12:42:22 -05002377 } catch (IllegalArgumentException e) {
2378 loge("Error parsing ip address in validation event");
2379 }
2380 }
Chiachang Wangea46de72018-11-27 18:00:05 +08002381
2382 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002383 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2384 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wangea46de72018-11-27 18:00:05 +08002385 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2386 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2387 // event callback for certain nai. e.g. cellular. Register here to pass to
2388 // NetworkMonitor instead.
Remi NGUYEN VAN76b14fd2019-02-04 10:25:11 +09002389 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2390 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2391 // multiple NetworkMonitor registrants.
Chalard Jean1bc77a92021-02-04 13:12:59 +09002392 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu0a2aa802021-01-08 00:51:49 +08002393 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wangea46de72018-11-27 18:00:05 +08002394 }
2395 }
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09002396
2397 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002398 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2399 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2400 event.prefixAddress, event.prefixLength));
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09002401 }
dalykf4977492018-03-05 12:42:22 -05002402
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002403 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002404 public int getInterfaceVersion() {
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002405 return this.VERSION;
2406 }
2407
2408 @Override
2409 public String getInterfaceHash() {
2410 return this.HASH;
2411 }
paulhu0a2aa802021-01-08 00:51:49 +08002412 }
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002413
2414 @VisibleForTesting
paulhu0a2aa802021-01-08 00:51:49 +08002415 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2416 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002417
paulhu0a2aa802021-01-08 00:51:49 +08002418 private void registerDnsResolverUnsolicitedEventListener() {
dalykf4977492018-03-05 12:42:22 -05002419 try {
paulhu0a2aa802021-01-08 00:51:49 +08002420 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalykf4977492018-03-05 12:42:22 -05002421 } catch (Exception e) {
paulhu0a2aa802021-01-08 00:51:49 +08002422 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalykf4977492018-03-05 12:42:22 -05002423 }
2424 }
2425
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002426 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002427 @Override
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002428 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002429 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2430 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002431 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002432 };
2433
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002434 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002435 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002436 setUidBlockedReasons(uid, blockedReasons);
junyulai5ab727b2018-08-07 19:50:45 +08002437 }
2438
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002439 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002440 for (String permission : permissions) {
2441 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002442 return true;
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002443 }
2444 }
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002445 return false;
2446 }
2447
paulhua9a6e2a2019-03-22 16:35:06 +08002448 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2449 for (String permission : permissions) {
2450 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2451 return true;
2452 }
2453 }
2454 return false;
2455 }
2456
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002457 private void enforceAnyPermissionOf(String... permissions) {
2458 if (!checkAnyPermissionOf(permissions)) {
2459 throw new SecurityException("Requires one of the following permissions: "
2460 + String.join(", ", permissions) + ".");
2461 }
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002462 }
2463
Paul Jensen57d231c2014-08-29 09:54:01 -04002464 private void enforceInternetPermission() {
2465 mContext.enforceCallingOrSelfPermission(
2466 android.Manifest.permission.INTERNET,
2467 "ConnectivityService");
2468 }
2469
The Android Open Source Project28527d22009-03-03 19:31:44 -08002470 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002471 mContext.enforceCallingOrSelfPermission(
2472 android.Manifest.permission.ACCESS_NETWORK_STATE,
2473 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002474 }
2475
paulhu4418c8e2021-02-22 15:40:43 +08002476 /**
2477 * Performs a strict and comprehensive check of whether a calling package is allowed to
2478 * change the state of network, as the condition differs for pre-M, M+, and
2479 * privileged/preinstalled apps. The caller is expected to have either the
2480 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2481 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2482 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2483 * permission and cannot be revoked. See http://b/23597341
2484 *
2485 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2486 * of this app will be updated to the current time.
2487 */
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002488 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhu4418c8e2021-02-22 15:40:43 +08002489 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2490 == PackageManager.PERMISSION_GRANTED) {
2491 return;
2492 }
2493
2494 if (callingPkg == null) {
2495 throw new SecurityException("Calling package name is null.");
2496 }
2497
2498 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2499 final int uid = mDeps.getCallingUid();
2500 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2501 callingPkg, callingAttributionTag, null /* message */);
2502
2503 if (mode == AppOpsManager.MODE_ALLOWED) {
2504 return;
2505 }
2506
2507 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2508 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2509 return;
2510 }
2511
2512 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2513 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2514 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002515 }
2516
Charles He729f0b42017-05-15 17:07:18 +01002517 private void enforceSettingsPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002518 enforceAnyPermissionOf(
Charles He729f0b42017-05-15 17:07:18 +01002519 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002520 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He729f0b42017-05-15 17:07:18 +01002521 }
2522
paulhud70b7dd2019-08-12 16:25:11 +08002523 private void enforceNetworkFactoryPermission() {
paulhu44939832020-03-04 09:43:41 +08002524 enforceAnyPermissionOf(
paulhud70b7dd2019-08-12 16:25:11 +08002525 android.Manifest.permission.NETWORK_FACTORY,
paulhu44939832020-03-04 09:43:41 +08002526 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhud70b7dd2019-08-12 16:25:11 +08002527 }
2528
Aaron Huange5c0ba32020-04-14 13:43:49 +08002529 private void enforceNetworkFactoryOrSettingsPermission() {
2530 enforceAnyPermissionOf(
2531 android.Manifest.permission.NETWORK_SETTINGS,
2532 android.Manifest.permission.NETWORK_FACTORY,
2533 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2534 }
2535
2536 private void enforceNetworkFactoryOrTestNetworksPermission() {
2537 enforceAnyPermissionOf(
2538 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2539 android.Manifest.permission.NETWORK_FACTORY,
2540 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2541 }
2542
Chalard Jean88953062018-02-21 18:43:54 +09002543 private boolean checkSettingsPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002544 return checkAnyPermissionOf(
2545 android.Manifest.permission.NETWORK_SETTINGS,
2546 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean88953062018-02-21 18:43:54 +09002547 }
2548
2549 private boolean checkSettingsPermission(int pid, int uid) {
2550 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002551 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2552 || PERMISSION_GRANTED == mContext.checkPermission(
2553 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean88953062018-02-21 18:43:54 +09002554 }
2555
paulhud70b7dd2019-08-12 16:25:11 +08002556 private void enforceNetworkStackOrSettingsPermission() {
2557 enforceAnyPermissionOf(
2558 android.Manifest.permission.NETWORK_SETTINGS,
2559 android.Manifest.permission.NETWORK_STACK,
2560 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2561 }
2562
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002563 private void enforceNetworkStackSettingsOrSetup() {
2564 enforceAnyPermissionOf(
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002565 android.Manifest.permission.NETWORK_SETTINGS,
2566 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov4753f402019-01-25 08:50:06 +00002567 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002568 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov4753f402019-01-25 08:50:06 +00002569 }
2570
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01002571 private void enforceAirplaneModePermission() {
2572 enforceAnyPermissionOf(
2573 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2574 android.Manifest.permission.NETWORK_SETTINGS,
2575 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2576 android.Manifest.permission.NETWORK_STACK,
2577 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2578 }
2579
James Mattis981865c2021-01-26 14:05:36 -08002580 private void enforceOemNetworkPreferencesPermission() {
2581 mContext.enforceCallingOrSelfPermission(
2582 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2583 "ConnectivityService");
2584 }
2585
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07002586 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002587 return checkAnyPermissionOf(
2588 android.Manifest.permission.NETWORK_STACK,
2589 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07002590 }
2591
Cody Kestingd292a332020-01-05 14:06:39 -08002592 private boolean checkNetworkStackPermission(int pid, int uid) {
2593 return checkAnyPermissionOf(pid, uid,
2594 android.Manifest.permission.NETWORK_STACK,
2595 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2596 }
2597
paulhua9a6e2a2019-03-22 16:35:06 +08002598 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2599 return checkAnyPermissionOf(pid, uid,
2600 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jeancbc7c5b2020-04-13 21:54:58 +09002601 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2602 android.Manifest.permission.NETWORK_SETTINGS);
paulhua9a6e2a2019-03-22 16:35:06 +08002603 }
2604
Hugo Benichic4899352016-07-19 15:59:27 +09002605 private void enforceConnectivityRestrictedNetworksPermission() {
2606 try {
2607 mContext.enforceCallingOrSelfPermission(
2608 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2609 "ConnectivityService");
2610 return;
2611 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhud70b7dd2019-08-12 16:25:11 +08002612 // TODO: Remove this fallback check after all apps have declared
2613 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2614 mContext.enforceCallingOrSelfPermission(
2615 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2616 "ConnectivityService");
Hugo Benichic4899352016-07-19 15:59:27 +09002617 }
2618
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002619 private void enforceKeepalivePermission() {
Lorenzo Colittib793d602015-09-08 13:21:48 +09002620 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002621 }
2622
Roshan Pius332e7a22021-03-21 17:55:29 +00002623 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2624 return PERMISSION_GRANTED == mContext.checkPermission(
2625 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2626 }
2627
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09002628 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002629 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002630 }
2631
2632 private void sendInetConditionBroadcast(NetworkInfo info) {
2633 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2634 }
2635
Wink Saville4f0de1e2011-08-04 15:01:58 -07002636 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002637 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002638 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002639 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002640 if (info.isFailover()) {
2641 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2642 info.setFailover(false);
2643 }
2644 if (info.getReason() != null) {
2645 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2646 }
2647 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002648 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2649 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002650 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002651 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002652 return intent;
2653 }
2654
2655 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2656 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2657 }
2658
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002659 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi47858762017-04-26 14:53:28 +09002660 synchronized (this) {
Chalard Jean9fbd93c2018-06-08 14:24:49 +09002661 if (!mSystemReady
2662 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002663 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002664 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002665 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09002666 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002667 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002668 }
2669
Dianne Hackborn6782e222015-12-09 17:22:26 -08002670 Bundle options = null;
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002671 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn2813a692014-12-04 17:46:42 -08002672 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte577c812015-09-01 08:23:04 -07002673 final NetworkInfo ni = intent.getParcelableExtra(
2674 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhud9ce33f2020-02-03 19:52:43 +08002675 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2676 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2677 options = opts.toBundle();
Chad Brubaker88a4e802018-03-08 10:37:09 -08002678 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn2813a692014-12-04 17:46:42 -08002679 }
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002680 try {
Paul Hu32fd2082021-01-26 02:53:06 +00002681 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002685 }
2686 }
2687
Remi NGUYEN VANebe52982019-06-20 18:29:36 +09002688 /**
Aaron Huang925d09b2020-06-27 07:18:23 +08002689 * Called by SystemServer through ConnectivityManager when the system is ready.
2690 */
2691 @Override
2692 public void systemReady() {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002693 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang925d09b2020-06-27 07:18:23 +08002694 throw new SecurityException("Calling Uid is not system uid.");
2695 }
2696 systemReadyInternal();
2697 }
2698
2699 /**
2700 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VANebe52982019-06-20 18:29:36 +09002701 */
2702 @VisibleForTesting
Aaron Huang925d09b2020-06-27 07:18:23 +08002703 public void systemReadyInternal() {
Aaron Huang5301b6f2020-12-08 10:03:29 +08002704 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2705 // listening network request which is sent by MultipathPolicyTracker won't be added
2706 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2707 // be called after PermissionMonitor#startMonitoring().
2708 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2709 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2710 // to ensure the tracking will be initialized correctly.
paulhubad55592019-11-19 17:55:31 +08002711 mPermissionMonitor.startMonitoring();
Chalard Jean7b09bbf2018-06-08 12:47:42 +09002712 mProxyTracker.loadGlobalProxy();
paulhu0a2aa802021-01-08 00:51:49 +08002713 registerDnsResolverUnsolicitedEventListener();
Wink Saville89c87b92013-08-29 08:55:16 -07002714
Hugo Benichi47858762017-04-26 14:53:28 +09002715 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002716 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002717 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002718 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002719 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002720 }
2721 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002722
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07002723 // Create network requests for always-on networks.
2724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
The Android Open Source Project28527d22009-03-03 19:31:44 -08002725 }
2726
The Android Open Source Project28527d22009-03-03 19:31:44 -08002727 /**
Chiachang Wangb4bba712020-12-15 15:56:00 +08002728 * Start listening for default data network activity state changes.
2729 */
2730 @Override
2731 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslina5e9bdb2021-01-21 02:04:15 +08002732 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wangb4bba712020-12-15 15:56:00 +08002733 }
2734
2735 /**
2736 * Stop listening for default data network activity state changes.
2737 */
2738 @Override
2739 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslina5e9bdb2021-01-21 02:04:15 +08002740 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wangb4bba712020-12-15 15:56:00 +08002741 }
2742
2743 /**
2744 * Check whether the default network radio is currently active.
2745 */
2746 @Override
2747 public boolean isDefaultNetworkActive() {
lucaslina5e9bdb2021-01-21 02:04:15 +08002748 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wangb4bba712020-12-15 15:56:00 +08002749 }
2750
2751 /**
Chalard Jean73d9db72018-06-04 16:52:49 +09002752 * Reads the network specific MTU size from resources.
sy.yun30043282013-09-02 05:24:09 +09002753 * and set it on it's iface.
2754 */
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002755 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2756 final String iface = newLp.getInterfaceName();
2757 final int mtu = newLp.getMtu();
Pierre Imai98f9c2c2016-02-08 16:01:40 +09002758 if (oldLp == null && mtu == 0) {
2759 // Silently ignore unset MTU value.
2760 return;
2761 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002762 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2763 if (VDBG) log("identical MTU - not setting");
2764 return;
2765 }
paulhu9bb04802019-03-08 16:35:20 +08002766 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09002767 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002768 return;
2769 }
sy.yun30043282013-09-02 05:24:09 +09002770
w19976c3455c32014-08-05 15:18:11 -07002771 // Cannot set MTU without interface name
2772 if (TextUtils.isEmpty(iface)) {
2773 loge("Setting MTU size with null iface.");
2774 return;
2775 }
2776
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002777 try {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09002778 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wangfd478312020-10-26 17:13:09 +08002779 mNetd.interfaceSetMtu(iface, mtu);
2780 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang11e9a312020-10-30 22:04:25 +08002781 loge("exception in interfaceSetMtu()" + e);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002782 }
2783 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002784
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002785 @VisibleForTesting
2786 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensena871d062015-05-13 14:05:12 -04002787
lucaslin589964b2018-11-28 19:27:52 +08002788 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt03806862014-08-06 12:00:25 -07002789 String[] values = null;
2790 if (tcpBufferSizes != null) {
2791 values = tcpBufferSizes.split(",");
2792 }
2793
2794 if (values == null || values.length != 6) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07002795 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt03806862014-08-06 12:00:25 -07002796 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2797 values = tcpBufferSizes.split(",");
2798 }
2799
2800 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2801
2802 try {
Aaron Huang11e9a312020-10-30 22:04:25 +08002803 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt03806862014-08-06 12:00:25 -07002804
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002805 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2806 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2807 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt03806862014-08-06 12:00:25 -07002808 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002809 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt03806862014-08-06 12:00:25 -07002810 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002811 }
2812 }
2813
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07002814 @Override
2815 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti756a0222017-03-21 18:54:11 +09002816 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002817 NETWORK_RESTORE_DELAY_PROP_NAME);
2818 if(restoreDefaultNetworkDelayStr != null &&
2819 restoreDefaultNetworkDelayStr.length() != 0) {
2820 try {
Narayan Kamath846fa3e2016-04-15 18:32:45 +01002821 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002822 } catch (NumberFormatException e) {
2823 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002824 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002825 // if the system property isn't set, use the value for the apn type
2826 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2827
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09002828 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2829 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002830 }
2831 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002832 }
2833
Lorenzo Colittidad88972016-03-03 17:53:46 +09002834 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2835 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2836 final long DIAG_TIME_MS = 5000;
Hugo Benichi821785c2018-09-03 08:19:02 +09002837 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yud0e42212019-07-05 11:51:34 +08002838 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colittidad88972016-03-03 17:53:46 +09002839 // Start gathering diagnostic information.
2840 netDiags.add(new NetworkDiagnostics(
2841 nai.network,
2842 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yud0e42212019-07-05 11:51:34 +08002843 privateDnsCfg,
Lorenzo Colittidad88972016-03-03 17:53:46 +09002844 DIAG_TIME_MS));
2845 }
2846
2847 for (NetworkDiagnostics netDiag : netDiags) {
2848 pw.println();
2849 netDiag.waitForMeasurements();
2850 netDiag.dump(pw);
2851 }
2852 }
2853
The Android Open Source Project28527d22009-03-03 19:31:44 -08002854 @Override
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09002855 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2856 @Nullable String[] args) {
Chiachang Wang70348a22021-04-19 10:59:24 +08002857 if (!checkDumpPermission(mContext, TAG, writer)) return;
2858
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08002859 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair9154a422017-10-26 10:08:50 -07002860 }
2861
lucaslin9d4b8642020-12-10 15:10:54 +08002862 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2863 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2864 != PackageManager.PERMISSION_GRANTED) {
2865 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002866 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin9d4b8642020-12-10 15:10:54 +08002867 + " due to missing android.permission.DUMP permission");
2868 return false;
2869 } else {
2870 return true;
2871 }
2872 }
2873
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08002874 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002875 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002876
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002877 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colittidad88972016-03-03 17:53:46 +09002878 dumpNetworkDiagnostics(pw);
2879 return;
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002880 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichif93f4482018-09-03 08:32:56 +09002881 dumpNetworks(pw);
2882 return;
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002883 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichif93f4482018-09-03 08:32:56 +09002884 dumpNetworkRequests(pw);
2885 return;
Lorenzo Colittidad88972016-03-03 17:53:46 +09002886 }
Erik Kline445cad12015-06-05 17:47:34 +09002887
Lorenzo Colitti94c93142020-01-10 00:40:28 +09002888 pw.print("NetworkProviders for:");
2889 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2890 pw.print(" " + npi.name);
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07002891 }
Lorenzo Colitti417c25c2015-06-03 11:18:24 +09002892 pw.println();
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07002893 pw.println();
2894
Chalard Jean1bc77a92021-02-04 13:12:59 +09002895 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalt31a40522014-05-13 15:36:27 -07002896 pw.print("Active default network: ");
Chalard Jean1bc77a92021-02-04 13:12:59 +09002897 if (defaultNai == null) {
Robert Greenwalt31a40522014-05-13 15:36:27 -07002898 pw.println("none");
2899 } else {
Chalard Jean1bc77a92021-02-04 13:12:59 +09002900 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002901 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002902 pw.println();
2903
James Mattis6e6fabf2021-01-10 14:24:24 -08002904 pw.print("Current per-app default networks: ");
2905 pw.increaseIndent();
2906 dumpPerAppNetworkPreferences(pw);
2907 pw.decreaseIndent();
2908 pw.println();
2909
Robert Greenwalt31a40522014-05-13 15:36:27 -07002910 pw.println("Current Networks:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002911 pw.increaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002912 dumpNetworks(pw);
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002913 pw.decreaseIndent();
Robert Greenwalt31a40522014-05-13 15:36:27 -07002914 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002915
junyulai5ab727b2018-08-07 19:50:45 +08002916 pw.println("Status for known UIDs:");
2917 pw.increaseIndent();
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002918 final int size = mUidBlockedReasons.size();
junyulai5ab727b2018-08-07 19:50:45 +08002919 for (int i = 0; i < size; i++) {
2920 // Don't crash if the array is modified while dumping in bugreports.
2921 try {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002922 final int uid = mUidBlockedReasons.keyAt(i);
2923 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2924 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankab9c396e2021-04-21 07:23:54 +00002925 + Integer.toHexString(blockedReasons));
junyulai5ab727b2018-08-07 19:50:45 +08002926 } catch (ArrayIndexOutOfBoundsException e) {
2927 pw.println(" ArrayIndexOutOfBoundsException");
2928 } catch (ConcurrentModificationException e) {
2929 pw.println(" ConcurrentModificationException");
2930 }
2931 }
2932 pw.println();
2933 pw.decreaseIndent();
2934
Robert Greenwalt31a40522014-05-13 15:36:27 -07002935 pw.println("Network Requests:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002936 pw.increaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002937 dumpNetworkRequests(pw);
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002938 pw.decreaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002939 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002940
Robert Greenwaltdbd5f312014-07-30 16:31:24 -07002941 mLegacyTypeTracker.dump(pw);
Robert Greenwaltdbd5f312014-07-30 16:31:24 -07002942
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002943 pw.println();
markchien497a0622019-09-30 14:40:57 +08002944 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002945
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002946 pw.println();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09002947 dumpAvoidBadWifiSettings(pw);
Lorenzo Colittidad88972016-03-03 17:53:46 +09002948
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09002949 pw.println();
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09002950
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002951 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt2784ed62015-06-23 15:03:33 -07002952 pw.println();
Erik Kline47401fa2015-07-09 18:24:03 +09002953 pw.println("mNetworkRequestInfoLogs (most recent first):");
2954 pw.increaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002955 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Kline47401fa2015-07-09 18:24:03 +09002956 pw.decreaseIndent();
Hugo Benichi7b3bf372016-07-11 11:05:12 +09002957
2958 pw.println();
2959 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2960 pw.increaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002961 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichi7b3bf372016-07-11 11:05:12 +09002962 pw.decreaseIndent();
Hugo Benichi23ec1c92017-03-30 10:46:05 +09002963
2964 pw.println();
2965 pw.println("NetTransition WakeLock activity (most recent first):");
2966 pw.increaseIndent();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09002967 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2968 pw.println("total releases: " + mTotalWakelockReleases);
2969 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2970 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2971 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2972 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2973 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2974 }
James Mattis6e4405f2021-04-06 17:07:42 -07002975 mWakelockLogs.reverseDump(pw);
Nathan Harold6179b142018-07-30 13:38:01 -07002976
2977 pw.println();
2978 pw.println("bandwidth update requests (by uid):");
2979 pw.increaseIndent();
2980 synchronized (mBandwidthRequests) {
2981 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2982 pw.println("[" + mBandwidthRequests.keyAt(i)
2983 + "]: " + mBandwidthRequests.valueAt(i));
2984 }
2985 }
2986 pw.decreaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002987 pw.decreaseIndent();
Nathan Harold6179b142018-07-30 13:38:01 -07002988
James Mattis6e4405f2021-04-06 17:07:42 -07002989 pw.println();
2990 pw.println("mOemNetworkPreferencesLogs (most recent first):");
2991 pw.increaseIndent();
2992 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi23ec1c92017-03-30 10:46:05 +09002993 pw.decreaseIndent();
Robert Greenwalt2784ed62015-06-23 15:03:33 -07002994 }
Remi NGUYEN VANa00a3f22019-02-18 11:20:28 +09002995
2996 pw.println();
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00002997
2998 pw.println();
2999 pw.println("Permission Monitor:");
3000 pw.increaseIndent();
3001 mPermissionMonitor.dump(pw);
3002 pw.decreaseIndent();
lucaslin3756fcc2021-01-21 02:04:35 +08003003
3004 pw.println();
3005 pw.println("Legacy network activity:");
3006 pw.increaseIndent();
3007 mNetworkActivityTracker.dump(pw);
3008 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003009 }
3010
Hugo Benichif93f4482018-09-03 08:32:56 +09003011 private void dumpNetworks(IndentingPrintWriter pw) {
3012 for (NetworkAgentInfo nai : networksSortedById()) {
3013 pw.println(nai.toString());
3014 pw.increaseIndent();
3015 pw.println(String.format(
3016 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3017 nai.numForegroundNetworkRequests(),
3018 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3019 nai.numBackgroundNetworkRequests(),
3020 nai.numNetworkRequests()));
3021 pw.increaseIndent();
3022 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3023 pw.println(nai.requestAt(i).toString());
3024 }
3025 pw.decreaseIndent();
junyulai2a4f0062021-02-03 20:15:30 +08003026 pw.println("Inactivity Timers:");
Hugo Benichif93f4482018-09-03 08:32:56 +09003027 pw.increaseIndent();
junyulai2a4f0062021-02-03 20:15:30 +08003028 nai.dumpInactivityTimers(pw);
Hugo Benichif93f4482018-09-03 08:32:56 +09003029 pw.decreaseIndent();
3030 pw.decreaseIndent();
3031 }
3032 }
3033
James Mattis6e6fabf2021-01-10 14:24:24 -08003034 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3035 pw.println("Per-App Network Preference:");
3036 pw.increaseIndent();
3037 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3038 pw.println("none");
3039 } else {
3040 pw.println(mOemNetworkPreferences.toString());
3041 }
3042 pw.decreaseIndent();
3043
3044 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3045 if (mDefaultRequest == defaultRequest) {
3046 continue;
3047 }
3048
3049 final boolean isActive = null != defaultRequest.getSatisfier();
3050 pw.println("Is per-app network active:");
3051 pw.increaseIndent();
3052 pw.println(isActive);
3053 if (isActive) {
3054 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3055 }
3056 pw.println("Tracked UIDs:");
3057 pw.increaseIndent();
3058 if (0 == defaultRequest.mRequests.size()) {
3059 pw.println("none, this should never occur.");
3060 } else {
Chiachang Wangd5034c72021-02-22 18:36:38 +08003061 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
James Mattis6e6fabf2021-01-10 14:24:24 -08003062 }
3063 pw.decreaseIndent();
3064 pw.decreaseIndent();
3065 }
3066 }
3067
Hugo Benichif93f4482018-09-03 08:32:56 +09003068 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3069 for (NetworkRequestInfo nri : requestsSortedById()) {
3070 pw.println(nri.toString());
3071 }
3072 }
3073
Hugo Benichi821785c2018-09-03 08:19:02 +09003074 /**
3075 * Return an array of all current NetworkAgentInfos sorted by network id.
3076 */
3077 private NetworkAgentInfo[] networksSortedById() {
3078 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003079 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayev284cb872020-12-07 22:43:07 -08003080 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichi821785c2018-09-03 08:19:02 +09003081 return networks;
3082 }
3083
3084 /**
3085 * Return an array of all current NetworkRequest sorted by request id.
3086 */
James Mattisf8eb49a2020-11-15 15:04:40 -08003087 @VisibleForTesting
James Mattisc449dde2020-11-20 16:08:10 -08003088 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichi821785c2018-09-03 08:19:02 +09003089 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattis622428c2020-12-02 14:12:41 -08003090 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattisf8eb49a2020-11-15 15:04:40 -08003091 // Sort the array based off the NRI containing the min requestId in its requests.
3092 Arrays.sort(requests,
3093 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3094 Comparator.comparingInt(req -> req.requestId)).requestId
3095 )
3096 );
Hugo Benichi821785c2018-09-03 08:19:02 +09003097 return requests;
3098 }
3099
Lorenzo Colittif0461852016-04-05 17:52:16 +09003100 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08003101 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwaltcf971852014-08-19 18:58:04 -07003102 if (officialNai != null && officialNai.equals(nai)) return true;
3103 if (officialNai != null || VDBG) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09003104 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwaltcf971852014-08-19 18:58:04 -07003105 " - " + nai);
3106 }
3107 return false;
3108 }
3109
Robert Greenwalt2034b912009-08-12 16:08:25 -07003110 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003111 private class NetworkStateTrackerHandler extends Handler {
3112 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003113 super(looper);
3114 }
3115
Lorenzo Colittif0461852016-04-05 17:52:16 +09003116 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003117 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3118 final NetworkAgentInfo nai = arg.first;
3119 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittif0461852016-04-05 17:52:16 +09003120 if (VDBG) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09003121 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittif0461852016-04-05 17:52:16 +09003122 }
3123 return;
3124 }
3125
3126 switch (msg.what) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003127 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003128 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin25a50472019-03-12 13:08:03 +08003129 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang11e9a312020-10-30 22:04:25 +08003130 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt948aea52014-04-11 15:53:27 -07003131 }
Chalard Jeanb5b172f2020-03-09 21:25:37 +09003132 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3133 // Make sure the original object is not mutated. NetworkAgent normally
3134 // makes a copy of the capabilities when sending the message through
3135 // the Messenger, but if this ever changes, not making a defensive copy
3136 // here will give attack vectors to clients using this code path.
3137 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Cody Kestingba343362020-04-07 16:07:33 -07003138 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
Chalard Jeanb5b172f2020-03-09 21:25:37 +09003139 }
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003140 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichi810f4912016-09-15 18:18:48 +09003141 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt948aea52014-04-11 15:53:27 -07003142 break;
3143 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003144 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003145 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09003146 processLinkPropertiesFromAgent(nai, newLp);
3147 handleUpdateLinkProperties(nai, newLp);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003148 break;
3149 }
3150 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003151 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003152 updateNetworkInfo(nai, info);
3153 break;
3154 }
Robert Greenwaltcf82b832014-05-27 13:20:24 -07003155 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jeandd753522020-12-21 18:36:52 +09003156 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwaltcf82b832014-05-27 13:20:24 -07003157 break;
3158 }
Robert Greenwaltcea86b02014-09-07 16:50:01 -07003159 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colitti72792e22019-06-04 14:37:26 +09003160 if (nai.everConnected) {
3161 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jean67b66082021-01-20 20:47:32 +09003162 // Note that if the NAI had been connected, this would affect the
3163 // score, and therefore would require re-mixing the score and performing
3164 // a rematch.
Paul Jensend4e077c2014-09-26 10:10:22 -04003165 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003166 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3167 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin25a50472019-03-12 13:08:03 +08003168 // Mark the network as temporarily accepting partial connectivity so that it
3169 // will be validated (and possibly become default) even if it only provides
3170 // partial internet access. Note that if user connects to partial connectivity
3171 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3172 // out of wifi coverage) and if the same wifi is available again, the device
3173 // will auto connect to this wifi even though the wifi has "no internet".
3174 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colitticf595362020-01-12 22:28:37 +09003175 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwaltcea86b02014-09-07 16:50:01 -07003176 break;
3177 }
junyulai21c06d02019-01-03 18:50:15 +08003178 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003179 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colittid1039d12015-06-15 14:29:22 +09003180 break;
3181 }
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003182 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09003183 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003184 if (!nai.supportsUnderlyingNetworks()) {
3185 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3186 break;
3187 }
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09003188
Remi NGUYEN VANd793eb32020-12-25 12:45:46 +09003189 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09003190
3191 if (isLegacyLockdownNai(nai)
3192 && (underlying == null || underlying.size() != 1)) {
3193 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3194 + " must have exactly one underlying network: " + underlying);
3195 }
3196
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003197 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3198 nai.declaredUnderlyingNetworks = (underlying != null)
3199 ? underlying.toArray(new Network[0]) : null;
3200
3201 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3202 if (DBG) {
3203 log(nai.toShortString() + " changed underlying networks to "
3204 + Arrays.toString(nai.declaredUnderlyingNetworks));
3205 }
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003206 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003207 notifyIfacesChangedForNetworkStats();
3208 }
Daniel Bright60f02ed2020-06-15 16:10:01 -07003209 break;
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003210 }
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003211 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3212 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3213 nai.teardownDelayMs = msg.arg1;
3214 } else {
3215 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3216 }
Chalard Jeane634b282021-03-05 23:07:53 +09003217 break;
3218 }
3219 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3220 nai.setLingerDuration((int) arg.second);
3221 break;
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003222 }
Lorenzo Colittif0461852016-04-05 17:52:16 +09003223 }
3224 }
3225
3226 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3227 switch (msg.what) {
3228 default:
3229 return false;
lucaslin8cf57f52019-10-22 18:27:33 +08003230 case EVENT_PROBE_STATUS_CHANGED: {
3231 final Integer netId = (Integer) msg.obj;
3232 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3233 if (nai == null) {
3234 break;
3235 }
3236 final boolean probePrivateDnsCompleted =
3237 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3238 final boolean privateDnsBroken =
3239 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3240 if (probePrivateDnsCompleted) {
3241 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3242 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003243 updateCapabilitiesForNetwork(nai);
lucaslin8cf57f52019-10-22 18:27:33 +08003244 }
3245 // Only show the notification when the private DNS is broken and the
3246 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colitticf595362020-01-12 22:28:37 +09003247 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucaslin8cf57f52019-10-22 18:27:33 +08003248 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3249 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003250 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucaslin8cf57f52019-10-22 18:27:33 +08003251 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3252 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3253 // private DNS is broken, it means this network is being reevaluated.
3254 // Either probing private DNS is not necessary any more or it hasn't been
3255 // done yet. In either case, the networkCapabilities should be updated to
3256 // reflect the new status.
3257 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003258 updateCapabilitiesForNetwork(nai);
Lorenzo Colitticf595362020-01-12 22:28:37 +09003259 nai.networkAgentConfig.hasShownBroken = false;
lucaslin8cf57f52019-10-22 18:27:33 +08003260 }
3261 break;
3262 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003263 case EVENT_NETWORK_TESTED: {
Cody Kestingd292a332020-01-05 14:06:39 -08003264 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3265
3266 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Klinec06d4f92018-01-11 21:07:29 +09003267 if (nai == null) break;
3268
Cody Kestingd292a332020-01-05 14:06:39 -08003269 handleNetworkTested(nai, results.mTestResult,
3270 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003271 break;
3272 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003273 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09003274 final int netId = msg.arg2;
Hugo Benichi7f919fe2017-04-21 15:07:12 +09003275 final boolean visible = toBool(msg.arg1);
Erik Kline076bd3d2018-03-21 07:18:33 -07003276 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin On3fd101e2016-10-11 15:10:46 -07003277 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen783c0e02015-06-16 14:27:36 -04003278 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3279 nai.lastCaptivePortalDetected = visible;
3280 nai.everCaptivePortalDetected |= visible;
Calvin On3fd101e2016-10-11 15:10:46 -07003281 if (nai.lastCaptivePortalDetected &&
paulhu79260c22021-03-17 20:30:33 +08003282 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3283 == getCaptivePortalMode()) {
Chalard Jean373391b2019-12-10 21:07:02 +09003284 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003285 nai.onPreventAutomaticReconnect();
Calvin On3fd101e2016-10-11 15:10:46 -07003286 teardownUnneededNetwork(nai);
3287 break;
3288 }
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003289 updateCapabilitiesForNetwork(nai);
Paul Jensen783c0e02015-06-16 14:27:36 -04003290 }
3291 if (!visible) {
lucaslin1ac72392019-01-24 15:55:30 +08003292 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin25a50472019-03-12 13:08:03 +08003293 // notifications belong to the same network may be cleared unexpectedly.
lucaslin1ac72392019-01-24 15:55:30 +08003294 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3295 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen8ba5ffb2014-07-15 12:07:36 -04003296 } else {
Paul Jensenc3deb112014-08-25 22:45:39 -04003297 if (nai == null) {
3298 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3299 break;
3300 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003301 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittib268f9f2016-08-22 16:46:40 +09003302 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitticf595362020-01-12 22:28:37 +09003303 (PendingIntent) msg.obj,
3304 nai.networkAgentConfig.explicitlySelected);
fionaxu5447c492016-05-23 16:33:16 -07003305 }
Paul Jensen77cbca52014-05-15 10:33:05 -04003306 }
Paul Jensen77cbca52014-05-15 10:33:05 -04003307 break;
3308 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003309 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline076bd3d2018-03-21 07:18:33 -07003310 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinec06d4f92018-01-11 21:07:29 +09003311 if (nai == null) break;
3312
Erik Kline076bd3d2018-03-21 07:18:33 -07003313 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinec06d4f92018-01-11 21:07:29 +09003314 break;
3315 }
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003316 case EVENT_CAPPORT_DATA_CHANGED: {
3317 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3318 if (nai == null) break;
Hai Shalom492febb2021-01-11 18:45:34 -08003319 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003320 break;
3321 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003322 }
Lorenzo Colittif0461852016-04-05 17:52:16 +09003323 return true;
3324 }
3325
Cody Kestingd292a332020-01-05 14:06:39 -08003326 private void handleNetworkTested(
3327 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3328 final boolean wasPartial = nai.partialConnectivity;
3329 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3330 final boolean partialConnectivityChanged =
3331 (wasPartial != nai.partialConnectivity);
3332
3333 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3334 final boolean wasValidated = nai.lastValidated;
Chalard Jean1bc77a92021-02-04 13:12:59 +09003335 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kestingd292a332020-01-05 14:06:39 -08003336
3337 if (DBG) {
3338 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3339 ? " with redirect to " + redirectUrl
3340 : "";
Chalard Jean373391b2019-12-10 21:07:02 +09003341 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kestingd292a332020-01-05 14:06:39 -08003342 }
3343 if (valid != nai.lastValidated) {
Cody Kestingd292a332020-01-05 14:06:39 -08003344 final int oldScore = nai.getCurrentScore();
3345 nai.lastValidated = valid;
3346 nai.everValidated |= valid;
3347 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kestingd292a332020-01-05 14:06:39 -08003348 if (valid) {
3349 handleFreshlyValidatedNetwork(nai);
3350 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3351 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayev284cb872020-12-07 22:43:07 -08003352 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003353 NotificationType.NO_INTERNET);
Serik Beketayev284cb872020-12-07 22:43:07 -08003354 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003355 NotificationType.LOST_INTERNET);
Serik Beketayev284cb872020-12-07 22:43:07 -08003356 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003357 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayev284cb872020-12-07 22:43:07 -08003358 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003359 NotificationType.PRIVATE_DNS_BROKEN);
3360 // If network becomes valid, the hasShownBroken should be reset for
3361 // that network so that the notification will be fired when the private
3362 // DNS is broken again.
3363 nai.networkAgentConfig.hasShownBroken = false;
3364 }
3365 } else if (partialConnectivityChanged) {
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003366 updateCapabilitiesForNetwork(nai);
Cody Kestingd292a332020-01-05 14:06:39 -08003367 }
3368 updateInetCondition(nai);
3369 // Let the NetworkAgent know the state of its network
Cody Kestingd292a332020-01-05 14:06:39 -08003370 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003371 nai.onValidationStatusChanged(
3372 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3373 redirectUrl);
Cody Kestingd292a332020-01-05 14:06:39 -08003374
3375 // If NetworkMonitor detects partial connectivity before
3376 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3377 // immediately. Re-notify partial connectivity silently if no internet
3378 // notification already there.
3379 if (!wasPartial && nai.partialConnectivity) {
3380 // Remove delayed message if there is a pending message.
3381 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3382 handlePromptUnvalidated(nai.network);
3383 }
3384
3385 if (wasValidated && !nai.lastValidated) {
3386 handleNetworkUnvalidated(nai);
3387 }
3388 }
3389
Calvin On3fd101e2016-10-11 15:10:46 -07003390 private int getCaptivePortalMode() {
3391 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08003392 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3393 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin On3fd101e2016-10-11 15:10:46 -07003394 }
3395
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003396 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3397 switch (msg.what) {
3398 default:
3399 return false;
3400 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3401 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3402 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3403 handleLingerComplete(nai);
3404 }
3405 break;
3406 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003407 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3408 handleNetworkAgentRegistered(msg);
3409 break;
3410 }
3411 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3412 handleNetworkAgentDisconnected(msg);
3413 break;
3414 }
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003415 }
3416 return true;
3417 }
3418
Lorenzo Colittif0461852016-04-05 17:52:16 +09003419 @Override
3420 public void handleMessage(Message msg) {
lifr1c0d9b22021-03-10 13:58:14 +08003421 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN8156bbe2020-01-14 19:48:18 +09003422 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittif0461852016-04-05 17:52:16 +09003423 maybeHandleNetworkAgentMessage(msg);
3424 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003425 }
3426 }
3427
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003428 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean15347192019-05-30 14:58:29 +09003429 private final int mNetId;
3430 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003431
3432 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayev284cb872020-12-07 22:43:07 -08003433 mNetId = nai.network.getNetId();
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09003434 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003435 }
3436
3437 @Override
3438 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3439 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean15347192019-05-30 14:58:29 +09003440 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003441 }
3442
3443 @Override
3444 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003445 // Legacy version of notifyNetworkTestedWithExtras.
3446 // Would only be called if the system has a NetworkStack module older than the
3447 // framework, which does not happen in practice.
Aaron Huang11e9a312020-10-30 22:04:25 +08003448 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kestingd292a332020-01-05 14:06:39 -08003449 }
3450
3451 @Override
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003452 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VANfb0774e2020-04-24 20:56:39 +09003453 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3454 // the same looper so messages will be processed in sequence.
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003455 final Message msg = mTrackerHandler.obtainMessage(
3456 EVENT_NETWORK_TESTED,
3457 new NetworkTestedResults(
3458 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kestingd292a332020-01-05 14:06:39 -08003459 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003460
3461 // Invoke ConnectivityReport generation for this Network test event.
3462 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3463 if (nai == null) return;
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003464
3465 final PersistableBundle extras = new PersistableBundle();
3466 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3467 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3468 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3469
Aaron Huang0d1be642021-01-21 15:47:41 +08003470 ConnectivityReportEvent reportEvent =
3471 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3472 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3473 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003474 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003475 }
3476
3477 @Override
3478 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3479 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3480 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean15347192019-05-30 14:58:29 +09003481 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003482 }
3483
3484 @Override
lucaslin8cf57f52019-10-22 18:27:33 +08003485 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3486 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3487 EVENT_PROBE_STATUS_CHANGED,
3488 probesCompleted, probesSucceeded, new Integer(mNetId)));
3489 }
3490
3491 @Override
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003492 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3493 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3494 EVENT_CAPPORT_DATA_CHANGED,
3495 0, mNetId, data));
3496 }
3497
3498 @Override
Remi NGUYEN VAN8b3999c2019-02-07 21:29:57 +09003499 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003500 final Intent intent = new Intent(action);
Remi NGUYEN VAN8b3999c2019-02-07 21:29:57 +09003501 intent.setPackage(packageName);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003502
3503 final PendingIntent pendingIntent;
3504 // Only the system server can register notifications with package "android"
3505 final long token = Binder.clearCallingIdentity();
3506 try {
paulhu68426192020-06-09 19:07:03 +08003507 pendingIntent = PendingIntent.getBroadcast(
3508 mContext,
3509 0 /* requestCode */,
3510 intent,
3511 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003512 } finally {
3513 Binder.restoreCallingIdentity(token);
3514 }
3515 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3516 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean15347192019-05-30 14:58:29 +09003517 mNetId, pendingIntent));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003518 }
3519
3520 @Override
3521 public void hideProvisioningNotification() {
3522 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean15347192019-05-30 14:58:29 +09003523 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003524 }
Remi NGUYEN VANe72fe2b2019-04-05 15:15:48 +09003525
3526 @Override
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003527 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kesting6784cf62020-05-11 10:06:51 -07003528 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kesting1d326382020-01-06 16:55:35 -08003529 }
3530
3531 @Override
Remi NGUYEN VANe72fe2b2019-04-05 15:15:48 +09003532 public int getInterfaceVersion() {
3533 return this.VERSION;
3534 }
Paul Trautrim69929da2020-01-23 14:55:57 +09003535
3536 @Override
3537 public String getInterfaceHash() {
3538 return this.HASH;
3539 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003540 }
3541
Cody Kesting6784cf62020-05-11 10:06:51 -07003542 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kesting43a47ef2020-05-15 10:36:01 -07003543 log("Data stall detected with methods: " + p.detectionMethod);
3544
Cody Kesting6784cf62020-05-11 10:06:51 -07003545 final PersistableBundle extras = new PersistableBundle();
Cody Kesting43a47ef2020-05-15 10:36:01 -07003546 int detectionMethod = 0;
3547 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3548 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3549 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3550 }
3551 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3552 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3553 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3554 p.tcpMetricsCollectionPeriodMillis);
3555 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kesting6784cf62020-05-11 10:06:51 -07003556 }
3557
Cody Kestingb5c7abd2020-04-15 12:33:28 -07003558 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kesting6784cf62020-05-11 10:06:51 -07003559 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang0d1be642021-01-21 15:47:41 +08003560 new Pair<>(p.timestampMillis, extras));
Cody Kestingb5c7abd2020-04-15 12:33:28 -07003561
3562 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3563 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3564 // the cost of going through two handlers.
3565 mConnectivityDiagnosticsHandler.sendMessage(msg);
3566 }
3567
Cody Kesting43a47ef2020-05-15 10:36:01 -07003568 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3569 return (p.detectionMethod & detectionMethod) != 0;
3570 }
3571
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003572 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3573 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline076bd3d2018-03-21 07:18:33 -07003574 }
3575
Erik Klinee6d899a2018-06-26 18:53:43 +09003576 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3577 if (nai == null) return;
3578 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3579 // in order to restart a validation pass from within netd.
3580 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3581 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayev284cb872020-12-07 22:43:07 -08003582 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinee6d899a2018-06-26 18:53:43 +09003583 }
3584 }
3585
Erik Klinec06d4f92018-01-11 21:07:29 +09003586 private void handlePrivateDnsSettingsChanged() {
3587 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3588
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003589 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline076bd3d2018-03-21 07:18:33 -07003590 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003591 if (networkRequiresPrivateDnsValidation(nai)) {
dalykf4977492018-03-05 12:42:22 -05003592 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3593 }
Erik Klinec06d4f92018-01-11 21:07:29 +09003594 }
3595 }
3596
Erik Kline076bd3d2018-03-21 07:18:33 -07003597 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3598 // Private DNS only ever applies to networks that might provide
3599 // Internet access and therefore also require validation.
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003600 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Klinec06d4f92018-01-11 21:07:29 +09003601
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003602 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline076bd3d2018-03-21 07:18:33 -07003603 // schedule DNS resolutions. If a DNS resolution is required the
3604 // result will be sent back to us.
Lorenzo Colitti260d9982019-05-31 15:41:29 +09003605 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline076bd3d2018-03-21 07:18:33 -07003606
3607 // With Private DNS bypass support, we can proceed to update the
3608 // Private DNS config immediately, even if we're in strict mode
3609 // and have not yet resolved the provider name into a set of IPs.
3610 updatePrivateDns(nai, cfg);
3611 }
3612
3613 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3614 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayev284cb872020-12-07 22:43:07 -08003615 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinec06d4f92018-01-11 21:07:29 +09003616 }
3617
dalykf4977492018-03-05 12:42:22 -05003618 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3619 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3620 if (nai == null) {
3621 return;
3622 }
3623 mDnsManager.updatePrivateDnsValidation(update);
3624 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3625 }
3626
paulhu0a2aa802021-01-08 00:51:49 +08003627 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003628 int prefixLength) {
3629 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3630 if (nai == null) return;
3631
paulhu0a2aa802021-01-08 00:51:49 +08003632 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3633 netId, operation, prefixAddress, prefixLength));
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003634
3635 IpPrefix prefix = null;
paulhu0a2aa802021-01-08 00:51:49 +08003636 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003637 try {
paulhu0a2aa802021-01-08 00:51:49 +08003638 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003639 prefixLength);
3640 } catch (IllegalArgumentException e) {
paulhu0a2aa802021-01-08 00:51:49 +08003641 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003642 return;
3643 }
3644 }
3645
Lorenzo Colittifff75392020-04-01 20:16:30 +09003646 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003647 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3648 }
3649
Hai Shalom492febb2021-01-11 18:45:34 -08003650 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003651 @Nullable final CaptivePortalData data) {
Hai Shalom492febb2021-01-11 18:45:34 -08003652 nai.capportApiData = data;
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003653 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3654 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3655 }
3656
Chalard Jeand915e362019-12-04 18:49:18 +09003657 /**
junyulai2a4f0062021-02-03 20:15:30 +08003658 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jeand915e362019-12-04 18:49:18 +09003659 * @param nai the agent info to update
3660 * @param now the timestamp of the event causing this update
junyulai2a4f0062021-02-03 20:15:30 +08003661 * @return whether the network was inactive as a result of this update
Chalard Jeand915e362019-12-04 18:49:18 +09003662 */
junyulai2a4f0062021-02-03 20:15:30 +08003663 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3664 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3665 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003666 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2a4f0062021-02-03 20:15:30 +08003667 // one lingered request, set inactive.
3668 nai.updateInactivityTimer();
junyulaif6d98ec2020-12-14 18:41:52 +08003669 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2a4f0062021-02-03 20:15:30 +08003670 if (DBG) log("Unsetting inactive " + nai.toShortString());
3671 nai.unsetInactive();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003672 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2a4f0062021-02-03 20:15:30 +08003673 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jeand915e362019-12-04 18:49:18 +09003674 if (DBG) {
junyulai2a4f0062021-02-03 20:15:30 +08003675 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3676 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jeand915e362019-12-04 18:49:18 +09003677 }
junyulai2a4f0062021-02-03 20:15:30 +08003678 nai.setInactive();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003679 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jeand915e362019-12-04 18:49:18 +09003680 return true;
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003681 }
Chalard Jeand915e362019-12-04 18:49:18 +09003682 return false;
Paul Jensen935ceef2014-11-25 15:26:53 -05003683 }
3684
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003685 private void handleNetworkAgentRegistered(Message msg) {
3686 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3687 if (!mNetworkAgentInfos.contains(nai)) {
3688 return;
3689 }
3690
3691 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3692 if (VDBG) log("NetworkAgent registered");
3693 } else {
3694 loge("Error connecting NetworkAgent");
3695 mNetworkAgentInfos.remove(nai);
3696 if (nai != null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09003697 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003698 synchronized (mNetworkForNetId) {
3699 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003700 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003701 mNetIdManager.releaseNetId(nai.network.getNetId());
3702 // Just in case.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003703 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003704 }
3705 }
3706 }
Paul Jensen935ceef2014-11-25 15:26:53 -05003707
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003708 private void handleNetworkAgentDisconnected(Message msg) {
3709 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3710 if (mNetworkAgentInfos.contains(nai)) {
3711 disconnectAndDestroyNetwork(nai);
3712 }
3713 }
3714
Chalard Jeanefaf6532018-05-11 20:19:20 +09003715 // Destroys a network, remove references to it from the internal state managed by
3716 // ConnectivityService, free its interfaces and clean up.
3717 // Must be called on the Handler thread.
3718 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean4deee632019-11-05 14:40:23 +09003719 ensureRunningOnConnectivityServiceThread();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003720 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09003721 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003722 }
lucaslinb5b671a2019-02-12 15:30:13 +08003723 // Clear all notifications of this network.
Serik Beketayev284cb872020-12-07 22:43:07 -08003724 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003725 // A network agent has disconnected.
3726 // TODO - if we move the logic to the network agent (have them disconnect
3727 // because they lost all their requests or because their score isn't good)
3728 // then they would disconnect organically, report their new state and then
3729 // disconnect the channel.
3730 if (nai.networkInfo.isConnected()) {
3731 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3732 null, null);
3733 }
Chalard Jean1bc77a92021-02-04 13:12:59 +09003734 final boolean wasDefault = isDefaultNetwork(nai);
3735 if (wasDefault) {
Chalard Jeanefaf6532018-05-11 20:19:20 +09003736 mDefaultInetConditionPublished = 0;
Chalard Jeanefaf6532018-05-11 20:19:20 +09003737 }
3738 notifyIfacesChangedForNetworkStats();
3739 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3740 // by other networks that are already connected. Perhaps that can be done by
3741 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3742 // of rematchAllNetworksAndRequests
3743 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai21c06d02019-01-03 18:50:15 +08003744 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Bright60f02ed2020-06-15 16:10:01 -07003745
3746 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003747 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3748 // Disable wakeup packet monitoring for each interface.
3749 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3750 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09003751 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003752 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti714b7862019-02-19 13:21:56 +09003753 nai.clatd.update();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003754 synchronized (mNetworkForNetId) {
3755 // Remove the NetworkAgent, but don't mark the netId as
3756 // available until we've told netd to delete it below.
Serik Beketayev284cb872020-12-07 22:43:07 -08003757 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003758 }
Lorenzo Colittic284b4b2021-01-12 00:34:44 +09003759 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003760 // Remove all previously satisfied requests.
3761 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattis1238af22020-12-23 16:37:26 -08003762 final NetworkRequest request = nai.requestAt(i);
Chalard Jeane8cf3bf2019-11-05 15:07:09 +09003763 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattis622428c2020-12-02 14:12:41 -08003764 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayev284cb872020-12-07 22:43:07 -08003765 if (currentNetwork != null
3766 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattis1238af22020-12-23 16:37:26 -08003767 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003768 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3769 // rematch not to keep disconnected agents instead of setting it here ; this
3770 // will also allow removing updating the offers below.
James Mattis622428c2020-12-02 14:12:41 -08003771 nri.setSatisfier(null, null);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003772 for (final NetworkOfferInfo noi : mNetworkOffers) {
3773 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis1238af22020-12-23 16:37:26 -08003774 }
James Mattis8af2d602020-12-20 11:09:58 -08003775
Chalard Jean1bc77a92021-02-04 13:12:59 +09003776 if (mDefaultRequest == nri) {
James Mattis8af2d602020-12-20 11:09:58 -08003777 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean1bc77a92021-02-04 13:12:59 +09003778 // active at the same time. For now keep calling this with the default
James Mattis8af2d602020-12-20 11:09:58 -08003779 // network, because while incorrect this is the closest to the old (also
3780 // incorrect) behavior.
3781 mNetworkActivityTracker.updateDataActivityTracking(
3782 null /* newNetwork */, nai);
James Mattis8af2d602020-12-20 11:09:58 -08003783 ensureNetworkTransitionWakelock(nai.toShortString());
3784 }
Chalard Jeanefaf6532018-05-11 20:19:20 +09003785 }
3786 }
junyulai2a4f0062021-02-03 20:15:30 +08003787 nai.clearInactivityState();
James Mattis8af2d602020-12-20 11:09:58 -08003788 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003789 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattis8af2d602020-12-20 11:09:58 -08003790 // Find out why, fix the rematch code, and delete this.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003791 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jean60902092019-11-07 18:54:49 +09003792 rematchAllNetworksAndRequests();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003793 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003794
3795 // Immediate teardown.
3796 if (nai.teardownDelayMs == 0) {
3797 destroyNetwork(nai);
3798 return;
3799 }
3800
3801 // Delayed teardown.
3802 try {
3803 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3804 } catch (RemoteException e) {
3805 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3806 }
3807 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3808 }
3809
3810 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeanefaf6532018-05-11 20:19:20 +09003811 if (nai.created) {
3812 // Tell netd to clean up the configuration for this network
3813 // (routing rules, DNS, etc).
3814 // This may be slow as it requires a lot of netd shelling out to ip and
3815 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean1bc77a92021-02-04 13:12:59 +09003816 // after we've rematched networks with requests (which might change the default
3817 // network or service a new request from an app), so network traffic isn't interrupted
3818 // for an unnecessarily long time.
Luke Huang135c5262019-04-09 18:41:49 +08003819 destroyNativeNetwork(nai);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003820 mDnsManager.removeNetwork(nai.network);
3821 }
Serik Beketayev284cb872020-12-07 22:43:07 -08003822 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003823 nai.onNetworkDestroyed();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003824 }
3825
Ken Chende5e7aa2021-04-09 15:08:42 +08003826 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huang135c5262019-04-09 18:41:49 +08003827 try {
3828 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chende5e7aa2021-04-09 15:08:42 +08003829 final NativeNetworkConfig config;
3830 if (nai.isVPN()) {
3831 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen4e6ae312021-05-12 13:38:13 +08003832 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chende5e7aa2021-04-09 15:08:42 +08003833 return false;
3834 }
3835 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3836 INetd.PERMISSION_NONE,
3837 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3838 getVpnType(nai));
Luke Huang135c5262019-04-09 18:41:49 +08003839 } else {
Ken Chende5e7aa2021-04-09 15:08:42 +08003840 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3841 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3842 VpnManager.TYPE_VPN_NONE);
Luke Huang135c5262019-04-09 18:41:49 +08003843 }
Ken Chende5e7aa2021-04-09 15:08:42 +08003844 mNetd.networkCreate(config);
3845 mDnsResolver.createNetworkCache(nai.network.getNetId());
3846 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3847 nai.networkCapabilities.getTransportTypes());
Luke Huang135c5262019-04-09 18:41:49 +08003848 return true;
3849 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen4e6ae312021-05-12 13:38:13 +08003850 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huang135c5262019-04-09 18:41:49 +08003851 return false;
3852 }
3853 }
3854
Ken Chende5e7aa2021-04-09 15:08:42 +08003855 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huang135c5262019-04-09 18:41:49 +08003856 try {
Ken Chende5e7aa2021-04-09 15:08:42 +08003857 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Oh1abe20f2021-01-20 11:04:46 +09003858 } catch (RemoteException | ServiceSpecificException e) {
3859 loge("Exception destroying network(networkDestroy): " + e);
3860 }
3861 try {
Ken Chende5e7aa2021-04-09 15:08:42 +08003862 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huang135c5262019-04-09 18:41:49 +08003863 } catch (RemoteException | ServiceSpecificException e) {
3864 loge("Exception destroying network: " + e);
3865 }
3866 }
3867
Jeremy Joslin94c30992014-11-05 10:32:09 -08003868 // If this method proves to be too slow then we can maintain a separate
3869 // pendingIntent => NetworkRequestInfo map.
3870 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3871 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003872 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3873 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3874 if (existingPendingIntent != null &&
paulhu94c60a92021-03-04 11:36:55 +08003875 existingPendingIntent.intentFilterEquals(pendingIntent)) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003876 return entry.getValue();
3877 }
3878 }
3879 return null;
3880 }
3881
James Mattis08131f32020-12-13 16:28:14 -08003882 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003883 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattis08131f32020-12-13 16:28:14 -08003884 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3885 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3886 final NetworkRequestInfo existingRequest =
3887 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003888 if (existingRequest != null) { // remove the existing request.
James Mattis08131f32020-12-13 16:28:14 -08003889 if (DBG) {
3890 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3891 + nri.mRequests.get(0) + " because their intents matched.");
3892 }
Lorenzo Colittie0857092021-03-12 22:39:08 +09003893 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohen06633de2019-01-08 12:09:18 -08003894 /* callOnUnavailable */ false);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003895 }
Erik Kline74d68ef2015-04-30 12:58:40 +09003896 handleRegisterNetworkRequest(nri);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003897 }
3898
James Mattis08131f32020-12-13 16:28:14 -08003899 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattise494cbb2021-02-09 18:18:28 -08003900 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis6e6fabf2021-01-10 14:24:24 -08003901 }
3902
James Mattise494cbb2021-02-09 18:18:28 -08003903 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean4deee632019-11-05 14:40:23 +09003904 ensureRunningOnConnectivityServiceThread();
James Mattis6e6fabf2021-01-10 14:24:24 -08003905 for (final NetworkRequestInfo nri : nris) {
3906 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3907 for (final NetworkRequest req : nri.mRequests) {
3908 mNetworkRequests.put(req, nri);
junyulai8cae3c72021-03-12 20:05:08 +08003909 // TODO: Consider update signal strength for other types.
James Mattis6e6fabf2021-01-10 14:24:24 -08003910 if (req.isListen()) {
3911 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3912 if (req.networkCapabilities.hasSignalStrength()
3913 && network.satisfiesImmutableCapabilitiesOf(req)) {
3914 updateSignalStrengthThresholds(network, "REGISTER", req);
3915 }
James Mattis08131f32020-12-13 16:28:14 -08003916 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09003917 }
3918 }
Chalard Jeand67ab4d2021-03-05 19:18:14 +09003919 // If this NRI has a satisfier already, it is replacing an older request that
3920 // has been removed. Track it.
3921 final NetworkRequest activeRequest = nri.getActiveRequest();
3922 if (null != activeRequest) {
3923 // If there is an active request, then for sure there is a satisfier.
3924 nri.getSatisfier().addRequest(activeRequest);
3925 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09003926 }
James Mattis08131f32020-12-13 16:28:14 -08003927
James Mattis6e6fabf2021-01-10 14:24:24 -08003928 rematchAllNetworksAndRequests();
James Mattis6e6fabf2021-01-10 14:24:24 -08003929
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003930 // Requests that have not been matched to a network will not have been sent to the
3931 // providers, because the old satisfier and the new satisfier are the same (null in this
3932 // case). Send these requests to the providers.
3933 for (final NetworkRequestInfo nri : nris) {
3934 for (final NetworkOfferInfo noi : mNetworkOffers) {
3935 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis6e6fabf2021-01-10 14:24:24 -08003936 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003937 }
3938 }
3939
James Mattis08131f32020-12-13 16:28:14 -08003940 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3941 final int callingUid) {
3942 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003943 if (nri != null) {
James Mattis08131f32020-12-13 16:28:14 -08003944 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3945 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3946 handleReleaseNetworkRequest(
3947 nri.mRequests.get(0),
3948 callingUid,
3949 /* callOnUnavailable */ false);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003950 }
3951 }
3952
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003953 // Determines whether the network is the best (or could become the best, if it validated), for
3954 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3955 // on the value of reason:
3956 //
3957 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3958 // then it should be torn down.
3959 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3960 // then it should be lingered.
3961 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean4deee632019-11-05 14:40:23 +09003962 ensureRunningOnConnectivityServiceThread();
Chalard Jeanf278aba2021-03-08 22:29:27 +09003963
3964 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
3965 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
3966 return false;
3967 }
3968
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003969 final int numRequests;
3970 switch (reason) {
3971 case TEARDOWN:
3972 numRequests = nai.numRequestNetworkRequests();
3973 break;
3974 case LINGER:
3975 numRequests = nai.numForegroundNetworkRequests();
3976 break;
3977 default:
Aaron Huang11e9a312020-10-30 22:04:25 +08003978 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003979 return true;
3980 }
3981
Chalard Jeanf278aba2021-03-08 22:29:27 +09003982 if (numRequests > 0) return false;
3983
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003984 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattise4e72bb2020-11-16 16:46:28 -08003985 if (reason == UnneededFor.LINGER
3986 && !nri.isMultilayerRequest()
3987 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003988 // Background requests don't affect lingering.
3989 continue;
3990 }
3991
James Mattise4e72bb2020-11-16 16:46:28 -08003992 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003993 return false;
Paul Jensen203a7442014-12-09 11:43:45 -05003994 }
3995 }
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003996 return true;
Paul Jensen203a7442014-12-09 11:43:45 -05003997 }
3998
James Mattise4e72bb2020-11-16 16:46:28 -08003999 private boolean isNetworkPotentialSatisfier(
4000 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4001 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis65d0d1c2020-11-24 17:40:49 -08004002 // request, return immediately. For multilayer requests, check to see if any of the
4003 // multilayer requests may have a potential satisfier.
junyulai8cae3c72021-03-12 20:05:08 +08004004 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4005 || nri.mRequests.get(0).isListenForBest())) {
James Mattise4e72bb2020-11-16 16:46:28 -08004006 return false;
4007 }
4008 for (final NetworkRequest req : nri.mRequests) {
James Mattis622428c2020-12-02 14:12:41 -08004009 // This multilayer listen request is satisfied therefore no further requests need to be
4010 // evaluated deeming this network not a potential satisfier.
junyulai8cae3c72021-03-12 20:05:08 +08004011 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattis622428c2020-12-02 14:12:41 -08004012 return false;
4013 }
James Mattise4e72bb2020-11-16 16:46:28 -08004014 // As non-multilayer listen requests have already returned, the below would only happen
4015 // for a multilayer request therefore continue to the next request if available.
junyulai8cae3c72021-03-12 20:05:08 +08004016 if (req.isListen() || req.isListenForBest()) {
James Mattise4e72bb2020-11-16 16:46:28 -08004017 continue;
4018 }
4019 // If this Network is already the highest scoring Network for a request, or if
4020 // there is hope for it to become one if it validated, then it is needed.
4021 if (candidate.satisfies(req)) {
4022 // As soon as a network is found that satisfies a request, return. Specifically for
4023 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4024 // is important so as to not evaluate lower priority requests further in
4025 // nri.mRequests.
Chalard Jean3d71e302021-04-07 17:06:19 +09004026 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4027 ? nri.getSatisfier() : null;
4028 // Note that this catches two important cases:
4029 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4030 // is currently satisfying the request. This is desirable when
4031 // cellular ends up validating but WiFi does not.
4032 // 2. Unvalidated WiFi will not be reaped when validated cellular
4033 // is currently satisfying the request. This is desirable when
4034 // WiFi ends up validating and out scoring cellular.
4035 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattise4e72bb2020-11-16 16:46:28 -08004036 }
4037 }
4038
4039 return false;
4040 }
4041
Erik Klineaec3f5e2016-07-07 16:50:58 +09004042 private NetworkRequestInfo getNriForAppRequest(
4043 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattise494cbb2021-02-09 18:18:28 -08004044 // Looking up the app passed param request in mRequests isn't possible since it may return
4045 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4046 // do the lookup since that will also find per-app default managed requests.
James Mattis27aeff02021-02-17 16:13:05 -08004047 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4048 // to avoid potential race conditions when validating a package->uid mapping when sending
4049 // the callback on the very low-chance that an application shuts down prior to the callback
4050 // being sent.
4051 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4052 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004053
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004054 if (nri != null) {
lucaslin2d72a132021-03-15 15:35:38 +08004055 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004056 log(String.format("UID %d attempted to %s for unowned request %s",
4057 callingUid, requestedOperation, nri));
4058 return null;
Paul Jensenabaa0ed2014-05-16 14:31:12 -04004059 }
Erik Klineaec3f5e2016-07-07 16:50:58 +09004060 }
4061
4062 return nri;
4063 }
4064
James Mattis08131f32020-12-13 16:28:14 -08004065 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4066 final String callingMethod) {
4067 if (nri.isMultilayerRequest()) {
4068 throw new IllegalStateException(
4069 callingMethod + " does not support multilayer requests.");
Erik Kline66721822015-11-25 12:49:38 +09004070 }
4071 }
4072
James Mattis08131f32020-12-13 16:28:14 -08004073 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004074 ensureRunningOnConnectivityServiceThread();
James Mattis08131f32020-12-13 16:28:14 -08004075 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4076 // single NetworkRequest and thus does not apply to multilayer requests.
4077 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4078 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004079 return;
4080 }
James Mattisf61f7be2021-01-31 17:06:19 -08004081 if (nri.isBeingSatisfied()) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004082 return;
4083 }
James Mattis08131f32020-12-13 16:28:14 -08004084 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4085 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Klineaec3f5e2016-07-07 16:50:58 +09004086 }
4087 handleRemoveNetworkRequest(nri);
James Mattis08131f32020-12-13 16:28:14 -08004088 callCallbackForRequest(
4089 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004090 }
4091
James Mattis08131f32020-12-13 16:28:14 -08004092 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4093 final int callingUid,
4094 final boolean callOnUnavailable) {
Hugo Benichi4802c802017-03-23 22:40:44 +09004095 final NetworkRequestInfo nri =
4096 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4097 if (nri == null) {
4098 return;
Erik Kline66721822015-11-25 12:49:38 +09004099 }
James Mattis08131f32020-12-13 16:28:14 -08004100 if (VDBG || (DBG && request.isRequest())) {
4101 log("releasing " + request + " (release request)");
Hugo Benichi4802c802017-03-23 22:40:44 +09004102 }
4103 handleRemoveNetworkRequest(nri);
Etan Cohen06633de2019-01-08 12:09:18 -08004104 if (callOnUnavailable) {
4105 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4106 }
Erik Kline66721822015-11-25 12:49:38 +09004107 }
Erik Klineaec3f5e2016-07-07 16:50:58 +09004108
James Mattis622428c2020-12-02 14:12:41 -08004109 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean4deee632019-11-05 14:40:23 +09004110 ensureRunningOnConnectivityServiceThread();
Erik Klineaec3f5e2016-07-07 16:50:58 +09004111 nri.unlinkDeathRecipient();
James Mattis622428c2020-12-02 14:12:41 -08004112 for (final NetworkRequest req : nri.mRequests) {
4113 mNetworkRequests.remove(req);
4114 if (req.isListen()) {
4115 removeListenRequestFromNetworks(req);
4116 }
4117 }
Chalard Jean07dc1862021-03-01 22:08:57 +09004118 if (mDefaultNetworkRequests.remove(nri)) {
4119 // If this request was one of the defaults, then the UID rules need to be updated
4120 // WARNING : if the app(s) for which this network request is the default are doing
4121 // traffic, this will kill their connected sockets, even if an equivalent request
4122 // is going to be reinstated right away ; unconnected traffic will go on the default
4123 // until the new default is set, which will happen very soon.
4124 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4125 // remove ranges for those requests that won't have a replacement
4126 final NetworkAgentInfo satisfier = nri.getSatisfier();
4127 if (null != satisfier) {
4128 try {
4129 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4130 toUidRangeStableParcels(nri.getUids()));
4131 } catch (RemoteException e) {
4132 loge("Exception setting network preference default network", e);
4133 }
4134 }
4135 }
Chalard Jean70b2d9a2021-04-01 16:41:04 +09004136 nri.decrementRequestCount();
Erik Klineaec3f5e2016-07-07 16:50:58 +09004137 mNetworkRequestInfoLogs.log("RELEASE " + nri);
James Mattis622428c2020-12-02 14:12:41 -08004138
4139 if (null != nri.getActiveRequest()) {
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09004140 if (!nri.getActiveRequest().isListen()) {
James Mattis622428c2020-12-02 14:12:41 -08004141 removeSatisfiedNetworkRequestFromNetwork(nri);
4142 } else {
4143 nri.setSatisfier(null, null);
4144 }
4145 }
4146
Chalard Jean7b6a33b2021-01-12 10:58:56 +09004147 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4148 // needed for this offer.
4149 for (final NetworkOfferInfo noi : mNetworkOffers) {
4150 for (final NetworkRequest req : nri.mRequests) {
4151 if (req.isRequest() && noi.offer.neededFor(req)) {
4152 noi.offer.onNetworkUnneeded(req);
4153 }
4154 }
4155 }
James Mattis622428c2020-12-02 14:12:41 -08004156 }
4157
James Mattise494cbb2021-02-09 18:18:28 -08004158 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4159 for (final NetworkRequestInfo nri : nris) {
4160 if (mDefaultRequest == nri) {
4161 // Make sure we never remove the default request.
4162 continue;
4163 }
4164 handleRemoveNetworkRequest(nri);
4165 }
4166 }
4167
James Mattis622428c2020-12-02 14:12:41 -08004168 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4169 // listens don't have a singular affected Network. Check all networks to see
4170 // if this listen request applies and remove it.
4171 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4172 nai.removeRequest(req.requestId);
4173 if (req.networkCapabilities.hasSignalStrength()
4174 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4175 updateSignalStrengthThresholds(nai, "RELEASE", req);
4176 }
4177 }
4178 }
4179
4180 /**
4181 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4182 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4183 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4184 */
4185 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4186 boolean wasKept = false;
4187 final NetworkAgentInfo nai = nri.getSatisfier();
4188 if (nai != null) {
4189 final int requestLegacyType = nri.getActiveRequest().legacyType;
4190 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4191 nai.removeRequest(nri.getActiveRequest().requestId);
4192 if (VDBG || DDBG) {
4193 log(" Removing from current network " + nai.toShortString()
4194 + ", leaving " + nai.numNetworkRequests() + " requests.");
4195 }
4196 // If there are still lingered requests on this network, don't tear it down,
4197 // but resume lingering instead.
4198 final long now = SystemClock.elapsedRealtime();
junyulai2a4f0062021-02-03 20:15:30 +08004199 if (updateInactivityState(nai, now)) {
James Mattis622428c2020-12-02 14:12:41 -08004200 notifyNetworkLosing(nai, now);
4201 }
4202 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4203 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4204 teardownUnneededNetwork(nai);
4205 } else {
4206 wasKept = true;
4207 }
4208 nri.setSatisfier(null, null);
4209 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4210 // Went from foreground to background.
4211 updateCapabilitiesForNetwork(nai);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004212 }
4213
Erik Klineaec3f5e2016-07-07 16:50:58 +09004214 // Maintain the illusion. When this request arrived, we might have pretended
4215 // that a network connected to serve it, even though the network was already
4216 // connected. Now that this request has gone away, we might have to pretend
4217 // that the network disconnected. LegacyTypeTracker will generate that
4218 // phantom disconnect for this type.
James Mattis622428c2020-12-02 14:12:41 -08004219 if (requestLegacyType != TYPE_NONE) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004220 boolean doRemove = true;
4221 if (wasKept) {
4222 // check if any of the remaining requests for this network are for the
4223 // same legacy type - if so, don't remove the nai
4224 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4225 NetworkRequest otherRequest = nai.requestAt(i);
James Mattis622428c2020-12-02 14:12:41 -08004226 if (otherRequest.legacyType == requestLegacyType
4227 && otherRequest.isRequest()) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004228 if (DBG) log(" still have other legacy request - leaving");
4229 doRemove = false;
Robert Greenwaltb0491bb2015-01-08 14:43:31 -08004230 }
4231 }
Robert Greenwaltbc5794d2014-08-24 22:52:10 -07004232 }
4233
Erik Klineaec3f5e2016-07-07 16:50:58 +09004234 if (doRemove) {
James Mattis622428c2020-12-02 14:12:41 -08004235 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004236 }
4237 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004238 }
4239 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004240
Lorenzo Colittib4f8d8e2021-03-30 19:29:00 +09004241 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4242 return checkAnyPermissionOf(
4243 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4244 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4245 }
4246
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004247 @Override
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004248 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004249 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004250 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004251 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004252 }
4253
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004254 @Override
lucaslin25a50472019-03-12 13:08:03 +08004255 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4256 enforceNetworkStackSettingsOrSetup();
4257 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4258 encodeBool(accept), encodeBool(always), network));
4259 }
4260
4261 @Override
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004262 public void setAvoidUnvalidated(Network network) {
lucaslin25a50472019-03-12 13:08:03 +08004263 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004264 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4265 }
4266
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004267 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4268 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4269 " accept=" + accept + " always=" + always);
4270
4271 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4272 if (nai == null) {
4273 // Nothing to do.
4274 return;
4275 }
4276
4277 if (nai.everValidated) {
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004278 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004279 return;
4280 }
4281
Lorenzo Colitticf595362020-01-12 22:28:37 +09004282 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang11e9a312020-10-30 22:04:25 +08004283 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004284 }
4285
Lorenzo Colitticf595362020-01-12 22:28:37 +09004286 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4287 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin25a50472019-03-12 13:08:03 +08004288 // If network becomes partial connectivity and user already accepted to use this
4289 // network, we should respect the user's option and don't need to popup the
4290 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004291 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean1fc55292021-03-31 23:19:05 +09004292 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean60902092019-11-07 18:54:49 +09004293 rematchAllNetworksAndRequests();
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004294 }
4295
4296 if (always) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004297 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004298 }
4299
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004300 if (!accept) {
Paul Jensen4afac232015-07-13 15:19:51 -04004301 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004302 nai.onPreventAutomaticReconnect();
Chalard Jean73d9db72018-06-04 16:52:49 +09004303 // Teardown the network.
Paul Jensen4afac232015-07-13 15:19:51 -04004304 teardownUnneededNetwork(nai);
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004305 }
4306
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004307 }
4308
lucaslin25a50472019-03-12 13:08:03 +08004309 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4310 boolean always) {
4311 if (DBG) {
4312 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4313 + " always=" + always);
4314 }
4315
4316 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4317 if (nai == null) {
4318 // Nothing to do.
4319 return;
4320 }
4321
4322 if (nai.lastValidated) {
4323 // The network validated while the dialog box was up. Take no action.
4324 return;
4325 }
4326
Lorenzo Colitticf595362020-01-12 22:28:37 +09004327 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4328 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin25a50472019-03-12 13:08:03 +08004329 }
4330
4331 // TODO: Use the current design or save the user choice into IpMemoryStore.
4332 if (always) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004333 nai.onSaveAcceptUnvalidated(accept);
lucaslin25a50472019-03-12 13:08:03 +08004334 }
4335
4336 if (!accept) {
4337 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004338 nai.onPreventAutomaticReconnect();
lucaslin25a50472019-03-12 13:08:03 +08004339 // Tear down the network.
4340 teardownUnneededNetwork(nai);
4341 } else {
lucaslin2afb4bc2019-03-20 18:21:59 +08004342 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4343 // result in a partial connectivity result which will be processed by
4344 // maybeHandleNetworkMonitorMessage.
Chiachang Wang9cfa6fe2019-05-23 16:29:30 +08004345 //
4346 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4347 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004348 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin25a50472019-03-12 13:08:03 +08004349 }
4350 }
4351
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004352 private void handleSetAvoidUnvalidated(Network network) {
4353 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4354 if (nai == null || nai.lastValidated) {
4355 // Nothing to do. The network either disconnected or revalidated.
4356 return;
4357 }
4358 if (!nai.avoidUnvalidated) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004359 nai.avoidUnvalidated = true;
Chalard Jean1fc55292021-03-31 23:19:05 +09004360 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean60902092019-11-07 18:54:49 +09004361 rematchAllNetworksAndRequests();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004362 }
4363 }
4364
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004365 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09004366 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004367 mHandler.sendMessageDelayed(
4368 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4369 PROMPT_UNVALIDATED_DELAY_MS);
4370 }
4371
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004372 @Override
4373 public void startCaptivePortalApp(Network network) {
paulhud70b7dd2019-08-12 16:25:11 +08004374 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004375 mHandler.post(() -> {
4376 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4377 if (nai == null) return;
4378 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004379 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004380 });
4381 }
4382
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004383 /**
4384 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4385 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004386 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004387 * @param appExtras Bundle to use as intent extras for the captive portal application.
4388 * Must be treated as opaque to avoid preventing the captive portal app to
4389 * update its arguments.
4390 */
4391 @Override
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004392 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhud203f7a2019-05-14 14:17:44 +08004393 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4394 "ConnectivityService");
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004395
4396 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4397 appIntent.putExtras(appExtras);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004398 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4399 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004400 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4401
lucaslin86086772020-12-17 04:14:35 +08004402 final long token = Binder.clearCallingIdentity();
4403 try {
4404 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4405 } finally {
4406 Binder.restoreCallingIdentity(token);
4407 }
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004408 }
4409
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004410 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4411 private final Network mNetwork;
4412
4413 private CaptivePortalImpl(Network network) {
4414 mNetwork = network;
4415 }
4416
4417 @Override
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004418 public void appResponse(final int response) {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004419 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4420 enforceSettingsPermission();
4421 }
4422
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004423 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004424 if (nm == null) return;
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004425 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004426 }
4427
4428 @Override
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004429 public void appRequest(final int request) {
4430 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4431 if (nm == null) return;
4432
4433 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wang1fa770d2020-02-12 13:44:50 +08004434 checkNetworkStackPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09004435 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004436 }
4437 }
4438
4439 @Nullable
4440 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4441 // getNetworkAgentInfoForNetwork is thread-safe
4442 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4443 if (nai == null) return null;
4444
4445 // nai.networkMonitor() is thread-safe
4446 return nai.networkMonitor();
4447 }
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004448 }
4449
Hugo Benichi4fc79c42016-09-14 23:23:08 +00004450 public boolean avoidBadWifi() {
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004451 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti49d32fe2016-09-16 23:43:38 +09004452 }
4453
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004454 /**
4455 * Return whether the device should maintain continuous, working connectivity by switching away
4456 * from WiFi networks having no connectivity.
4457 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4458 */
4459 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004460 if (!checkNetworkStackPermission()) {
4461 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4462 }
4463 return avoidBadWifi();
4464 }
4465
Chalard Jean78515442021-03-19 13:49:56 +09004466 private void updateAvoidBadWifi() {
4467 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean1fc55292021-03-31 23:19:05 +09004468 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean78515442021-03-19 13:49:56 +09004469 }
Chalard Jean60902092019-11-07 18:54:49 +09004470 rematchAllNetworksAndRequests();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004471 }
4472
Erik Klinefc52be92016-10-02 18:02:14 +09004473 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004474 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004475 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004476 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004477 if (!configRestrict) {
4478 pw.println("Bad Wi-Fi avoidance: unrestricted");
4479 return;
4480 }
4481
4482 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4483 pw.increaseIndent();
4484 pw.println("Config restrict: " + configRestrict);
4485
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004486 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004487 String description;
4488 // Can't use a switch statement because strings are legal case labels, but null is not.
4489 if ("0".equals(value)) {
4490 description = "get stuck";
4491 } else if (value == null) {
4492 description = "prompt";
4493 } else if ("1".equals(value)) {
4494 description = "avoid";
4495 } else {
4496 description = value + " (?)";
4497 }
4498 pw.println("User setting: " + description);
4499 pw.println("Network overrides:");
4500 pw.increaseIndent();
Hugo Benichi821785c2018-09-03 08:19:02 +09004501 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004502 if (nai.avoidUnvalidated) {
Chalard Jean373391b2019-12-10 21:07:02 +09004503 pw.println(nai.toShortString());
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004504 }
4505 }
4506 pw.decreaseIndent();
4507 pw.decreaseIndent();
4508 }
4509
paulhu68426192020-06-09 19:07:03 +08004510 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4511 // unify the method.
4512 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4513 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4514 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4515 return settingsComponent != null
4516 ? settingsComponent.getPackageName() : "com.android.settings";
4517 }
4518
lucaslin1ac72392019-01-24 15:55:30 +08004519 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004520 final String action;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004521 final boolean highPriority;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004522 switch (type) {
4523 case NO_INTERNET:
4524 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004525 // High priority because it is only displayed for explicitly selected networks.
4526 highPriority = true;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004527 break;
lucaslin8cf57f52019-10-22 18:27:33 +08004528 case PRIVATE_DNS_BROKEN:
4529 action = Settings.ACTION_WIRELESS_SETTINGS;
4530 // High priority because we should let user know why there is no internet.
4531 highPriority = true;
4532 break;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004533 case LOST_INTERNET:
4534 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004535 // High priority because it could help the user avoid unexpected data usage.
4536 highPriority = true;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004537 break;
lucaslin25a50472019-03-12 13:08:03 +08004538 case PARTIAL_CONNECTIVITY:
4539 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004540 // Don't bother the user with a high-priority notification if the network was not
4541 // explicitly selected by the user.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004542 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin25a50472019-03-12 13:08:03 +08004543 break;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004544 default:
Aaron Huang11e9a312020-10-30 22:04:25 +08004545 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004546 return;
4547 }
4548
4549 Intent intent = new Intent(action);
lucaslin5cba3142020-02-20 16:56:59 +08004550 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wangef52aad2021-03-18 16:20:27 +08004551 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslin1ac72392019-01-24 15:55:30 +08004552 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu68426192020-06-09 19:07:03 +08004553 // Some OEMs have their own Settings package. Thus, need to get the current using
4554 // Settings package name instead of just use default name "com.android.settings".
4555 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4556 intent.setClassName(settingsPkgName,
4557 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslin1ac72392019-01-24 15:55:30 +08004558 }
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004559
paulhufea8f292020-10-11 22:52:27 +08004560 PendingIntent pendingIntent = PendingIntent.getActivity(
4561 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu68426192020-06-09 19:07:03 +08004562 0 /* requestCode */,
4563 intent,
paulhufea8f292020-10-11 22:52:27 +08004564 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004565
Serik Beketayev284cb872020-12-07 22:43:07 -08004566 mNotifier.showNotification(
4567 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004568 }
4569
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004570 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4571 // Don't prompt if the network is validated, and don't prompt on captive portals
4572 // because we're already prompting the user to sign in.
4573 if (nai.everValidated || nai.everCaptivePortalDetected) {
4574 return false;
4575 }
4576
4577 // If a network has partial connectivity, always prompt unless the user has already accepted
4578 // partial connectivity and selected don't ask again. This ensures that if the device
4579 // automatically connects to a network that has partial Internet access, the user will
4580 // always be able to use it, either because they've already chosen "don't ask again" or
4581 // because we have prompt them.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004582 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004583 return true;
4584 }
4585
4586 // If a network has no Internet access, only prompt if the network was explicitly selected
4587 // and if the user has not already told us to use the network regardless of whether it
4588 // validated or not.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004589 if (nai.networkAgentConfig.explicitlySelected
4590 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004591 return true;
4592 }
4593
4594 return false;
4595 }
4596
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004597 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09004598 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004599 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4600
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004601 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004602 return;
4603 }
Lorenzo Colitti50501802019-05-30 16:24:31 +09004604
4605 // Stop automatically reconnecting to this network in the future. Automatically connecting
4606 // to a network that provides no or limited connectivity is not useful, because the user
4607 // cannot use that network except through the notification shown by this method, and the
4608 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004609 nai.onPreventAutomaticReconnect();
Lorenzo Colitti50501802019-05-30 16:24:31 +09004610
lucaslin25a50472019-03-12 13:08:03 +08004611 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4612 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4613 // popup the notification immediately when the network is partial connectivity.
4614 if (nai.partialConnectivity) {
lucaslin32ecfc42019-03-21 11:59:22 +08004615 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin25a50472019-03-12 13:08:03 +08004616 } else {
4617 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4618 }
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004619 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004620
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004621 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4622 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean373391b2019-12-10 21:07:02 +09004623 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5447c492016-05-23 16:33:16 -07004624
lucaslin25a50472019-03-12 13:08:03 +08004625 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4626 return;
4627 }
4628
4629 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslin1ac72392019-01-24 15:55:30 +08004630 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004631 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004632 }
4633
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004634 @Override
4635 public int getMultipathPreference(Network network) {
4636 enforceAccessPermission();
4637
4638 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey41a72692017-07-12 10:50:42 -06004639 if (nai != null && nai.networkCapabilities
4640 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004641 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4642 }
4643
Aaron Huang5301b6f2020-12-08 10:03:29 +08004644 final NetworkPolicyManager netPolicyManager =
4645 mContext.getSystemService(NetworkPolicyManager.class);
4646
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09004647 final long token = Binder.clearCallingIdentity();
4648 final int networkPreference;
4649 try {
4650 networkPreference = netPolicyManager.getMultipathPreference(network);
4651 } finally {
4652 Binder.restoreCallingIdentity(token);
4653 }
Aaron Huang5301b6f2020-12-08 10:03:29 +08004654 if (networkPreference != 0) {
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09004655 return networkPreference;
4656 }
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004657 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4658 }
4659
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004660 @Override
4661 public NetworkRequest getDefaultRequest() {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004662 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004663 }
4664
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004665 private class InternalHandler extends Handler {
4666 public InternalHandler(Looper looper) {
4667 super(looper);
4668 }
4669
4670 @Override
4671 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004672 switch (msg.what) {
Robert Greenwalt61837eb2014-06-25 16:45:57 -07004673 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004674 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi58aab552017-03-30 23:18:10 +09004675 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004676 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004677 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004678 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean9fbd93c2018-06-08 14:24:49 +09004679 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004680 break;
4681 }
Jason Monk445cea82013-10-10 14:02:51 -04004682 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangb2ad4a92021-01-18 15:28:01 +08004683 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4684 handleApplyDefaultProxy(arg.second);
Jason Monk445cea82013-10-10 14:02:51 -04004685 break;
4686 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09004687 case EVENT_REGISTER_NETWORK_PROVIDER: {
4688 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07004689 break;
4690 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09004691 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4692 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt948aea52014-04-11 15:53:27 -07004693 break;
4694 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09004695 case EVENT_REGISTER_NETWORK_OFFER: {
4696 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4697 break;
4698 }
4699 case EVENT_UNREGISTER_NETWORK_OFFER: {
4700 final NetworkOfferInfo offer =
4701 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4702 if (null != offer) {
4703 handleUnregisterNetworkOffer(offer);
4704 }
4705 break;
4706 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004707 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004708 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4709 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4710 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004711 break;
4712 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004713 case EVENT_REGISTER_NETWORK_REQUEST:
4714 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline74d68ef2015-04-30 12:58:40 +09004715 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004716 break;
4717 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004718 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4719 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin94c30992014-11-05 10:32:09 -08004720 handleRegisterNetworkRequestWithIntent(msg);
4721 break;
4722 }
Erik Kline66721822015-11-25 12:49:38 +09004723 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4724 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4725 handleTimedOutNetworkRequest(nri);
4726 break;
4727 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004728 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4729 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4730 break;
4731 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004732 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohen06633de2019-01-08 12:09:18 -08004733 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4734 /* callOnUnavailable */ false);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004735 break;
4736 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004737 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004738 Network network = (Network) msg.obj;
4739 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004740 break;
4741 }
lucaslin25a50472019-03-12 13:08:03 +08004742 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4743 Network network = (Network) msg.obj;
4744 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4745 toBool(msg.arg2));
4746 break;
4747 }
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004748 case EVENT_SET_AVOID_UNVALIDATED: {
4749 handleSetAvoidUnvalidated((Network) msg.obj);
4750 break;
4751 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004752 case EVENT_PROMPT_UNVALIDATED: {
4753 handlePromptUnvalidated((Network) msg.obj);
4754 break;
4755 }
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07004756 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4757 handleConfigureAlwaysOnNetworks();
Erik Kline74d68ef2015-04-30 12:58:40 +09004758 break;
4759 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004760 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai21c06d02019-01-03 18:50:15 +08004761 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004762 mKeepaliveTracker.handleStartKeepalive(msg);
4763 break;
4764 }
4765 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai21c06d02019-01-03 18:50:15 +08004766 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004767 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4768 int slot = msg.arg1;
4769 int reason = msg.arg2;
4770 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4771 break;
4772 }
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004773 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004774 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004775 break;
4776 }
Erik Klinec06d4f92018-01-11 21:07:29 +09004777 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4778 handlePrivateDnsSettingsChanged();
4779 break;
dalykf4977492018-03-05 12:42:22 -05004780 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4781 handlePrivateDnsValidationUpdate(
4782 (PrivateDnsValidationUpdate) msg.obj);
4783 break;
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00004784 case EVENT_UID_BLOCKED_REASON_CHANGED:
4785 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulai5ab727b2018-08-07 19:50:45 +08004786 break;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09004787 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4788 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4789 break;
Chalard Jeandc974072021-03-01 22:00:20 +09004790 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jeancc9ad152021-03-03 16:37:13 +09004791 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4792 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jeandc974072021-03-01 22:00:20 +09004793 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis6e6fabf2021-01-10 14:24:24 -08004794 break;
Chalard Jeandc974072021-03-01 22:00:20 +09004795 }
Chalard Jean9d968182021-02-25 21:46:34 +09004796 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4797 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4798 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4799 msg.obj;
4800 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhu339d9be2021-05-05 11:04:59 +08004801 break;
Chalard Jean9d968182021-02-25 21:46:34 +09004802 }
lucaslina5e9bdb2021-01-21 02:04:15 +08004803 case EVENT_REPORT_NETWORK_ACTIVITY:
4804 mNetworkActivityTracker.handleReportNetworkActivity();
4805 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004806 }
4807 }
4808 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004809
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004810 @Override
markchien4f949812019-12-16 20:15:20 +08004811 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004812 public int getLastTetherError(String iface) {
markchien4f949812019-12-16 20:15:20 +08004813 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4814 Context.TETHERING_SERVICE);
4815 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004816 }
4817
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004818 @Override
markchien4f949812019-12-16 20:15:20 +08004819 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004820 public String[] getTetherableIfaces() {
markchien4f949812019-12-16 20:15:20 +08004821 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4822 Context.TETHERING_SERVICE);
4823 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004824 }
4825
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004826 @Override
markchien4f949812019-12-16 20:15:20 +08004827 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004828 public String[] getTetheredIfaces() {
markchien4f949812019-12-16 20:15:20 +08004829 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4830 Context.TETHERING_SERVICE);
4831 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004832 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004833
markchien4f949812019-12-16 20:15:20 +08004834
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004835 @Override
markchien4f949812019-12-16 20:15:20 +08004836 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004837 public String[] getTetheringErroredIfaces() {
markchien4f949812019-12-16 20:15:20 +08004838 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4839 Context.TETHERING_SERVICE);
4840
4841 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004842 }
4843
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004844 @Override
markchien4f949812019-12-16 20:15:20 +08004845 @Deprecated
4846 public String[] getTetherableUsbRegexs() {
4847 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4848 Context.TETHERING_SERVICE);
4849
4850 return tm.getTetherableUsbRegexs();
Robert Greenwalta75c4652014-06-23 14:53:42 -07004851 }
4852
Udam Saini15072332017-06-07 12:06:28 -07004853 @Override
markchien4f949812019-12-16 20:15:20 +08004854 @Deprecated
4855 public String[] getTetherableWifiRegexs() {
4856 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4857 Context.TETHERING_SERVICE);
4858 return tm.getTetherableWifiRegexs();
markchiena005c992019-02-27 14:56:11 +08004859 }
4860
Robert Greenwalt205fd8e2014-07-02 09:59:16 -07004861 // Called when we lose the default network and have no replacement yet.
4862 // This will automatically be cleared after X seconds or a new default network
4863 // becomes CONNECTED, whichever happens first. The timer is started by the
4864 // first caller and not restarted by subsequent callers.
Hugo Benichi58aab552017-03-30 23:18:10 +09004865 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004866 synchronized (this) {
Hugo Benichi58aab552017-03-30 23:18:10 +09004867 if (mNetTransitionWakeLock.isHeld()) {
4868 return;
4869 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004870 mNetTransitionWakeLock.acquire();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09004871 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4872 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004873 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004874 mWakelockLogs.log("ACQUIRE for " + forWhom);
4875 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09004876 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09004877 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09004878 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004879 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07004880
Hugo Benichi58aab552017-03-30 23:18:10 +09004881 // Called when we gain a new default network to release the network transition wakelock in a
4882 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4883 // message is cancelled.
4884 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004885 synchronized (this) {
Hugo Benichi58aab552017-03-30 23:18:10 +09004886 if (!mNetTransitionWakeLock.isHeld()) {
4887 return; // expiry message released the lock first.
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004888 }
4889 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004890 // Cancel self timeout on wakelock hold.
4891 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4892 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4893 mHandler.sendMessageDelayed(msg, 1000);
4894 }
4895
4896 // Called when either message of ensureNetworkTransitionWakelock or
4897 // scheduleReleaseNetworkTransitionWakelock is processed.
4898 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4899 String event = eventName(eventId);
4900 synchronized (this) {
4901 if (!mNetTransitionWakeLock.isHeld()) {
4902 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang11e9a312020-10-30 22:04:25 +08004903 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi58aab552017-03-30 23:18:10 +09004904 return;
4905 }
4906 mNetTransitionWakeLock.release();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09004907 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4908 mTotalWakelockDurationMs += lockDuration;
4909 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4910 mTotalWakelockReleases++;
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004911 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004912 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004913 }
4914
Robert Greenwalt986c7412010-09-08 15:24:47 -07004915 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004916 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07004917 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltb264cd82014-08-06 21:32:18 -07004918 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittibdda6bf2015-02-11 07:39:20 +09004919 if (nai == null) return;
Paul Jensen7aac1b32015-04-07 12:43:13 -04004920 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07004921 }
4922
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004923 @Override
Paul Jensen7aac1b32015-04-07 12:43:13 -04004924 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen57d231c2014-08-29 09:54:01 -04004925 enforceAccessPermission();
4926 enforceInternetPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09004927 final int uid = mDeps.getCallingUid();
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004928 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kestinga58c07c2020-01-07 11:18:54 -08004929
Cody Kestingb0174782020-06-25 11:13:39 -07004930 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4931 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4932 // does not match the known connectivity of the network - this causes NetworkMonitor to
4933 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
Cody Kestinga58c07c2020-01-07 11:18:54 -08004934 final NetworkAgentInfo nai;
4935 if (network == null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004936 nai = getDefaultNetwork();
Cody Kestinga58c07c2020-01-07 11:18:54 -08004937 } else {
4938 nai = getNetworkAgentInfoForNetwork(network);
4939 }
4940 if (nai != null) {
4941 mConnectivityDiagnosticsHandler.sendMessage(
4942 mConnectivityDiagnosticsHandler.obtainMessage(
4943 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4944 connectivityInfo, 0, nai));
4945 }
Cody Kestingb0174782020-06-25 11:13:39 -07004946
4947 mHandler.sendMessage(
4948 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004949 }
Paul Jensen57d231c2014-08-29 09:54:01 -04004950
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004951 private void handleReportNetworkConnectivity(
4952 Network network, int uid, boolean hasConnectivity) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09004953 final NetworkAgentInfo nai;
Paul Jensen7aac1b32015-04-07 12:43:13 -04004954 if (network == null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004955 nai = getDefaultNetwork();
Paul Jensen7aac1b32015-04-07 12:43:13 -04004956 } else {
4957 nai = getNetworkAgentInfoForNetwork(network);
4958 }
Paul Jensen773f4f32015-06-25 10:28:34 -04004959 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4960 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4961 return;
4962 }
Paul Jensen7aac1b32015-04-07 12:43:13 -04004963 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9a35d82017-04-06 16:01:44 +09004964 if (hasConnectivity == nai.lastValidated) {
4965 return;
4966 }
Paul Jensen7aac1b32015-04-07 12:43:13 -04004967 if (DBG) {
Serik Beketayev284cb872020-12-07 22:43:07 -08004968 int netid = nai.network.getNetId();
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004969 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensen7aac1b32015-04-07 12:43:13 -04004970 }
Hugo Benichie9a35d82017-04-06 16:01:44 +09004971 // Validating a network that has not yet connected could result in a call to
4972 // rematchNetworkAndRequests() which is not meant to work on such networks.
4973 if (!nai.everConnected) {
4974 return;
Paul Jensen57d231c2014-08-29 09:54:01 -04004975 }
paulhu3b063e32020-12-30 00:42:19 +08004976 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
4977 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09004978 return;
4979 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004980 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004981 }
4982
Lorenzo Colittid81932b2021-03-23 21:01:07 +09004983 // TODO: call into netd.
4984 private boolean queryUserAccess(int uid, Network network) {
4985 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4986 if (nai == null) return false;
4987
4988 // Any UID can use its default network.
4989 if (nai == getDefaultNetworkForUid(uid)) return true;
4990
4991 // Privileged apps can use any network.
4992 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
4993 return true;
4994 }
4995
4996 // An unprivileged UID can use a VPN iff the VPN applies to it.
4997 if (nai.isVPN()) {
4998 return nai.networkCapabilities.appliesToUid(uid);
4999 }
5000
5001 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5002 // sockets, i.e., if it is the owner.
5003 final NetworkAgentInfo vpn = getVpnForUid(uid);
5004 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5005 && uid != vpn.networkCapabilities.getOwnerUid()) {
5006 return false;
5007 }
5008
5009 // The UID's permission must be at least sufficient for the network. Since the restricted
5010 // permission was already checked above, that just leaves background networks.
5011 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5012 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5013 }
5014
5015 // Unrestricted network. Anyone gets to use it.
5016 return true;
5017 }
5018
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005019 /**
5020 * Returns information about the proxy a certain network is using. If given a null network, it
5021 * it will return the proxy for the bound network for the caller app or the default proxy if
5022 * none.
5023 *
5024 * @param network the network we want to get the proxy information for.
5025 * @return Proxy information if a network has a proxy configured, or otherwise null.
5026 */
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09005027 @Override
Paul Jensenfdec88b2015-05-06 07:32:40 -04005028 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean626c0122018-06-07 18:02:37 +09005029 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensenfdec88b2015-05-06 07:32:40 -04005030 if (globalProxy != null) return globalProxy;
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005031 if (network == null) {
5032 // Get the network associated with the calling UID.
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005033 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005034 true);
5035 if (activeNetwork == null) {
5036 return null;
5037 }
5038 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colittid81932b2021-03-23 21:01:07 +09005039 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005040 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5041 // caller may not have.
5042 return getLinkPropertiesProxyInfo(network);
5043 }
5044 // No proxy info available if the calling UID does not have network access.
5045 return null;
5046 }
5047
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005048
5049 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensenfdec88b2015-05-06 07:32:40 -04005050 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5051 if (nai == null) return null;
5052 synchronized (nai) {
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005053 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5054 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensenfdec88b2015-05-06 07:32:40 -04005055 }
5056 }
5057
Chalard Jean850c29e2018-06-07 18:37:59 +09005058 @Override
Chalard Jeanaac3b872021-03-17 17:03:34 +09005059 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu5e094422021-01-25 18:53:17 +08005060 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean850c29e2018-06-07 18:37:59 +09005061 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005062 }
5063
Chalard Jean626c0122018-06-07 18:02:37 +09005064 @Override
5065 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04005066 public ProxyInfo getGlobalProxy() {
Chalard Jean626c0122018-06-07 18:02:37 +09005067 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005068 }
5069
Jason Monk1e3df5d2014-04-25 15:00:09 -04005070 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04005071 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard21523a42014-11-20 14:35:32 -05005072 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005073 proxy = null;
5074 }
Chalard Jeanbbd62a02018-06-08 12:20:15 +09005075 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005076 }
5077
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005078 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5079 // when any network changes proxy.
5080 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5081 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005082 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensen12131352014-12-10 15:12:18 -05005083 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5084 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5085
Chalard Jean80b334a2018-06-07 17:41:29 +09005086 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean07c5bab2018-06-08 19:46:44 +09005087 mProxyTracker.sendProxyBroadcast();
Paul Jensen12131352014-12-10 15:12:18 -05005088 }
5089 }
5090
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005091 private static class SettingsObserver extends ContentObserver {
Erik Kline74d68ef2015-04-30 12:58:40 +09005092 final private HashMap<Uri, Integer> mUriEventMap;
5093 final private Context mContext;
5094 final private Handler mHandler;
5095
5096 SettingsObserver(Context context, Handler handler) {
5097 super(null);
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005098 mUriEventMap = new HashMap<>();
Erik Kline74d68ef2015-04-30 12:58:40 +09005099 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005100 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005101 }
5102
Erik Kline74d68ef2015-04-30 12:58:40 +09005103 void observe(Uri uri, int what) {
5104 mUriEventMap.put(uri, what);
5105 final ContentResolver resolver = mContext.getContentResolver();
5106 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005107 }
5108
5109 @Override
5110 public void onChange(boolean selfChange) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005111 Log.wtf(TAG, "Should never be reached.");
Erik Kline74d68ef2015-04-30 12:58:40 +09005112 }
5113
5114 @Override
5115 public void onChange(boolean selfChange, Uri uri) {
5116 final Integer what = mUriEventMap.get(uri);
5117 if (what != null) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09005118 mHandler.obtainMessage(what).sendToTarget();
Erik Kline74d68ef2015-04-30 12:58:40 +09005119 } else {
5120 loge("No matching event to send for URI=" + uri);
5121 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005122 }
5123 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005124
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005125 private static void log(String s) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005126 Log.d(TAG, s);
5127 }
5128
5129 private static void logw(String s) {
5130 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005131 }
5132
Daniel Bright60f02ed2020-06-15 16:10:01 -07005133 private static void logwtf(String s) {
5134 Log.wtf(TAG, s);
5135 }
5136
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09005137 private static void logwtf(String s, Throwable t) {
5138 Log.wtf(TAG, s, t);
5139 }
5140
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005141 private static void loge(String s) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005142 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005143 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005144
Hugo Benichi0a28d302017-02-11 17:04:43 +09005145 private static void loge(String s, Throwable t) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005146 Log.e(TAG, s, t);
Hugo Benichi0a28d302017-02-11 17:04:43 +09005147 }
5148
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005149 /**
Varun Anand5e980f42019-02-07 14:13:13 -08005150 * Return the information of all ongoing VPNs.
5151 *
5152 * <p>This method is used to update NetworkStatsService.
5153 *
5154 * <p>Must be called on the handler thread.
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005155 */
junyulai62d35f72021-01-23 09:46:34 +08005156 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anand5e980f42019-02-07 14:13:13 -08005157 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005158 if (mLockdownEnabled) {
5159 return new UnderlyingNetworkInfo[0];
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005160 }
junyulai62d35f72021-01-23 09:46:34 +08005161 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colittia68139a2020-12-15 15:47:24 +09005162 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai62d35f72021-01-23 09:46:34 +08005163 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colittia68139a2020-12-15 15:47:24 +09005164 if (info != null) {
5165 infoList.add(info);
5166 }
5167 }
junyulai62d35f72021-01-23 09:46:34 +08005168 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005169 }
5170
5171 /**
5172 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wongb393d282019-06-12 17:46:15 +00005173 * information, e.g underlying ifaces.
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005174 */
junyulai62d35f72021-01-23 09:46:34 +08005175 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005176 if (!nai.isVPN()) return null;
5177
5178 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005179 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5180 // the underlyingNetworks list.
5181 if (underlyingNetworks == null) {
James Mattisf61f7be2021-01-31 17:06:19 -08005182 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5183 nai.networkCapabilities.getOwnerUid());
Benedict Wongb98e0692019-06-12 17:46:31 +00005184 if (defaultNai != null) {
Benedict Wongb393d282019-06-12 17:46:15 +00005185 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005186 }
5187 }
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005188
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005189 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005190
5191 List<String> interfaces = new ArrayList<>();
5192 for (Network network : underlyingNetworks) {
5193 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5194 if (underlyingNai == null) continue;
5195 LinkProperties lp = underlyingNai.linkProperties;
5196 for (String iface : lp.getAllInterfaceNames()) {
5197 if (!TextUtils.isEmpty(iface)) {
5198 interfaces.add(iface);
Benedict Wongb393d282019-06-12 17:46:15 +00005199 }
5200 }
Benedict Wongb393d282019-06-12 17:46:15 +00005201 }
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005202
5203 if (interfaces.isEmpty()) return null;
5204
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005205 // Must be non-null or NetworkStatsService will crash.
5206 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5207 // tun or ipsec interface is created.
junyulai62d35f72021-01-23 09:46:34 +08005208 // TODO: Remove this check.
junyulaibd7f3cd2021-01-23 01:09:11 +08005209 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005210
junyulai62d35f72021-01-23 09:46:34 +08005211 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5212 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005213 }
5214
James Mattis1238af22020-12-23 16:37:26 -08005215 // TODO This needs to be the default network that applies to the NAI.
James Mattisf61f7be2021-01-31 17:06:19 -08005216 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5217 Network[] underlyingNetworks) {
5218 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005219 if (underlyingNetworks == null && defaultNetwork != null) {
5220 // null underlying networks means to track the default.
5221 underlyingNetworks = new Network[] { defaultNetwork };
5222 }
5223 return underlyingNetworks;
5224 }
5225
5226 // Returns true iff |network| is an underlying network of |nai|.
5227 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5228 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5229 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5230 if (!nai.supportsUnderlyingNetworks()) return false;
James Mattisf61f7be2021-01-31 17:06:19 -08005231 final Network[] underlying = underlyingNetworksOrDefault(
5232 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005233 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005234 }
5235
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005236 /**
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005237 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005238 *
Lorenzo Colitti220987b2020-11-09 10:32:56 +09005239 * When underlying networks change, such networks may have to update capabilities to reflect
5240 * things like the metered bit, their transports, and so on. The capabilities are calculated
5241 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005242 */
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005243 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti220987b2020-11-09 10:32:56 +09005244 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005245 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005246 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09005247 updateCapabilitiesForNetwork(nai);
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005248 }
5249 }
5250 }
5251
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005252 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5253 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5254 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5255 // a VPN is not up.
5256 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5257 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5258 for (UidRange range : blockedUidRanges) {
5259 if (range.contains(uid)) return true;
5260 }
5261 return false;
5262 }
5263
5264 @Override
5265 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucaslin5140e482021-03-22 11:51:27 +08005266 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005267 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5268 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5269 }
5270
5271 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5272 if (DBG) {
5273 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5274 + Arrays.toString(ranges));
5275 }
5276 // Cannot use a Set since the list of UID ranges might contain duplicates.
5277 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5278 for (int i = 0; i < ranges.length; i++) {
5279 if (requireVpn) {
5280 newVpnBlockedUidRanges.add(ranges[i]);
5281 } else {
5282 newVpnBlockedUidRanges.remove(ranges[i]);
5283 }
5284 }
5285
5286 try {
5287 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5288 } catch (RemoteException | ServiceSpecificException e) {
5289 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5290 + Arrays.toString(ranges) + "): netd command failed: " + e);
5291 }
5292
5293 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5294 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00005295 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5296 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005297 }
5298
5299 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5300 }
5301
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07005302 @Override
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005303 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucaslin5140e482021-03-22 11:51:27 +08005304 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005305 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He729f0b42017-05-15 17:07:18 +01005306 }
5307
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005308 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5309 return mLockdownEnabled
5310 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5311 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Lee33c73e22016-01-05 18:03:46 +00005312 }
5313
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005314 private NetworkAgentInfo getLegacyLockdownNai() {
5315 if (!mLockdownEnabled) {
5316 return null;
Robin Lee33c73e22016-01-05 18:03:46 +00005317 }
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005318 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005319 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5320 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Lee33c73e22016-01-05 18:03:46 +00005321
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005322 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005323 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5324 // a local variable. There is no need to make a copy because its contents cannot change.
5325 final Network[] underlying = nai.declaredUnderlyingNetworks;
5326 if (underlying == null || underlying.length != 1) {
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005327 return null;
Pavel Grafov4753f402019-01-25 08:50:06 +00005328 }
Pavel Grafov4753f402019-01-25 08:50:06 +00005329
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005330 // The legacy lockdown VPN always uses the default network.
5331 // If the VPN's underlying network is no longer the current default network, it means that
5332 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005333 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5334 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005335 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005336 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005337 return null;
Pavel Grafov4753f402019-01-25 08:50:06 +00005338 }
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005339
5340 return nai;
5341 };
5342
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005343 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5344 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5345 // just a DetailedState object.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005346 private DetailedState getLegacyLockdownState(DetailedState origState) {
5347 if (origState != DetailedState.CONNECTED) {
5348 return origState;
5349 }
5350 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5351 ? DetailedState.CONNECTING
5352 : DetailedState.CONNECTED;
Pavel Grafov4753f402019-01-25 08:50:06 +00005353 }
5354
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005355 private void filterForLegacyLockdown(NetworkInfo ni) {
5356 if (!mLockdownEnabled || !ni.isConnected()) return;
5357 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5358 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5359 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5360 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5361 // network, this time with a state of CONNECTED.
5362 //
5363 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5364 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5365 // is not too far off the truth, since an always-on VPN, when not connected, is always
5366 // trying to reconnect.
5367 if (getLegacyLockdownNai() == null) {
5368 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5369 }
5370 }
5371
Pavel Grafov4753f402019-01-25 08:50:06 +00005372 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07005373 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04005374 String action) {
paulhud70b7dd2019-08-12 16:25:11 +08005375 enforceSettingsPermission();
Hugo Benichi37d5c3c2017-06-20 14:07:59 +09005376 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5377 return;
5378 }
Paul Jensen82c7e422014-09-15 15:59:36 -04005379 final long ident = Binder.clearCallingIdentity();
5380 try {
Lorenzo Colittieb166f42016-08-22 22:36:19 +09005381 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09005382 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittieb166f42016-08-22 22:36:19 +09005383 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen82c7e422014-09-15 15:59:36 -04005384 } finally {
5385 Binder.restoreCallingIdentity(ident);
5386 }
Wink Saville89c87b92013-08-29 08:55:16 -07005387 }
Wink Saville3ade4872013-08-29 14:57:08 -07005388
Yuhao Zheng15019892013-09-09 17:00:04 -07005389 @Override
5390 public void setAirplaneMode(boolean enable) {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01005391 enforceAirplaneModePermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07005392 final long ident = Binder.clearCallingIdentity();
5393 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07005394 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichi7f919fe2017-04-21 15:07:12 +09005395 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng82579362013-09-11 09:36:41 -07005396 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5397 intent.putExtra("state", enable);
xinhe51e77032014-11-17 11:35:01 -08005398 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng15019892013-09-09 17:00:04 -07005399 } finally {
5400 Binder.restoreCallingIdentity(ident);
5401 }
5402 }
5403
James Mattisbd275dc2021-03-13 19:27:21 -08005404 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005405 mPermissionMonitor.onUserAdded(user);
James Mattis3bf8b7a2021-03-01 17:09:11 -08005406 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5407 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5408 }
Fyodor Kupolov188d3bd2015-09-02 13:27:21 -07005409 }
5410
James Mattisbd275dc2021-03-13 19:27:21 -08005411 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005412 mPermissionMonitor.onUserRemoved(user);
Chalard Jean6bb468c2021-03-09 21:09:20 +09005413 // If there was a network preference for this user, remove it.
5414 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5415 null /* listener */);
James Mattis3bf8b7a2021-03-01 17:09:11 -08005416 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5417 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5418 }
junyulaib56dc512020-08-28 13:44:33 +08005419 }
5420
James Mattisbd275dc2021-03-13 19:27:21 -08005421 private void onPackageChanged(@NonNull final String packageName) {
5422 // This is necessary in case a package is added or removed, but also when it's replaced to
5423 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5424 // as one in the preferences, then it should follow the same routing as that other package,
5425 // which means updating the rules is never to be needed in this case (whether it joins or
5426 // leaves a UID with a preference).
5427 if (isMappedInOemNetworkPreference(packageName)) {
5428 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5429 }
5430 }
5431
5432 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerccae0d32013-06-14 11:16:51 -07005433 @Override
5434 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti37d17e62021-02-15 09:36:55 +09005435 ensureRunningOnConnectivityServiceThread();
Chad Brubakerccae0d32013-06-14 11:16:51 -07005436 final String action = intent.getAction();
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005437 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaib56dc512020-08-28 13:44:33 +08005438
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005439 // User should be filled for below intents, check the existence.
5440 if (user == null) {
5441 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5442 return;
5443 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07005444
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005445 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005446 onUserAdded(user);
Fyodor Kupolov188d3bd2015-09-02 13:27:21 -07005447 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005448 onUserRemoved(user);
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005449 } else {
junyulaib56dc512020-08-28 13:44:33 +08005450 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerccae0d32013-06-14 11:16:51 -07005451 }
5452 }
5453 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07005454
James Mattisbd275dc2021-03-13 19:27:21 -08005455 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5456 @Override
5457 public void onReceive(Context context, Intent intent) {
5458 ensureRunningOnConnectivityServiceThread();
5459 switch (intent.getAction()) {
5460 case Intent.ACTION_PACKAGE_ADDED:
5461 case Intent.ACTION_PACKAGE_REMOVED:
5462 case Intent.ACTION_PACKAGE_REPLACED:
5463 onPackageChanged(intent.getData().getSchemeSpecificPart());
5464 break;
5465 default:
5466 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5467 }
5468 }
5469 };
5470
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005471 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005472 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt948aea52014-04-11 15:53:27 -07005473
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005474 private static class NetworkProviderInfo {
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005475 public final String name;
5476 public final Messenger messenger;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005477 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005478 public final int providerId;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005479
lifr1c0d9b22021-03-10 13:58:14 +08005480 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5481 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005482 this.name = name;
5483 this.messenger = messenger;
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005484 this.providerId = providerId;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005485 mDeathRecipient = deathRecipient;
5486
Remi NGUYEN VAN773d9182021-02-04 18:04:43 +09005487 if (mDeathRecipient == null) {
5488 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005489 }
5490 }
5491
Lorenzo Colittia54a1aa2020-01-07 19:36:24 +09005492 void connect(Context context, Handler handler) {
Remi NGUYEN VAN773d9182021-02-04 18:04:43 +09005493 try {
5494 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5495 } catch (RemoteException e) {
5496 mDeathRecipient.binderDied();
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005497 }
Lorenzo Colittia54a1aa2020-01-07 19:36:24 +09005498 }
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005499 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005500
James Mattis3f93a312020-11-12 15:53:42 -08005501 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5502 for (int i = 0; i < requests.size(); i++) {
5503 ensureNetworkRequestHasType(requests.get(i));
5504 }
5505 }
5506
Lorenzo Colitticef9c492016-07-05 01:22:13 +09005507 private void ensureNetworkRequestHasType(NetworkRequest request) {
5508 if (request.type == NetworkRequest.Type.NONE) {
5509 throw new IllegalArgumentException(
5510 "All NetworkRequests in ConnectivityService must have a type");
5511 }
5512 }
5513
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005514 /**
5515 * Tracks info about the requester.
James Mattis08131f32020-12-13 16:28:14 -08005516 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005517 */
James Mattisf8eb49a2020-11-15 15:04:40 -08005518 @VisibleForTesting
5519 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattis8af2d602020-12-20 11:09:58 -08005520 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5521 // single NetworkRequest in mRequests.
James Mattis7835f742020-11-03 15:54:33 -08005522 final List<NetworkRequest> mRequests;
James Mattis7835f742020-11-03 15:54:33 -08005523
James Mattis622428c2020-12-02 14:12:41 -08005524 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5525 void setSatisfier(
5526 @Nullable final NetworkAgentInfo satisfier,
5527 @Nullable final NetworkRequest activeRequest) {
5528 mSatisfier = satisfier;
5529 mActiveRequest = activeRequest;
5530 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005531
James Mattis1238af22020-12-23 16:37:26 -08005532 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09005533 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeane8cf3bf2019-11-05 15:07:09 +09005534 @Nullable
James Mattis622428c2020-12-02 14:12:41 -08005535 private NetworkAgentInfo mSatisfier;
5536 NetworkAgentInfo getSatisfier() {
5537 return mSatisfier;
5538 }
5539
5540 // The request in mRequests assigned to a network agent. This is null if none of the
5541 // requests in mRequests can be satisfied. This member has the constraint of only being
5542 // accessible on the handler thread.
5543 @Nullable
5544 private NetworkRequest mActiveRequest;
5545 NetworkRequest getActiveRequest() {
5546 return mActiveRequest;
5547 }
5548
Jeremy Joslin94c30992014-11-05 10:32:09 -08005549 final PendingIntent mPendingIntent;
Jeremy Joslinb9846d02014-12-03 17:15:28 -08005550 boolean mPendingIntentSent;
James Mattis6e6fabf2021-01-10 14:24:24 -08005551 @Nullable
5552 final Messenger mMessenger;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005553
5554 // Information about the caller that caused this object to be created.
James Mattis6e6fabf2021-01-10 14:24:24 -08005555 @Nullable
Jeremy Joslin94c30992014-11-05 10:32:09 -08005556 private final IBinder mBinder;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005557 final int mPid;
5558 final int mUid;
Roshan Pius7992afd2020-12-22 15:10:42 -08005559 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusc97d8062020-12-17 14:53:09 -08005560 @Nullable
5561 final String mCallingAttributionTag;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005562
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005563 // Counter keeping track of this NRI.
5564 final PerUidCounter mPerUidCounter;
5565
Lorenzo Colittif2514122021-03-12 22:50:57 +09005566 // Effective UID of this request. This is different from mUid when a privileged process
5567 // files a request on behalf of another UID. This UID is used to determine blocked status,
5568 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5569 // maximum limit of registered callbacks per UID.
5570 final int mAsUid;
5571
James Mattise494cbb2021-02-09 18:18:28 -08005572 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5573 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5574 // maintained for keying off of. This is only a concern when the original nri
5575 // mNetworkRequests changes which happens currently for apps that register callbacks to
5576 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5577 // that match the per-app default nri that currently tracks the calling app's uid so that
5578 // callbacks are fired at the appropriate time. When the callbacks fire,
5579 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5580 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5581 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5582 @NonNull
5583 private final NetworkRequest mNetworkRequestForCallback;
5584 NetworkRequest getNetworkRequestForCallback() {
5585 return mNetworkRequestForCallback;
5586 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005587
James Mattis1238af22020-12-23 16:37:26 -08005588 /**
5589 * Get the list of UIDs this nri applies to.
5590 */
5591 @NonNull
5592 private Set<UidRange> getUids() {
5593 // networkCapabilities.getUids() returns a defensive copy.
5594 // multilayer requests will all have the same uids so return the first one.
Chiachang Wangd5034c72021-02-22 18:36:38 +08005595 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5596 return (null == uids) ? new ArraySet<>() : uids;
James Mattis1238af22020-12-23 16:37:26 -08005597 }
5598
Lorenzo Colittif2514122021-03-12 22:50:57 +09005599 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5600 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5601 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
James Mattis6e6fabf2021-01-10 14:24:24 -08005602 }
5603
Lorenzo Colittif2514122021-03-12 22:50:57 +09005604 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattise494cbb2021-02-09 18:18:28 -08005605 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5606 @Nullable String callingAttributionTag) {
5607 ensureAllNetworkRequestsHaveType(r);
James Mattis7835f742020-11-03 15:54:33 -08005608 mRequests = initializeRequests(r);
James Mattise494cbb2021-02-09 18:18:28 -08005609 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005610 mPendingIntent = pi;
James Mattis6e6fabf2021-01-10 14:24:24 -08005611 mMessenger = null;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005612 mBinder = null;
5613 mPid = getCallingPid();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005614 mUid = mDeps.getCallingUid();
Lorenzo Colittif2514122021-03-12 22:50:57 +09005615 mAsUid = asUid;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005616 mPerUidCounter = getRequestCounter(this);
5617 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005618 /**
5619 * Location sensitive data not included in pending intent. Only included in
5620 * {@link NetworkCallback}.
5621 */
5622 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusc97d8062020-12-17 14:53:09 -08005623 mCallingAttributionTag = callingAttributionTag;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005624 }
5625
Lorenzo Colittif2514122021-03-12 22:50:57 +09005626 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius7992afd2020-12-22 15:10:42 -08005627 @Nullable final IBinder binder,
5628 @NetworkCallback.Flag int callbackFlags,
5629 @Nullable String callingAttributionTag) {
Lorenzo Colittif2514122021-03-12 22:50:57 +09005630 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5631 callingAttributionTag);
James Mattis6e6fabf2021-01-10 14:24:24 -08005632 }
5633
Lorenzo Colittif2514122021-03-12 22:50:57 +09005634 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattise494cbb2021-02-09 18:18:28 -08005635 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius7992afd2020-12-22 15:10:42 -08005636 @Nullable final IBinder binder,
5637 @NetworkCallback.Flag int callbackFlags,
5638 @Nullable String callingAttributionTag) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005639 super();
James Mattise494cbb2021-02-09 18:18:28 -08005640 ensureAllNetworkRequestsHaveType(r);
James Mattis7835f742020-11-03 15:54:33 -08005641 mRequests = initializeRequests(r);
James Mattise494cbb2021-02-09 18:18:28 -08005642 mNetworkRequestForCallback = requestForCallback;
James Mattis6e6fabf2021-01-10 14:24:24 -08005643 mMessenger = m;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005644 mBinder = binder;
5645 mPid = getCallingPid();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005646 mUid = mDeps.getCallingUid();
Lorenzo Colittif2514122021-03-12 22:50:57 +09005647 mAsUid = asUid;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005648 mPendingIntent = null;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005649 mPerUidCounter = getRequestCounter(this);
5650 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005651 mCallbackFlags = callbackFlags;
Roshan Piusc97d8062020-12-17 14:53:09 -08005652 mCallingAttributionTag = callingAttributionTag;
James Mattisfdd2d3b2021-03-31 13:57:52 -07005653 linkDeathRecipient();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005654 }
5655
James Mattise494cbb2021-02-09 18:18:28 -08005656 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5657 @NonNull final List<NetworkRequest> r) {
5658 super();
5659 ensureAllNetworkRequestsHaveType(r);
5660 mRequests = initializeRequests(r);
5661 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeand67ab4d2021-03-05 19:18:14 +09005662 final NetworkAgentInfo satisfier = nri.getSatisfier();
5663 if (null != satisfier) {
5664 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5665 // The active request is necessary to figure out what callbacks to send, in
5666 // particular then a network updates its capabilities.
5667 // As this code creates a new NRI with a new set of requests, figure out which of
5668 // the list of requests should be the active request. It is always the first
5669 // request of the list that can be satisfied by the satisfier since the order of
5670 // requests is a priority order.
5671 // Note even in the presence of a satisfier there may not be an active request,
5672 // when the satisfier is the no-service network.
5673 NetworkRequest activeRequest = null;
5674 for (final NetworkRequest candidate : r) {
5675 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5676 activeRequest = candidate;
5677 break;
5678 }
5679 }
5680 setSatisfier(satisfier, activeRequest);
5681 }
James Mattise494cbb2021-02-09 18:18:28 -08005682 mMessenger = nri.mMessenger;
5683 mBinder = nri.mBinder;
5684 mPid = nri.mPid;
5685 mUid = nri.mUid;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005686 mAsUid = nri.mAsUid;
James Mattise494cbb2021-02-09 18:18:28 -08005687 mPendingIntent = nri.mPendingIntent;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005688 mPerUidCounter = getRequestCounter(this);
5689 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005690 mCallbackFlags = nri.mCallbackFlags;
James Mattise494cbb2021-02-09 18:18:28 -08005691 mCallingAttributionTag = nri.mCallingAttributionTag;
James Mattisfdd2d3b2021-03-31 13:57:52 -07005692 linkDeathRecipient();
James Mattise494cbb2021-02-09 18:18:28 -08005693 }
5694
Lorenzo Colittif2514122021-03-12 22:50:57 +09005695 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5696 this(asUid, Collections.singletonList(r));
James Mattis6e6fabf2021-01-10 14:24:24 -08005697 }
5698
Lorenzo Colittif2514122021-03-12 22:50:57 +09005699 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5700 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
Cody Kesting0ffbf922019-12-18 10:57:50 -08005701 }
5702
James Mattisf61f7be2021-01-31 17:06:19 -08005703 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5704 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5705 // false.
5706 boolean isBeingSatisfied() {
5707 return (null != mSatisfier && null != mActiveRequest);
5708 }
5709
James Mattise4e72bb2020-11-16 16:46:28 -08005710 boolean isMultilayerRequest() {
5711 return mRequests.size() > 1;
5712 }
5713
James Mattis6e6fabf2021-01-10 14:24:24 -08005714 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5715 // Creating a defensive copy to prevent the sender from modifying the list being
5716 // reflected in the return value of this method.
5717 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis7835f742020-11-03 15:54:33 -08005718 return Collections.unmodifiableList(tempRequests);
5719 }
5720
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005721 void decrementRequestCount() {
5722 mPerUidCounter.decrementCount(mUid);
5723 }
5724
James Mattisfdd2d3b2021-03-31 13:57:52 -07005725 void linkDeathRecipient() {
5726 if (null != mBinder) {
5727 try {
5728 mBinder.linkToDeath(this, 0);
5729 } catch (RemoteException e) {
5730 binderDied();
5731 }
5732 }
5733 }
5734
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005735 void unlinkDeathRecipient() {
James Mattisfdd2d3b2021-03-31 13:57:52 -07005736 if (null != mBinder) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08005737 mBinder.unlinkToDeath(this, 0);
5738 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005739 }
5740
James Mattis3f93a312020-11-12 15:53:42 -08005741 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005742 public void binderDied() {
5743 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis3f93a312020-11-12 15:53:42 -08005744 mRequests + ", " + mBinder + ")");
James Mattisc449dde2020-11-20 16:08:10 -08005745 releaseNetworkRequests(mRequests);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005746 }
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005747
James Mattis3f93a312020-11-12 15:53:42 -08005748 @Override
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005749 public String toString() {
Lorenzo Colittif2514122021-03-12 22:50:57 +09005750 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5751 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattis1238af22020-12-23 16:37:26 -08005752 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colittif2514122021-03-12 22:50:57 +09005753 + " callbackRequest: "
Chalard Jeandc974072021-03-01 22:00:20 +09005754 + mNetworkRequestForCallback.requestId
James Mattis1238af22020-12-23 16:37:26 -08005755 + " " + mRequests
Roshan Pius7992afd2020-12-22 15:10:42 -08005756 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
Roshan Piusf75ffaa2021-03-11 21:16:44 -08005757 + " callback flags: " + mCallbackFlags;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005758 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005759 }
5760
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09005761 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5762 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5763 if (badCapability != null) {
5764 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04005765 }
5766 }
5767
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09005768 // This checks that the passed capabilities either do not request a
5769 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean058cd312018-04-11 21:09:10 +09005770 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005771 int callerPid, int callerUid, String callerPackageName) {
Chalard Jeanbd958b32020-03-18 15:58:50 +09005772 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean058cd312018-04-11 21:09:10 +09005773 throw new SecurityException("Insufficient permissions to request a specific SSID");
5774 }
paulhua9a6e2a2019-03-22 16:35:06 +08005775
5776 if (nc.hasSignalStrength()
5777 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5778 throw new SecurityException(
5779 "Insufficient permissions to request a specific signal strength");
5780 }
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005781 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong4310e452021-03-24 14:01:51 -07005782
junyulai58153cc2021-04-14 23:33:31 +08005783 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong4310e452021-03-24 14:01:51 -07005784 enforceNetworkFactoryPermission();
5785 }
Chalard Jean058cd312018-04-11 21:09:10 +09005786 }
5787
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005788 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005789 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005790 synchronized (nai) {
James Mattis622428c2020-12-02 14:12:41 -08005791 // mNetworkRequests may contain the same value multiple times in case of
5792 // multilayer requests. It won't matter in this case because the thresholds
5793 // will then be the same and be deduplicated as they enter the `thresholds` set.
5794 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattis9301a9a2020-11-18 16:23:25 -08005795 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5796 for (final NetworkRequest req : nri.mRequests) {
5797 if (req.networkCapabilities.hasSignalStrength()
5798 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5799 thresholds.add(req.networkCapabilities.getSignalStrength());
5800 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005801 }
5802 }
5803 }
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005804 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005805 }
5806
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005807 private void updateSignalStrengthThresholds(
5808 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005809 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005810
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09005811 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005812 String detail;
5813 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5814 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5815 } else {
5816 detail = reason;
5817 }
5818 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005819 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005820 }
5821
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005822 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005823 }
5824
Etan Cohenb184cba2017-04-03 17:42:34 -07005825 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5826 if (nc == null) {
5827 return;
5828 }
5829 NetworkSpecifier ns = nc.getNetworkSpecifier();
5830 if (ns == null) {
5831 return;
5832 }
lucaslin61ad5f32021-01-22 15:15:23 +08005833 if (ns instanceof MatchAllNetworkSpecifier) {
5834 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5835 }
Etan Cohenb184cba2017-04-03 17:42:34 -07005836 }
5837
lucaslin8cf57f52019-10-22 18:27:33 +08005838 private void ensureValid(NetworkCapabilities nc) {
5839 ensureValidNetworkSpecifier(nc);
5840 if (nc.isPrivateDnsBroken()) {
5841 throw new IllegalArgumentException("Can't request broken private DNS");
5842 }
5843 }
5844
Roshan Pius7992afd2020-12-22 15:10:42 -08005845 private boolean isTargetSdkAtleast(int version, int callingUid,
5846 @NonNull String callingPackageName) {
5847 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu66797212020-12-10 23:32:32 +08005848 final PackageManager pm =
5849 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien7fae6ea2020-03-27 18:12:39 +08005850 try {
Roshan Pius7992afd2020-12-22 15:10:42 -08005851 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien7fae6ea2020-03-27 18:12:39 +08005852 if (callingVersion < version) return false;
5853 } catch (PackageManager.NameNotFoundException e) { }
5854 return true;
5855 }
5856
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005857 @Override
Lorenzo Colittib199b962021-03-12 22:48:07 +09005858 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
junyulaid1a78162021-01-11 16:53:38 +08005859 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
Roshan Pius7992afd2020-12-22 15:10:42 -08005860 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaid1a78162021-01-11 16:53:38 +08005861 @Nullable String callingAttributionTag) {
markchieneddbe2b2020-03-18 21:16:15 +08005862 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius7992afd2020-12-22 15:10:42 -08005863 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5864 callingPackageName)) {
markchien7fae6ea2020-03-27 18:12:39 +08005865 throw new SecurityException("Insufficient permissions to specify legacy type");
5866 }
markchieneddbe2b2020-03-18 21:16:15 +08005867 }
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005868 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005869 final int callingUid = mDeps.getCallingUid();
Lorenzo Colittib199b962021-03-12 22:48:07 +09005870 // Privileged callers can track the default network of another UID by passing in a UID.
5871 if (asUid != Process.INVALID_UID) {
5872 enforceSettingsPermission();
5873 } else {
5874 asUid = callingUid;
5875 }
junyulaid1a78162021-01-11 16:53:38 +08005876 final NetworkRequest.Type reqType;
5877 try {
5878 reqType = NetworkRequest.Type.values()[reqTypeInt];
5879 } catch (ArrayIndexOutOfBoundsException e) {
5880 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5881 }
5882 switch (reqType) {
5883 case TRACK_DEFAULT:
5884 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colittib199b962021-03-12 22:48:07 +09005885 // is unused and will be replaced by ones appropriate for the UID (usually, the
5886 // calling app). This allows callers to keep track of the default network.
James Mattise494cbb2021-02-09 18:18:28 -08005887 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittib199b962021-03-12 22:48:07 +09005888 defaultNc, asUid, callingUid, callingPackageName);
junyulaid1a78162021-01-11 16:53:38 +08005889 enforceAccessPermission();
5890 break;
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005891 case TRACK_SYSTEM_DEFAULT:
5892 enforceSettingsPermission();
5893 networkCapabilities = new NetworkCapabilities(defaultNc);
5894 break;
Junyu Lai23568a42021-01-19 11:10:56 +00005895 case BACKGROUND_REQUEST:
5896 enforceNetworkStackOrSettingsPermission();
5897 // Fall-through since other checks are the same with normal requests.
junyulaid1a78162021-01-11 16:53:38 +08005898 case REQUEST:
5899 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5900 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5901 callingAttributionTag);
5902 // TODO: this is incorrect. We mark the request as metered or not depending on
5903 // the state of the app when the request is filed, but we never change the
5904 // request if the app changes network state. http://b/29964605
5905 enforceMeteredApnPolicy(networkCapabilities);
5906 break;
junyulai8cae3c72021-03-12 20:05:08 +08005907 case LISTEN_FOR_BEST:
5908 enforceAccessPermission();
5909 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5910 break;
junyulaid1a78162021-01-11 16:53:38 +08005911 default:
5912 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Klinee0aed632016-03-16 15:31:39 +09005913 }
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09005914 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09005915 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005916 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005917
junyulai8cae3c72021-03-12 20:05:08 +08005918 // Enforce FOREGROUND if the caller does not have permission to use background network.
5919 if (reqType == LISTEN_FOR_BEST) {
5920 restrictBackgroundRequestForCaller(networkCapabilities);
5921 }
5922
5923 // Set the UID range for this request to the single UID of the requester, unless the
5924 // requester has the permission to specify other UIDs.
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09005925 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5926 // are no visible methods to set the UIDs, an app could use reflection to try and get
5927 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai8cae3c72021-03-12 20:05:08 +08005928 // Also set the requester UID and package name in the request.
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005929 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5930 callingUid, callingPackageName);
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005931
Etan Cohen3985c172017-02-05 10:42:27 -08005932 if (timeoutMs < 0) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005933 throw new IllegalArgumentException("Bad timeout specified");
5934 }
lucaslin8cf57f52019-10-22 18:27:33 +08005935 ensureValid(networkCapabilities);
Etan Cohend988de62015-11-18 10:56:15 -08005936
James Mattise494cbb2021-02-09 18:18:28 -08005937 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaid1a78162021-01-11 16:53:38 +08005938 nextNetworkRequestId(), reqType);
James Mattise494cbb2021-02-09 18:18:28 -08005939 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colittib199b962021-03-12 22:48:07 +09005940 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colittif2514122021-03-12 22:50:57 +09005941 callingAttributionTag);
Erik Kline47401fa2015-07-09 18:24:03 +09005942 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005943
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005944 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5945 // copied from the default request above. (This is necessary to ensure, for example, that
5946 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5947 // changes don't alter request matching.
5948 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5949 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colittid5e9f982021-02-10 11:59:07 +09005950 throw new IllegalStateException(
5951 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005952 + networkCapabilities + " vs. " + defaultNc);
5953 }
5954
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005955 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07005956 if (timeoutMs > 0) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005957 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07005958 nri), timeoutMs);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005959 }
5960 return networkRequest;
5961 }
5962
James Mattise494cbb2021-02-09 18:18:28 -08005963 /**
5964 * Return the nri to be used when registering a network request. Specifically, this is used with
5965 * requests registered to track the default request. If there is currently a per-app default
5966 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5967 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colittif2514122021-03-12 22:50:57 +09005968 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5969 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08005970 * @param nr the network request for the nri.
5971 * @param msgr the messenger for the nri.
5972 * @param binder the binder for the nri.
5973 * @param callingAttributionTag the calling attribution tag for the nri.
5974 * @return the nri to register.
5975 */
Lorenzo Colittif2514122021-03-12 22:50:57 +09005976 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattise494cbb2021-02-09 18:18:28 -08005977 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius7992afd2020-12-22 15:10:42 -08005978 @NetworkCallback.Flag int callbackFlags,
James Mattise494cbb2021-02-09 18:18:28 -08005979 @Nullable String callingAttributionTag) {
5980 final List<NetworkRequest> requests;
5981 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
5982 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09005983 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattise494cbb2021-02-09 18:18:28 -08005984 } else {
5985 requests = Collections.singletonList(nr);
5986 }
Roshan Pius7992afd2020-12-22 15:10:42 -08005987 return new NetworkRequestInfo(
Lorenzo Colittif2514122021-03-12 22:50:57 +09005988 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattise494cbb2021-02-09 18:18:28 -08005989 }
5990
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07005991 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
5992 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti98097292015-05-14 17:28:27 +09005993 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichic4899352016-07-19 15:59:27 +09005994 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin94c30992014-11-05 10:32:09 -08005995 } else {
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07005996 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin94c30992014-11-05 10:32:09 -08005997 }
5998 }
5999
fenglu76564332015-03-20 11:29:56 -07006000 @Override
fenglu73169332015-04-21 17:12:05 -07006001 public boolean requestBandwidthUpdate(Network network) {
fenglu76564332015-03-20 11:29:56 -07006002 enforceAccessPermission();
6003 NetworkAgentInfo nai = null;
6004 if (network == null) {
6005 return false;
6006 }
6007 synchronized (mNetworkForNetId) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006008 nai = mNetworkForNetId.get(network.getNetId());
fenglu76564332015-03-20 11:29:56 -07006009 }
6010 if (nai != null) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006011 nai.onBandwidthUpdateRequested();
Nathan Harold6179b142018-07-30 13:38:01 -07006012 synchronized (mBandwidthRequests) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006013 final int uid = mDeps.getCallingUid();
Nathan Harold6179b142018-07-30 13:38:01 -07006014 Integer uidReqs = mBandwidthRequests.get(uid);
6015 if (uidReqs == null) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006016 uidReqs = 0;
Nathan Harold6179b142018-07-30 13:38:01 -07006017 }
6018 mBandwidthRequests.put(uid, ++uidReqs);
6019 }
fenglu76564332015-03-20 11:29:56 -07006020 return true;
6021 }
6022 return false;
6023 }
6024
Felipe Lemeff760142016-06-20 16:36:29 -07006025 private boolean isSystem(int uid) {
6026 return uid < Process.FIRST_APPLICATION_UID;
6027 }
fenglu76564332015-03-20 11:29:56 -07006028
Jeremy Joslin94c30992014-11-05 10:32:09 -08006029 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006030 final int uid = mDeps.getCallingUid();
Felipe Lemeff760142016-06-20 16:36:29 -07006031 if (isSystem(uid)) {
Hugo Benichi0a28d302017-02-11 17:04:43 +09006032 // Exemption for system uid.
Felipe Lemeff760142016-06-20 16:36:29 -07006033 return;
6034 }
Hugo Benichi0a28d302017-02-11 17:04:43 +09006035 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6036 // Policy already enforced.
6037 return;
6038 }
paulhu76cf0c52020-12-24 19:47:34 +08006039 final long ident = Binder.clearCallingIdentity();
6040 try {
6041 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6042 // If UID is restricted, don't allow them to bring up metered APNs.
6043 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6044 }
6045 } finally {
6046 Binder.restoreCallingIdentity(ident);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006047 }
6048 }
6049
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006050 @Override
6051 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07006052 PendingIntent operation, @NonNull String callingPackageName,
6053 @Nullable String callingAttributionTag) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006054 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006055 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin94c30992014-11-05 10:32:09 -08006056 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07006057 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6058 callingAttributionTag);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006059 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09006060 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006061 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006062 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohenb184cba2017-04-03 17:42:34 -07006063 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006064 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6065 callingUid, callingPackageName);
Etan Cohendb38d9d2017-04-03 12:17:51 -07006066
Jeremy Joslin94c30992014-11-05 10:32:09 -08006067 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006068 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006069 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6070 callingAttributionTag);
Erik Kline47401fa2015-07-09 18:24:03 +09006071 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006072 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6073 nri));
6074 return networkRequest;
6075 }
6076
Jeremy Joslinb9846d02014-12-03 17:15:28 -08006077 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6078 mHandler.sendMessageDelayed(
6079 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colittie0857092021-03-12 22:39:08 +09006080 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslinb9846d02014-12-03 17:15:28 -08006081 }
6082
Jeremy Joslin94c30992014-11-05 10:32:09 -08006083 @Override
6084 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006085 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin94c30992014-11-05 10:32:09 -08006086 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colittie0857092021-03-12 22:39:08 +09006087 mDeps.getCallingUid(), 0, operation));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006088 }
6089
Lorenzo Colitti15ff2fc2015-04-22 10:44:49 +09006090 // In order to implement the compatibility measure for pre-M apps that call
6091 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6092 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6093 // This ensures it has permission to do so.
6094 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6095 if (nc == null) {
6096 return false;
6097 }
6098 int[] transportTypes = nc.getTransportTypes();
6099 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6100 return false;
6101 }
6102 try {
6103 mContext.enforceCallingOrSelfPermission(
6104 android.Manifest.permission.ACCESS_WIFI_STATE,
6105 "ConnectivityService");
6106 } catch (SecurityException e) {
6107 return false;
6108 }
6109 return true;
6110 }
6111
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006112 @Override
6113 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius7992afd2020-12-22 15:10:42 -08006114 Messenger messenger, IBinder binder,
6115 @NetworkCallback.Flag int callbackFlags,
6116 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006117 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti15ff2fc2015-04-22 10:44:49 +09006118 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6119 enforceAccessPermission();
6120 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006121
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09006122 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006123 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006124 Binder.getCallingPid(), callingUid, callingPackageName);
6125 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeana43eede2018-03-20 19:13:57 +09006126 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6127 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6128 // onLost and onAvailable callbacks when networks move in and out of the background.
6129 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6130 // can't request networks.
6131 restrictBackgroundRequestForCaller(nc);
lucaslin8cf57f52019-10-22 18:27:33 +08006132 ensureValid(nc);
Etan Cohendb38d9d2017-04-03 12:17:51 -07006133
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09006134 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006135 NetworkRequest.Type.LISTEN);
Roshan Piusc97d8062020-12-17 14:53:09 -08006136 NetworkRequestInfo nri =
Lorenzo Colittif2514122021-03-12 22:50:57 +09006137 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius7992afd2020-12-22 15:10:42 -08006138 callingAttributionTag);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09006139 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006140
6141 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6142 return networkRequest;
6143 }
6144
6145 @Override
6146 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusc97d8062020-12-17 14:53:09 -08006147 PendingIntent operation, @NonNull String callingPackageName,
6148 @Nullable String callingAttributionTag) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006149 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006150 final int callingUid = mDeps.getCallingUid();
Paul Jensen9ceed862015-06-17 14:15:39 -04006151 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6152 enforceAccessPermission();
6153 }
lucaslin8cf57f52019-10-22 18:27:33 +08006154 ensureValid(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006155 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006156 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09006157 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006158 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09006159
6160 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006161 NetworkRequest.Type.LISTEN);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006162 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6163 callingAttributionTag);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09006164 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen9ceed862015-06-17 14:15:39 -04006165
6166 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006167 }
6168
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006169 /** Returns the next Network provider ID. */
6170 public final int nextNetworkProviderId() {
6171 return mNextNetworkProviderId.getAndIncrement();
6172 }
6173
James Mattisc449dde2020-11-20 16:08:10 -08006174 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
James Mattis3f93a312020-11-12 15:53:42 -08006175 for (int i = 0; i < networkRequests.size(); i++) {
6176 releaseNetworkRequest(networkRequests.get(i));
6177 }
6178 }
6179
Erik Klineaec3f5e2016-07-07 16:50:58 +09006180 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006181 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitticef9c492016-07-05 01:22:13 +09006182 ensureNetworkRequestHasType(networkRequest);
Erik Klineaec3f5e2016-07-07 16:50:58 +09006183 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colittie0857092021-03-12 22:39:08 +09006184 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006185 }
6186
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006187 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6188 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006189 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6190 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6191 // as that will throw if a duplicate provider is registered.
Aaron Huang11e9a312020-10-30 22:04:25 +08006192 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006193 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006194 return;
6195 }
6196
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006197 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6198 mNetworkProviderInfos.put(npi.messenger, npi);
6199 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006200 }
6201
6202 @Override
6203 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006204 enforceNetworkFactoryOrSettingsPermission();
Aaron Huang6a16a412021-04-09 12:06:42 +08006205 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006206 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifr1c0d9b22021-03-10 13:58:14 +08006207 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006208 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6209 return npi.providerId;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006210 }
6211
6212 @Override
6213 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006214 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006215 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07006216 }
6217
Chalard Jean1ef1d902021-01-05 08:40:09 +09006218 @Override
Chalard Jeanb004da52021-03-22 22:44:02 +09006219 public void offerNetwork(final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09006220 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6221 @NonNull final INetworkOfferCallback callback) {
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006222 Objects.requireNonNull(score);
6223 Objects.requireNonNull(caps);
6224 Objects.requireNonNull(callback);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006225 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanb004da52021-03-22 22:44:02 +09006226 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6228 }
6229
6230 @Override
6231 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6233 }
6234
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006235 private void handleUnregisterNetworkProvider(Messenger messenger) {
6236 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6237 if (npi == null) {
6238 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07006239 return;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006240 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09006241 // Unregister all the offers from this provider
6242 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6243 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jeanb004da52021-03-22 22:44:02 +09006244 if (noi.offer.providerId == npi.providerId) {
Chalard Jean1ef1d902021-01-05 08:40:09 +09006245 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6246 toRemove.add(noi);
6247 }
6248 }
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006249 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jean1ef1d902021-01-05 08:40:09 +09006250 handleUnregisterNetworkOffer(noi);
6251 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006252 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt948aea52014-04-11 15:53:27 -07006253 }
6254
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006255 @Override
James Mattis08131f32020-12-13 16:28:14 -08006256 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006257 if (request.hasTransport(TRANSPORT_TEST)) {
6258 enforceNetworkFactoryOrTestNetworksPermission();
6259 } else {
6260 enforceNetworkFactoryPermission();
6261 }
James Mattis08131f32020-12-13 16:28:14 -08006262 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6263 if (nri != null) {
6264 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6265 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6266 mHandler.post(() -> handleReleaseNetworkRequest(
6267 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6268 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006269 }
6270
Paul Jensenc2569432015-02-13 14:18:39 -05006271 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6272 @GuardedBy("mNetworkForNetId")
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006273 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensenc2569432015-02-13 14:18:39 -05006274 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006275 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensenc2569432015-02-13 14:18:39 -05006276 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006277 private final NetIdManager mNetIdManager;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006278
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006279 // NetworkAgentInfo keyed off its connecting messenger
6280 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensenc2569432015-02-13 14:18:39 -05006281 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006282 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006283
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09006284 // UID ranges for users that are currently blocked by VPNs.
6285 // This array is accessed and iterated on multiple threads without holding locks, so its
6286 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6287 // (on the handler thread).
6288 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6289
Chalard Jean1ef1d902021-01-05 08:40:09 +09006290 // Must only be accessed on the handler thread
6291 @NonNull
6292 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6293
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09006294 @GuardedBy("mBlockedAppUids")
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006295 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09006296
Chalard Jean9d968182021-02-25 21:46:34 +09006297 // Current OEM network preferences. This object must only be written to on the handler thread.
6298 // Since it is immutable and always non-null, other threads may read it if they only care
6299 // about seeing a consistent object but not that it is current.
James Mattis6e6fabf2021-01-10 14:24:24 -08006300 @NonNull
6301 private OemNetworkPreferences mOemNetworkPreferences =
6302 new OemNetworkPreferences.Builder().build();
Chalard Jean9d968182021-02-25 21:46:34 +09006303 // Current per-profile network preferences. This object follows the same threading rules as
6304 // the OEM network preferences above.
6305 @NonNull
6306 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
James Mattis6e6fabf2021-01-10 14:24:24 -08006307
James Mattis6e4405f2021-04-06 17:07:42 -07006308 // OemNetworkPreferences activity String log entries.
6309 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6310 @NonNull
6311 private final LocalLog mOemNetworkPreferencesLogs =
6312 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6313
James Mattisbd275dc2021-03-13 19:27:21 -08006314 /**
6315 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6316 * @param packageName the package name to check existence of a mapping for.
6317 * @return true if a mapping exists, false otherwise
6318 */
6319 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6320 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6321 }
6322
James Mattis8af2d602020-12-20 11:09:58 -08006323 // The always-on request for an Internet-capable network that apps without a specific default
6324 // fall back to.
James Mattis6e6fabf2021-01-10 14:24:24 -08006325 @VisibleForTesting
Chalard Jean4deee632019-11-05 14:40:23 +09006326 @NonNull
James Mattis6e6fabf2021-01-10 14:24:24 -08006327 final NetworkRequestInfo mDefaultRequest;
James Mattis8af2d602020-12-20 11:09:58 -08006328 // Collection of NetworkRequestInfo's used for default networks.
James Mattis6e6fabf2021-01-10 14:24:24 -08006329 @VisibleForTesting
James Mattis8af2d602020-12-20 11:09:58 -08006330 @NonNull
James Mattis6e6fabf2021-01-10 14:24:24 -08006331 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09006332
James Mattis1238af22020-12-23 16:37:26 -08006333 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6334 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6335 }
6336
6337 /**
James Mattise494cbb2021-02-09 18:18:28 -08006338 * Return the default network request currently tracking the given uid.
6339 * @param uid the uid to check.
6340 * @return the NetworkRequestInfo tracking the given uid.
6341 */
6342 @NonNull
James Mattisbd275dc2021-03-13 19:27:21 -08006343 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
James Mattise494cbb2021-02-09 18:18:28 -08006344 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6345 if (nri == mDefaultRequest) {
6346 continue;
6347 }
6348 // Checking the first request is sufficient as only multilayer requests will have more
6349 // than one request and for multilayer, all requests will track the same uids.
6350 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6351 return nri;
6352 }
6353 }
6354 return mDefaultRequest;
6355 }
6356
6357 /**
6358 * Get a copy of the network requests of the default request that is currently tracking the
6359 * given uid.
Lorenzo Colittif2514122021-03-12 22:50:57 +09006360 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6361 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08006362 * @param requestorUid the uid to check the default for.
6363 * @param requestorPackageName the requestor's package name.
6364 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6365 */
6366 @NonNull
6367 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006368 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattise494cbb2021-02-09 18:18:28 -08006369 return copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006370 getDefaultRequestTrackingUid(asUid).mRequests,
6371 asUid, requestorUid, requestorPackageName);
James Mattise494cbb2021-02-09 18:18:28 -08006372 }
6373
6374 /**
6375 * Copy the given nri's NetworkRequest collection.
6376 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colittif2514122021-03-12 22:50:57 +09006377 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6378 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08006379 * @param requestorUid the uid to set on the copied collection.
6380 * @param requestorPackageName the package name to set on the copied collection.
6381 * @return the copied NetworkRequest collection.
6382 */
6383 @NonNull
6384 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006385 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6386 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattise494cbb2021-02-09 18:18:28 -08006387 final List<NetworkRequest> requests = new ArrayList<>();
6388 for (final NetworkRequest nr : requestsToCopy) {
6389 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006390 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattise494cbb2021-02-09 18:18:28 -08006391 nr.legacyType, nextNetworkRequestId(), nr.type));
6392 }
6393 return requests;
6394 }
6395
6396 @NonNull
6397 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006398 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6399 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colittic62368f2021-03-22 02:12:04 +09006400 // These capabilities are for a TRACK_DEFAULT callback, so:
6401 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6402 // mDefaultRequest and a per-UID default request.
6403 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colittif2514122021-03-12 22:50:57 +09006404 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colittic62368f2021-03-22 02:12:04 +09006405 // not do this in the case of a privileged application.
James Mattise494cbb2021-02-09 18:18:28 -08006406 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6407 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006408 netCap.setSingleUid(asUid);
James Mattise494cbb2021-02-09 18:18:28 -08006409 restrictRequestUidsForCallerAndSetRequestorInfo(
6410 netCap, requestorUid, requestorPackageName);
6411 return netCap;
6412 }
6413
6414 /**
6415 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6416 * @param nr the network request to check for equality against.
6417 * @return the nri if one exists, null otherwise.
6418 */
6419 @Nullable
6420 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6421 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6422 if (nri.getNetworkRequestForCallback().equals(nr)) {
6423 return nri;
6424 }
6425 }
6426 return null;
6427 }
6428
6429 /**
6430 * Check if an nri is currently being managed by per-app default networking.
6431 * @param nri the nri to check.
6432 * @return true if this nri is currently being managed by per-app default networking.
6433 */
6434 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6435 // nri.mRequests.get(0) is only different from the original request filed in
6436 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6437 // functionality therefore if these two don't match, it means this particular nri is
6438 // currently being managed by a per-app default.
6439 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6440 }
6441
6442 /**
James Mattis1238af22020-12-23 16:37:26 -08006443 * Determine if an nri is a managed default request that disallows default networking.
6444 * @param nri the request to evaluate
6445 * @return true if device-default networking is disallowed
6446 */
6447 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6448 // Check if this nri is a managed default that supports the default network at its
6449 // lowest priority request.
6450 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6451 final NetworkCapabilities lowestPriorityNetCap =
6452 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6453 return isPerAppDefaultRequest(nri)
6454 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6455 lowestPriorityNetCap));
6456 }
6457
Erik Kline74d68ef2015-04-30 12:58:40 +09006458 // Request used to optionally keep mobile data active even when higher
6459 // priority networks like Wi-Fi are active.
6460 private final NetworkRequest mDefaultMobileDataRequest;
6461
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07006462 // Request used to optionally keep wifi data active even when higher
6463 // priority networks like ethernet are active.
6464 private final NetworkRequest mDefaultWifiRequest;
6465
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08006466 // Request used to optionally keep vehicle internal network always active
6467 private final NetworkRequest mDefaultVehicleRequest;
6468
James Mattis1238af22020-12-23 16:37:26 -08006469 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6470 // network with no service. This NAI should never be matched against, nor should any public API
6471 // ever return the associated network. For this reason, this NAI is not in the list of available
6472 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6473 // default requests that don't support using the device default network which will ultimately
6474 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6475 @VisibleForTesting
6476 final NetworkAgentInfo mNoServiceNetwork;
6477
Chalard Jean1bc77a92021-02-04 13:12:59 +09006478 // The NetworkAgentInfo currently satisfying the default request, if any.
6479 private NetworkAgentInfo getDefaultNetwork() {
6480 return mDefaultRequest.mSatisfier;
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09006481 }
6482
James Mattisf61f7be2021-01-31 17:06:19 -08006483 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6484 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6485 // Currently, all network requests will have the same uids therefore checking the first
6486 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wangd5034c72021-02-22 18:36:38 +08006487 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattisf61f7be2021-01-31 17:06:19 -08006488 if (null == uids) {
6489 continue;
6490 }
6491 for (final UidRange range : uids) {
6492 if (range.contains(uid)) {
6493 return nri.getSatisfier();
6494 }
6495 }
6496 }
6497 return getDefaultNetwork();
6498 }
6499
Varun Anand273f9002019-02-06 10:13:38 -08006500 @Nullable
6501 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6502 return nai != null ? nai.network : null;
6503 }
6504
6505 private void ensureRunningOnConnectivityServiceThread() {
6506 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6507 throw new IllegalStateException(
6508 "Not running on ConnectivityService thread: "
6509 + Thread.currentThread().getName());
6510 }
6511 }
6512
Chalard Jean8cc4e872019-04-10 23:07:55 +09006513 @VisibleForTesting
Chalard Jean1bc77a92021-02-04 13:12:59 +09006514 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6515 return nai == getDefaultNetwork();
Robert Greenwaltb264cd82014-08-06 21:32:18 -07006516 }
6517
Chalard Jean44689aa2018-05-02 21:14:54 +09006518 /**
6519 * Register a new agent with ConnectivityService to handle a network.
6520 *
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006521 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean44689aa2018-05-02 21:14:54 +09006522 * @param networkInfo the initial info associated with this network. It can be updated later :
6523 * see {@link #updateNetworkInfo}.
6524 * @param linkProperties the initial link properties of this network. They can be updated
6525 * later : see {@link #updateLinkProperties}.
6526 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean945f2482019-12-12 13:56:13 +09006527 * later : see {@link #updateCapabilities}.
Chalard Jeandd753522020-12-21 18:36:52 +09006528 * @param initialScore the initial score of the network. See
Chalard Jean44689aa2018-05-02 21:14:54 +09006529 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colitticf595362020-01-12 22:28:37 +09006530 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006531 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeana973c7a2019-12-13 19:47:12 +09006532 * @return the network created for this agent.
Chalard Jean44689aa2018-05-02 21:14:54 +09006533 */
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006534 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean44689aa2018-05-02 21:14:54 +09006535 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeandd753522020-12-21 18:36:52 +09006536 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6537 int providerId) {
Lorenzo Colitti83d06562021-01-18 14:15:17 +09006538 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6539 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6540 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jeandd753522020-12-21 18:36:52 +09006541 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colitti83d06562021-01-18 14:15:17 +09006542 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006543 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6544 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006545 } else {
6546 enforceNetworkFactoryPermission();
6547 }
6548
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006549 final int uid = mDeps.getCallingUid();
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006550 final long token = Binder.clearCallingIdentity();
6551 try {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006552 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeandd753522020-12-21 18:36:52 +09006553 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006554 } finally {
6555 Binder.restoreCallingIdentity(token);
6556 }
6557 }
6558
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006559 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006560 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeandd753522020-12-21 18:36:52 +09006561 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6562 int uid) {
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006563 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006564 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6565 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6566 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6567 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006568 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006569 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006570
Rubin Xu57b437a2017-09-05 18:40:49 +01006571 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006572
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09006573 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006574 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006575 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jeande419812020-03-04 17:45:08 +09006576 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jeane634b282021-03-05 23:07:53 +09006577 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6578 mQosCallbackTracker, mDeps);
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006579
6580 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006581 processCapabilitiesFromAgent(nai, nc);
Chalard Jean8ffefba2019-11-22 22:39:56 +09006582 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006583 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6584
Chalard Jeandf2478a2018-04-26 16:16:10 +09006585 final String extraInfo = networkInfo.getExtraInfo();
6586 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jeanbd958b32020-03-18 15:58:50 +09006587 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt721f2372014-08-27 14:34:02 -07006588 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006589 mDeps.getNetworkStack().makeNetworkMonitor(
6590 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006591 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6592 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006593 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006594 // registration.
Chalard Jeana973c7a2019-12-13 19:47:12 +09006595 return nai.network;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006596 }
6597
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006598 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6599 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006600 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006601 mNetworkAgentInfos.add(nai);
Paul Jensenc2569432015-02-13 14:18:39 -05006602 synchronized (mNetworkForNetId) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006603 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensenc2569432015-02-13 14:18:39 -05006604 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006605
6606 try {
6607 networkMonitor.start();
6608 } catch (RemoteException e) {
Chiachang Wang619a8a22019-04-24 21:44:05 +08006609 e.rethrowAsRuntimeException();
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006610 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006611 nai.notifyRegistered();
Erik Kline79371012018-03-04 21:01:01 +09006612 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline79371012018-03-04 21:01:01 +09006613 updateNetworkInfo(nai, networkInfo);
6614 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006615 }
6616
Chalard Jean1ef1d902021-01-05 08:40:09 +09006617 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6618 @NonNull public final NetworkOffer offer;
6619
6620 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6621 this.offer = offer;
6622 }
6623
6624 @Override
6625 public void binderDied() {
6626 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6627 }
6628 }
6629
Chalard Jean7618f1a2021-03-24 14:31:38 +09006630 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6631 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6632 if (npi.providerId == providerId) return true;
6633 }
6634 return false;
6635 }
6636
Chalard Jean1ef1d902021-01-05 08:40:09 +09006637 /**
6638 * Register or update a network offer.
6639 * @param newOffer The new offer. If the callback member is the same as an existing
6640 * offer, it is an update of that offer.
6641 */
6642 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6643 ensureRunningOnConnectivityServiceThread();
Chalard Jean7618f1a2021-03-24 14:31:38 +09006644 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6645 // This may actually happen if a provider updates its score or registers and then
6646 // immediately unregisters. The offer would still be in the handler queue, but the
6647 // provider would have been removed.
6648 if (DBG) log("Received offer from an unregistered provider");
6649 return;
6650 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09006651 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6652 if (null != existingOffer) {
6653 handleUnregisterNetworkOffer(existingOffer);
6654 newOffer.migrateFrom(existingOffer.offer);
6655 }
6656 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6657 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09006658 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006659 } catch (RemoteException e) {
6660 noi.binderDied();
6661 return;
6662 }
6663 mNetworkOffers.add(noi);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006664 issueNetworkNeeds(noi);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006665 }
6666
6667 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6668 ensureRunningOnConnectivityServiceThread();
6669 mNetworkOffers.remove(noi);
Chalard Jeanb004da52021-03-22 22:44:02 +09006670 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006671 }
6672
6673 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6674 @NonNull final INetworkOfferCallback callback) {
6675 ensureRunningOnConnectivityServiceThread();
6676 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jeanf1364432021-04-08 17:37:36 +09006677 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jean1ef1d902021-01-05 08:40:09 +09006678 }
6679 return null;
6680 }
6681
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006682 /**
6683 * Called when receiving LinkProperties directly from a NetworkAgent.
6684 * Stores into |nai| any data coming from the agent that might also be written to the network's
6685 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6686 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti3c75ca82020-12-02 13:58:47 +09006687 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006688 */
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006689 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6690 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colitti54fb93f2020-04-01 22:25:16 +09006691 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalom492febb2021-01-11 18:45:34 -08006692 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006693 }
6694
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006695 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006696 @NonNull LinkProperties oldLp) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006697 int netId = networkAgent.network.getNetId();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006698
Lorenzo Colittifff75392020-04-01 20:16:30 +09006699 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6700 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6701 // the LinkProperties for the network are accurate.
Lorenzo Colitti07f10202019-01-08 14:43:37 +09006702 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti667da282014-09-20 13:47:47 +09006703
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006704 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006705
6706 // update filtering rules, need to happen after the interface update so netd knows about the
6707 // new interface (the interface name -> index map becomes initialized)
6708 updateVpnFiltering(newLp, oldLp, networkAgent);
6709
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006710 updateMtu(newLp, oldLp);
6711 // TODO - figure out what to do for clat
6712// for (LinkProperties lp : newLp.getStackedLinks()) {
6713// updateMtu(lp, null);
6714// }
Chalard Jean1bc77a92021-02-04 13:12:59 +09006715 if (isDefaultNetwork(networkAgent)) {
lucaslin589964b2018-11-28 19:27:52 +08006716 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6717 }
Lorenzo Colittiaa4f1f62014-11-28 20:07:46 +09006718
Erik Kline3d4ed152016-04-05 13:30:49 +09006719 updateRoutes(newLp, oldLp, netId);
6720 updateDnses(newLp, oldLp, netId);
dalykf4977492018-03-05 12:42:22 -05006721 // Make sure LinkProperties represents the latest private DNS status.
6722 // This does not need to be done before updateDnses because the
6723 // LinkProperties are not the source of the private DNS configuration.
6724 // updateDnses will fetch the private DNS configuration from DnsManager.
6725 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colittiaa4f1f62014-11-28 20:07:46 +09006726
Chalard Jean1bc77a92021-02-04 13:12:59 +09006727 if (isDefaultNetwork(networkAgent)) {
Paul Jensen12131352014-12-10 15:12:18 -05006728 handleApplyDefaultProxy(newLp.getHttpProxy());
6729 } else {
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006730 updateProxy(newLp, oldLp);
Paul Jensen12131352014-12-10 15:12:18 -05006731 }
Valentin Iftimea039e572019-09-24 13:32:13 +02006732
6733 updateWakeOnLan(newLp);
6734
Hai Shalom492febb2021-01-11 18:45:34 -08006735 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6736 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6737 // does, it needs to be merged here.
6738 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6739 networkAgent.capportApiData));
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09006740
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07006741 // TODO - move this check to cover the whole function
6742 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanf2f75592018-05-23 09:07:51 +09006743 synchronized (networkAgent) {
6744 networkAgent.linkProperties = newLp;
6745 }
Lorenzo Colitti714b7862019-02-19 13:21:56 +09006746 // Start or stop DNS64 detection and 464xlat according to network state.
6747 networkAgent.clatd.update();
Jeff Davidson9804c892016-01-20 11:35:38 -08006748 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VAN3b1d8b42020-05-10 16:11:11 +09006749 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6750 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin34cd3942018-11-28 12:51:55 +08006751 if (networkAgent.everConnected) {
6752 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6753 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07006754 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09006755
6756 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen7d854042014-05-13 11:44:01 -04006757 }
6758
Hai Shalom492febb2021-01-11 18:45:34 -08006759 /**
6760 * @param naData captive portal data from NetworkAgent
6761 * @param apiData captive portal data from capport API
6762 */
6763 @Nullable
6764 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6765 CaptivePortalData apiData) {
6766 if (naData == null || apiData == null) {
6767 return naData == null ? apiData : naData;
6768 }
6769 final CaptivePortalData.Builder captivePortalBuilder =
6770 new CaptivePortalData.Builder(naData);
6771
6772 if (apiData.isCaptive()) {
6773 captivePortalBuilder.setCaptive(true);
6774 }
6775 if (apiData.isSessionExtendable()) {
6776 captivePortalBuilder.setSessionExtendable(true);
6777 }
6778 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6779 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6780 // otherwise data would be inconsistent. Prefer the capport API info if present,
6781 // as it can generally be refreshed more often.
6782 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6783 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6784 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6785 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6786 // No source has time / bytes remaining information: surface the newest refresh time
6787 // for other fields
6788 captivePortalBuilder.setRefreshTime(
6789 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6790 }
6791
Hai Shalom7fcd18a2021-02-04 19:34:06 -08006792 // Prioritize the user portal URL from the network agent if the source is authenticated.
6793 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6794 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6795 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6796 apiData.getUserPortalUrlSource());
Hai Shalom492febb2021-01-11 18:45:34 -08006797 }
Hai Shalom7fcd18a2021-02-04 19:34:06 -08006798 // Prioritize the venue information URL from the network agent if the source is
6799 // authenticated.
6800 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6801 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6802 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6803 apiData.getVenueInfoUrlSource());
Hai Shalom492febb2021-01-11 18:45:34 -08006804 }
6805 return captivePortalBuilder.build();
6806 }
6807
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006808 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean73d9db72018-06-04 16:52:49 +09006809 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006810 // marks on unsupported interfaces is harmless.
6811 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6812 return;
6813 }
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006814
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09006815 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6816 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6817
6818 // TODO (b/183076074): remove legacy fallback after migrating overlays
6819 final int legacyMark = mContext.getResources().getInteger(mContext.getResources()
6820 .getIdentifier("config_networkWakeupPacketMark", "integer", "android"));
6821 final int legacyMask = mContext.getResources().getInteger(mContext.getResources()
6822 .getIdentifier("config_networkWakeupPacketMask", "integer", "android"));
6823 mark = mark == 0 ? legacyMark : mark;
6824 mask = mask == 0 ? legacyMask : mask;
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006825
6826 // Mask/mark of zero will not detect anything interesting.
6827 // Don't install rules unless both values are nonzero.
6828 if (mark == 0 || mask == 0) {
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006829 return;
6830 }
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006831
6832 final String prefix = "iface:" + iface;
6833 try {
6834 if (add) {
Luke Huang358aa262018-09-27 19:33:11 +08006835 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006836 } else {
Luke Huang358aa262018-09-27 19:33:11 +08006837 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006838 }
6839 } catch (Exception e) {
6840 loge("Exception modifying wakeup packet monitoring: " + e);
6841 }
6842
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006843 }
6844
Chalard Jeane5550312019-11-19 19:03:53 +09006845 private void updateInterfaces(final @Nullable LinkProperties newLp,
6846 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006847 final @NonNull NetworkCapabilities caps) {
Chalard Jeane5550312019-11-19 19:03:53 +09006848 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu8cb82d22017-08-22 16:35:52 +01006849 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6850 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jeane5550312019-11-19 19:03:53 +09006851 if (!interfaceDiff.added.isEmpty()) {
Chalard Jeane5550312019-11-19 19:03:53 +09006852 for (final String iface : interfaceDiff.added) {
6853 try {
6854 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wanga93ddb22020-10-26 14:23:52 +08006855 mNetd.networkAddInterface(netId, iface);
Chalard Jeane5550312019-11-19 19:03:53 +09006856 wakeupModifyInterface(iface, caps, true);
Aaron Huange044c462020-10-27 03:36:19 +08006857 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6858 caps.getTransportTypes());
Chalard Jeane5550312019-11-19 19:03:53 +09006859 } catch (Exception e) {
lucaslin3967e5f2021-04-01 19:17:08 +08006860 logw("Exception adding interface: " + e);
Chalard Jeane5550312019-11-19 19:03:53 +09006861 }
Paul Jensen6b197532014-04-28 10:33:11 -04006862 }
6863 }
Chalard Jeane5550312019-11-19 19:03:53 +09006864 for (final String iface : interfaceDiff.removed) {
Paul Jensen6b197532014-04-28 10:33:11 -04006865 try {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006866 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006867 wakeupModifyInterface(iface, caps, false);
Chiachang Wanga93ddb22020-10-26 14:23:52 +08006868 mNetd.networkRemoveInterface(netId, iface);
Paul Jensen6b197532014-04-28 10:33:11 -04006869 } catch (Exception e) {
6870 loge("Exception removing interface: " + e);
6871 }
6872 }
6873 }
6874
Tyler Weara8978d42019-12-05 14:55:30 -08006875 // TODO: move to frameworks/libs/net.
6876 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6877 final String nextHop;
6878
6879 switch (route.getType()) {
6880 case RouteInfo.RTN_UNICAST:
6881 if (route.hasGateway()) {
6882 nextHop = route.getGateway().getHostAddress();
6883 } else {
6884 nextHop = INetd.NEXTHOP_NONE;
6885 }
6886 break;
6887 case RouteInfo.RTN_UNREACHABLE:
6888 nextHop = INetd.NEXTHOP_UNREACHABLE;
6889 break;
6890 case RouteInfo.RTN_THROW:
6891 nextHop = INetd.NEXTHOP_THROW;
6892 break;
6893 default:
6894 nextHop = INetd.NEXTHOP_NONE;
6895 break;
6896 }
6897
6898 final RouteInfoParcel rip = new RouteInfoParcel();
6899 rip.ifName = route.getInterface();
6900 rip.destination = route.getDestination().toString();
6901 rip.nextHop = nextHop;
6902 rip.mtu = route.getMtu();
6903
6904 return rip;
6905 }
6906
Paul Jensen1b79a592014-08-06 15:51:33 -04006907 /**
6908 * Have netd update routes from oldLp to newLp.
6909 * @return true if routes changed between oldLp and newLp
6910 */
6911 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weara8978d42019-12-05 14:55:30 -08006912 // compare the route diff to determine which routes have been updated
junyulai21c26da2020-03-23 20:49:43 +08006913 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
6914 new CompareOrUpdateResult<>(
6915 oldLp != null ? oldLp.getAllRoutes() : null,
6916 newLp != null ? newLp.getAllRoutes() : null,
6917 (r) -> r.getRouteKey());
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006918
6919 // add routes before removing old in case it helps with continuous connectivity
6920
Chalard Jean73d9db72018-06-04 16:52:49 +09006921 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006922 for (RouteInfo route : routeDiff.added) {
6923 if (route.hasGateway()) continue;
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006924 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006925 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006926 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006927 } catch (Exception e) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006928 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weara8978d42019-12-05 14:55:30 -08006929 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt721f2372014-08-27 14:34:02 -07006930 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006931 }
6932 }
6933 for (RouteInfo route : routeDiff.added) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006934 if (!route.hasGateway()) continue;
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006935 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006936 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006937 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006938 } catch (Exception e) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006939 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weara8978d42019-12-05 14:55:30 -08006940 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt721f2372014-08-27 14:34:02 -07006941 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006942 }
6943 }
6944
6945 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006946 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006947 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006948 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006949 } catch (Exception e) {
Tyler Weara8978d42019-12-05 14:55:30 -08006950 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006951 }
6952 }
Tyler Weara8978d42019-12-05 14:55:30 -08006953
6954 for (RouteInfo route : routeDiff.updated) {
6955 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
6956 try {
6957 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
6958 } catch (Exception e) {
6959 loge("Exception in networkUpdateRouteParcel: " + e);
6960 }
6961 }
6962 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
6963 || !routeDiff.updated.isEmpty();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006964 }
Erik Kline04270062015-06-17 13:19:54 +09006965
Erik Kline3d4ed152016-04-05 13:30:49 +09006966 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
6967 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
6968 return; // no updating necessary
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006969 }
Erik Kline3d4ed152016-04-05 13:30:49 +09006970
Erik Klinec06d4f92018-01-11 21:07:29 +09006971 if (DBG) {
6972 final Collection<InetAddress> dnses = newLp.getDnsServers();
6973 log("Setting DNS servers for network " + netId + " to " + dnses);
6974 }
Erik Kline3d4ed152016-04-05 13:30:49 +09006975 try {
chenbruce2e6b79f2020-02-20 14:28:31 +08006976 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce2e6b79f2020-02-20 14:28:31 +08006977 mDnsManager.flushVmDnsCache();
Erik Kline3d4ed152016-04-05 13:30:49 +09006978 } catch (Exception e) {
Pierre Imai5b5fe392016-04-28 17:00:04 +09006979 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline3d4ed152016-04-05 13:30:49 +09006980 }
Erik Klinebd18f302017-04-07 15:29:29 +09006981 }
6982
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006983 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
6984 NetworkAgentInfo nai) {
6985 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
6986 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
6987 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
6988 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
6989
6990 if (!wasFiltering && !needsFiltering) {
6991 // Nothing to do.
6992 return;
6993 }
6994
6995 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
6996 // Nothing changed.
6997 return;
6998 }
6999
Chiachang Wangd5034c72021-02-22 18:36:38 +08007000 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb3347b2020-01-17 17:54:27 -08007001 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007002 // TODO: this create a window of opportunity for apps to receive traffic between the time
7003 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey0d585432020-09-11 15:10:20 -06007004 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007005 // old rules are being removed.
7006 if (wasFiltering) {
7007 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7008 }
7009 if (needsFiltering) {
7010 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7011 }
7012 }
7013
Valentin Iftimea039e572019-09-24 13:32:13 +02007014 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09007015 if (mWolSupportedInterfaces == null) {
7016 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09007017 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09007018 }
Valentin Iftimea039e572019-09-24 13:32:13 +02007019 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7020 }
7021
Luke Huang089ebf12018-08-24 20:33:16 +08007022 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007023 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang089ebf12018-08-24 20:33:16 +08007024 return INetd.PERMISSION_SYSTEM;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007025 }
7026 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang089ebf12018-08-24 20:33:16 +08007027 return INetd.PERMISSION_NETWORK;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007028 }
Luke Huang089ebf12018-08-24 20:33:16 +08007029 return INetd.PERMISSION_NONE;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007030 }
7031
Chalard Jeana00029d2019-12-02 18:39:29 +09007032 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7033 @NonNull final NetworkCapabilities newNc) {
7034 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7035 final int newPermission = getNetworkPermission(newNc);
7036 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7037 try {
Serik Beketayev284cb872020-12-07 22:43:07 -08007038 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wang9695da32020-10-26 19:59:31 +08007039 } catch (RemoteException | ServiceSpecificException e) {
7040 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jeana00029d2019-12-02 18:39:29 +09007041 }
7042 }
7043 }
7044
Paul Jensen783c0e02015-06-16 14:27:36 -04007045 /**
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007046 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7047 * Stores into |nai| any data coming from the agent that might also be written to the network's
7048 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7049 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti3c75ca82020-12-02 13:58:47 +09007050 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007051 */
7052 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007053 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7054 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7055 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7056 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti39b4c5b2020-12-09 18:30:52 +09007057 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7058 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7059 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7060 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7061 }
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007062 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007063 }
7064
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007065 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007066 @VisibleForTesting
Lorenzo Colitti8750be02020-12-01 01:08:37 +09007067 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007068 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattisf61f7be2021-01-31 17:06:19 -08007069 underlyingNetworks = underlyingNetworksOrDefault(
7070 agentCaps.getOwnerUid(), underlyingNetworks);
lifrc33ea4d2021-03-04 14:08:08 +08007071 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007072 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7073 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007074 // metered if any underlying is metered, or originally declared metered by the agent.
7075 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007076 boolean roaming = false; // roaming if any underlying is roaming
7077 boolean congested = false; // congested if any underlying is congested
7078 boolean suspended = true; // suspended if all underlying are suspended
7079
7080 boolean hadUnderlyingNetworks = false;
7081 if (null != underlyingNetworks) {
7082 for (Network underlyingNetwork : underlyingNetworks) {
7083 final NetworkAgentInfo underlying =
7084 getNetworkAgentInfoForNetwork(underlyingNetwork);
7085 if (underlying == null) continue;
7086
7087 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7088 hadUnderlyingNetworks = true;
7089 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09007090 transportTypes |= 1L << underlyingType;
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007091 }
7092
7093 // Merge capabilities of this underlying network. For bandwidth, assume the
7094 // worst case.
7095 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7096 underlyingCaps.getLinkDownstreamBandwidthKbps());
7097 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7098 underlyingCaps.getLinkUpstreamBandwidthKbps());
7099 // If this underlying network is metered, the VPN is metered (it may cost money
7100 // to send packets on this network).
7101 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7102 // If this underlying network is roaming, the VPN is roaming (the billing structure
7103 // is different than the usual, local one).
7104 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7105 // If this underlying network is congested, the VPN is congested (the current
7106 // condition of the network affects the performance of this network).
7107 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7108 // If this network is not suspended, the VPN is not suspended (the VPN
7109 // is able to transfer some data).
7110 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7111 }
7112 }
7113 if (!hadUnderlyingNetworks) {
7114 // No idea what the underlying networks are; assume reasonable defaults
7115 metered = true;
7116 roaming = false;
7117 congested = false;
7118 suspended = false;
7119 }
7120
lifrc33ea4d2021-03-04 14:08:08 +08007121 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007122 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7123 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7124 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7125 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7126 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7127 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007128 }
7129
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007130 /**
Lorenzo Colitti72664112018-01-16 00:52:07 +09007131 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7132 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7133 * and foreground status).
Paul Jensen783c0e02015-06-16 14:27:36 -04007134 */
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09007135 @NonNull
Lorenzo Colitti72664112018-01-16 00:52:07 +09007136 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi2f90b2d2017-08-16 13:19:04 +09007137 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007138 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7139 // causing a connect/teardown loop.
Lorenzo Colitti94c93142020-01-10 00:40:28 +09007140 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007141 // avoid connect/teardown loops.
Lorenzo Colitti72664112018-01-16 00:52:07 +09007142 if (nai.everConnected &&
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007143 !nai.isVPN() &&
Lorenzo Colitti72664112018-01-16 00:52:07 +09007144 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7145 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi2f90b2d2017-08-16 13:19:04 +09007146 // does not cause any request (that is not a listen) currently matching that agent to
7147 // stop being matched by the updated agent.
Lorenzo Colitti72664112018-01-16 00:52:07 +09007148 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi8c928882017-07-25 11:40:56 +09007149 if (!TextUtils.isEmpty(diff)) {
Aaron Huang11e9a312020-10-30 22:04:25 +08007150 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi8c928882017-07-25 11:40:56 +09007151 }
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007152 }
7153
Paul Jensen783c0e02015-06-16 14:27:36 -04007154 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007155 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007156 if (nai.lastValidated) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007157 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen783c0e02015-06-16 14:27:36 -04007158 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007159 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen783c0e02015-06-16 14:27:36 -04007160 }
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007161 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007162 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen783c0e02015-06-16 14:27:36 -04007163 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007164 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen783c0e02015-06-16 14:27:36 -04007165 }
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007166 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007167 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007168 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007169 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007170 }
lucaslin25a50472019-03-12 13:08:03 +08007171 if (nai.partialConnectivity) {
7172 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7173 } else {
7174 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7175 }
lucaslin8cf57f52019-10-22 18:27:33 +08007176 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007177
Chalard Jeanc212ed12020-01-15 00:49:43 +09007178 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeanfa33a752020-01-14 22:46:36 +09007179 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7180 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanc212ed12020-01-15 00:49:43 +09007181 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeanfa33a752020-01-14 22:46:36 +09007182 }
7183
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007184 if (nai.supportsUnderlyingNetworks()) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007185 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7186 newNc);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007187 }
7188
Lorenzo Colitti72664112018-01-16 00:52:07 +09007189 return newNc;
7190 }
7191
Lorenzo Colitti246d1762021-01-11 22:27:57 +09007192 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7193 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7194 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7195 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7196 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7197 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7198 if (prevSuspended != suspended) {
7199 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7200 // onResumed have been removed.
7201 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7202 : ConnectivityManager.CALLBACK_RESUMED);
7203 }
7204 if (prevSuspended != suspended || prevRoaming != roaming) {
7205 // updateNetworkInfo will mix in the suspended info from the capabilities and
7206 // take appropriate action for the network having possibly changed state.
7207 updateNetworkInfo(nai, nai.networkInfo);
7208 }
7209 }
7210
Lorenzo Colitti72664112018-01-16 00:52:07 +09007211 /**
7212 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7213 *
7214 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7215 * capabilities we manage and store in {@code nai}, such as validated status and captive
7216 * portal status)
7217 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7218 * potentially triggers rematches.
7219 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7220 * change.)
7221 *
7222 * @param oldScore score of the network before any of the changes that prompted us
7223 * to call this function.
7224 * @param nai the network having its capabilities updated.
7225 * @param nc the new network capabilities.
7226 */
Chalard Jeana00029d2019-12-02 18:39:29 +09007227 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7228 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007229 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti72664112018-01-16 00:52:07 +09007230 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jeana00029d2019-12-02 18:39:29 +09007231 updateNetworkPermissions(nai, newNc);
Chalard Jean8ffefba2019-11-22 22:39:56 +09007232 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007233
Chalard Jeana39c91c2018-01-16 18:43:05 +09007234 updateUids(nai, prevNc, newNc);
Chalard Jean1fc55292021-03-31 23:19:05 +09007235 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeana39c91c2018-01-16 18:43:05 +09007236
Lorenzo Colitti72664112018-01-16 00:52:07 +09007237 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007238 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7239 // the change we're processing can't affect any requests, it can only affect the listens
7240 // on this network. We might have been called by rematchNetworkAndRequests when a
7241 // network changed foreground state.
Chalard Jeanb9c02722019-12-09 11:50:38 +09007242 processListenRequests(nai);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007243 } else {
7244 // If the requestable capabilities have changed or the score changed, we can't have been
7245 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jean60902092019-11-07 18:54:49 +09007246 rematchAllNetworksAndRequests();
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007247 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07007248 }
Lorenzo Colitti246d1762021-01-11 22:27:57 +09007249 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007250
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007251 final boolean oldMetered = prevNc.isMetered();
7252 final boolean newMetered = newNc.isMetered();
7253 final boolean meteredChanged = oldMetered != newMetered;
junyulai5ab727b2018-08-07 19:50:45 +08007254
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007255 if (meteredChanged) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00007256 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7257 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007258 }
junyulai5ab727b2018-08-07 19:50:45 +08007259
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007260 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7261 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai5ab727b2018-08-07 19:50:45 +08007262
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007263 // Report changes that are interesting for network statistics tracking.
7264 if (meteredChanged || roamingChanged) {
7265 notifyIfacesChangedForNetworkStats();
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007266 }
7267
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007268 // This network might have been underlying another network. Propagate its capabilities.
7269 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce2e6b79f2020-02-20 14:28:31 +08007270
7271 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayev284cb872020-12-07 22:43:07 -08007272 mDnsManager.updateTransportsForNetwork(
7273 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce2e6b79f2020-02-20 14:28:31 +08007274 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007275 }
7276
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09007277 /** Convenience method to update the capabilities for a given network. */
7278 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7279 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7280 }
7281
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007282 /**
7283 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7284 * network.
7285 *
7286 * Ingress interface filtering enforces that all apps under the given network can only receive
7287 * packets from the network's interface (and loopback). This is important for VPNs because
7288 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7289 * non-VPN interfaces.
7290 *
7291 * As a result, this method should return true iff
7292 * 1. the network is an app VPN (not legacy VPN)
7293 * 2. the VPN does not allow bypass
7294 * 3. the VPN is fully-routed
7295 * 4. the VPN interface is non-null
7296 *
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09007297 * @see INetd#firewallAddUidInterfaceRules
7298 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007299 */
7300 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7301 LinkProperties lp) {
7302 if (nc == null || lp == null) return false;
7303 return nai.isVPN()
Lorenzo Colitticf595362020-01-12 22:28:37 +09007304 && !nai.networkAgentConfig.allowBypass
Qingxi Libb3347b2020-01-17 17:54:27 -08007305 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007306 && lp.getInterfaceName() != null
lucaslin62bc2b02020-11-02 16:05:02 +08007307 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7308 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007309 }
7310
Chiachang Wang1f50ae52020-12-10 22:24:47 +08007311 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7312 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7313 int index = 0;
7314 for (UidRange range : ranges) {
7315 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7316 index++;
7317 }
7318 return stableRanges;
7319 }
7320
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09007321 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7322 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7323 for (int i = 0; i < ranges.length; i++) {
7324 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7325 }
7326 return stableRanges;
7327 }
7328
Ken Chenb8e4bc92020-12-24 12:59:10 +08007329 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7330 int[] exemptUids) {
7331 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7332 try {
7333 mNetd.socketDestroy(ranges, exemptUids);
7334 } catch (Exception e) {
7335 loge("Exception in socket destroy: ", e);
7336 }
7337 }
7338 }
7339
7340 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7341 int[] exemptUids = new int[2];
7342 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7343 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7344 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7345 exemptUids[0] = VPN_UID;
7346 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7347 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7348
7349 maybeCloseSockets(nai, ranges, exemptUids);
7350 try {
7351 if (add) {
7352 mNetd.networkAddUidRanges(nai.network.netId, ranges);
7353 } else {
7354 mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
7355 }
7356 } catch (Exception e) {
7357 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7358 " on netId " + nai.network.netId + ". " + e);
7359 }
7360 maybeCloseSockets(nai, ranges, exemptUids);
7361 }
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09007362
Chalard Jeana39c91c2018-01-16 18:43:05 +09007363 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7364 NetworkCapabilities newNc) {
Chiachang Wangd5034c72021-02-22 18:36:38 +08007365 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7366 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeana39c91c2018-01-16 18:43:05 +09007367 if (null == prevRanges) prevRanges = new ArraySet<>();
7368 if (null == newRanges) newRanges = new ArraySet<>();
7369 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7370
7371 prevRanges.removeAll(newRanges);
7372 newRanges.removeAll(prevRangesCopy);
7373
7374 try {
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007375 // When updating the VPN uid routing rules, add the new range first then remove the old
7376 // range. If old range were removed first, there would be a window between the old
7377 // range being removed and the new range being added, during which UIDs contained
7378 // in both ranges are not subject to any VPN routing rules. Adding new range before
7379 // removing old range works because, unlike the filtering rules below, it's possible to
7380 // add duplicate UID routing rules.
Ken Chenb8e4bc92020-12-24 12:59:10 +08007381 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7382 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7383 // [1-5] & [1-2],[4-5] == [3]
7384 // Then we can do:
7385 // maybeCloseSockets([3])
7386 // mNetd.networkAddUidRanges([1-2],[4-5])
7387 // mNetd.networkRemoveUidRanges([1-5])
7388 // maybeCloseSockets([3])
7389 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7390 // number of binder calls from 6 to 4.
Chalard Jeana39c91c2018-01-16 18:43:05 +09007391 if (!newRanges.isEmpty()) {
Ken Chenb8e4bc92020-12-24 12:59:10 +08007392 updateUidRanges(true, nai, newRanges);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007393 }
7394 if (!prevRanges.isEmpty()) {
Ken Chenb8e4bc92020-12-24 12:59:10 +08007395 updateUidRanges(false, nai, prevRanges);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007396 }
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007397 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7398 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7399 final String iface = nai.linkProperties.getInterfaceName();
7400 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jean7f06b342020-05-20 16:11:50 +09007401 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007402 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7403 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7404 // were added first and then newRanges got removed later, there would be only one uid
7405 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7406 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7407 // Note that this is in contrast with the (more robust) update of VPN routing rules
7408 // above, where the addition of new ranges happens before the removal of old ranges.
7409 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7410 // to be removed will never overlap with the new range to be added.
7411 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb3347b2020-01-17 17:54:27 -08007412 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007413 }
7414 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb3347b2020-01-17 17:54:27 -08007415 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007416 }
Chalard Jeana39c91c2018-01-16 18:43:05 +09007417 } catch (Exception e) {
7418 // Never crash!
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007419 loge("Exception in updateUids: ", e);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007420 }
7421 }
7422
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007423 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti7ec341a2019-02-20 21:34:01 +09007424 ensureRunningOnConnectivityServiceThread();
7425
Serik Beketayev284cb872020-12-07 22:43:07 -08007426 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007427 // Ignore updates for disconnected networks
7428 return;
7429 }
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09007430 if (VDBG || DDBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007431 log("Update of LinkProperties for " + nai.toShortString()
7432 + "; created=" + nai.created
7433 + "; everConnected=" + nai.everConnected);
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007434 }
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09007435 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7436 // modify its oldLp parameter.
lucaslin34cd3942018-11-28 12:51:55 +08007437 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007438 }
7439
Jeremy Joslin94c30992014-11-05 10:32:09 -08007440 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7441 int notificationType) {
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007442 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08007443 Intent intent = new Intent();
Jeremy Joslin362093e2014-11-26 14:24:15 -08007444 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattis622428c2020-12-02 14:12:41 -08007445 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7446 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7447 // such an API is ever implemented, there is no doubt the right request to send in
7448 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7449 // be sent as a separate extra.
7450 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007451 nri.mPendingIntentSent = true;
Jeremy Joslin94c30992014-11-05 10:32:09 -08007452 sendIntent(nri.mPendingIntent, intent);
7453 }
7454 // else not handled
7455 }
7456
7457 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7458 mPendingIntentWakeLock.acquire();
7459 try {
7460 if (DBG) log("Sending " + pendingIntent);
7461 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7462 } catch (PendingIntent.CanceledException e) {
7463 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7464 mPendingIntentWakeLock.release();
7465 releasePendingNetworkRequest(pendingIntent);
7466 }
7467 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7468 }
7469
7470 @Override
7471 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7472 String resultData, Bundle resultExtras) {
7473 if (DBG) log("Finished sending " + pendingIntent);
7474 mPendingIntentWakeLock.release();
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007475 // Release with a delay so the receiving client has an opportunity to put in its
7476 // own request.
7477 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08007478 }
7479
James Mattis757e0e82020-12-03 19:57:41 -08007480 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7481 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7482 final int arg1) {
James Mattis6e6fabf2021-01-10 14:24:24 -08007483 if (nri.mMessenger == null) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08007484 // Default request has no msgr. Also prevents callbacks from being invoked for
7485 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7486 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7487 return;
Hugo Benichi4802c802017-03-23 22:40:44 +09007488 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007489 Bundle bundle = new Bundle();
James Mattis757e0e82020-12-03 19:57:41 -08007490 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichi4802c802017-03-23 22:40:44 +09007491 // TODO: check if defensive copies of data is needed.
James Mattise494cbb2021-02-09 18:18:28 -08007492 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis757e0e82020-12-03 19:57:41 -08007493 putParcelable(bundle, nrForCallback);
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007494 Message msg = Message.obtain();
Hugo Benichi4802c802017-03-23 22:40:44 +09007495 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7496 putParcelable(bundle, networkAgent.network);
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007497 }
Roshan Pius7992afd2020-12-22 15:10:42 -08007498 final boolean includeLocationSensitiveInfo =
7499 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007500 switch (notificationType) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09007501 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Libf6bf082020-01-08 12:51:49 -08007502 final NetworkCapabilities nc =
7503 networkCapabilitiesRestrictedForCallerPermissions(
7504 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7505 putParcelable(
7506 bundle,
Roshan Pius423fff62020-12-28 09:01:49 -08007507 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius332e7a22021-03-21 17:55:29 +00007508 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius7992afd2020-12-22 15:10:42 -08007509 nrForCallback.getRequestorPackageName(),
Roshan Piusc97d8062020-12-17 14:53:09 -08007510 nri.mCallingAttributionTag));
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09007511 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7512 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulai5ab727b2018-08-07 19:50:45 +08007513 // For this notification, arg1 contains the blocked status.
7514 msg.arg1 = arg1;
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09007515 break;
7516 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007517 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007518 msg.arg1 = arg1;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007519 break;
7520 }
7521 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanb70f7cc2018-01-26 19:24:40 +09007522 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Libf6bf082020-01-08 12:51:49 -08007523 final NetworkCapabilities netCap =
7524 networkCapabilitiesRestrictedForCallerPermissions(
7525 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7526 putParcelable(
7527 bundle,
Roshan Pius423fff62020-12-28 09:01:49 -08007528 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius332e7a22021-03-21 17:55:29 +00007529 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius7992afd2020-12-22 15:10:42 -08007530 nrForCallback.getRequestorPackageName(),
Roshan Piusc97d8062020-12-17 14:53:09 -08007531 nri.mCallingAttributionTag));
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007532 break;
7533 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007534 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09007535 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7536 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007537 break;
7538 }
junyulai5ab727b2018-08-07 19:50:45 +08007539 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09007540 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulai5ab727b2018-08-07 19:50:45 +08007541 msg.arg1 = arg1;
7542 break;
7543 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007544 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007545 msg.what = notificationType;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007546 msg.setData(bundle);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007547 try {
Robert Greenwalt721f2372014-08-27 14:34:02 -07007548 if (VDBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09007549 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis757e0e82020-12-03 19:57:41 -08007550 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt721f2372014-08-27 14:34:02 -07007551 }
James Mattis6e6fabf2021-01-10 14:24:24 -08007552 nri.mMessenger.send(msg);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007553 } catch (RemoteException e) {
7554 // may occur naturally in the race of binder death.
James Mattis757e0e82020-12-03 19:57:41 -08007555 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007556 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007557 }
7558
Hugo Benichi4802c802017-03-23 22:40:44 +09007559 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7560 bundle.putParcelable(t.getClass().getSimpleName(), t);
7561 }
7562
Paul Jensenab9bdd52014-09-30 15:37:41 -04007563 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09007564 if (nai.numRequestNetworkRequests() != 0) {
7565 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7566 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09007567 // Ignore listening and track default requests.
7568 if (!nr.isRequest()) continue;
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09007569 loge("Dead network still had at least " + nr);
7570 break;
7571 }
Paul Jensenab9bdd52014-09-30 15:37:41 -04007572 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007573 nai.disconnect();
Paul Jensenab9bdd52014-09-30 15:37:41 -04007574 }
7575
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007576 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7577 if (oldNetwork == null) {
7578 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7579 return;
7580 }
Chalard Jean373391b2019-12-10 21:07:02 +09007581 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007582
7583 // If we get here it means that the last linger timeout for this network expired. So there
7584 // must be no other active linger timers, and we must stop lingering.
junyulai2a4f0062021-02-03 20:15:30 +08007585 oldNetwork.clearInactivityState();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007586
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09007587 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007588 // Tear the network down.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007589 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007590 } else {
junyulaif6d98ec2020-12-14 18:41:52 +08007591 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09007592 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007593 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007594 }
7595
James Mattis8af2d602020-12-20 11:09:58 -08007596 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7597 boolean isDefaultChanged = false;
7598 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7599 final NetworkReassignment.RequestReassignment reassignment =
7600 changes.getReassignment(defaultRequestInfo);
7601 if (null == reassignment) {
7602 continue;
7603 }
7604 // reassignment only contains those instances where the satisfying network changed.
7605 isDefaultChanged = true;
7606 // Notify system services of the new default.
7607 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7608 }
Chiachang Wang228b1c32018-09-28 22:42:48 +08007609
James Mattis8af2d602020-12-20 11:09:58 -08007610 if (isDefaultChanged) {
7611 // Hold a wakelock for a short time to help apps in migrating to a new default.
7612 scheduleReleaseNetworkTransitionWakelock();
7613 }
7614 }
7615
7616 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7617 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7618 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7619 if (DBG) {
7620 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7621 }
Chalard Jean337a8032019-12-03 20:45:30 +09007622
James Mattis1238af22020-12-23 16:37:26 -08007623 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7624 if (newDefaultNetwork != null) {
7625 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensen207feb72014-07-14 12:03:33 -04007626 }
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09007627
James Mattis1238af22020-12-23 16:37:26 -08007628 // Set an app level managed default and return since further processing only applies to the
7629 // default network.
7630 if (mDefaultRequest != nri) {
7631 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7632 return;
7633 }
7634
7635 makeDefaultNetwork(newDefaultNetwork);
7636
James Mattis8af2d602020-12-20 11:09:58 -08007637 if (oldDefaultNetwork != null) {
7638 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7639 }
7640 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattis8af2d602020-12-20 11:09:58 -08007641 handleApplyDefaultProxy(null != newDefaultNetwork
7642 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7643 updateTcpBufferSizes(null != newDefaultNetwork
7644 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09007645 notifyIfacesChangedForNetworkStats();
Paul Jensen207feb72014-07-14 12:03:33 -04007646 }
7647
James Mattis1238af22020-12-23 16:37:26 -08007648 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7649 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7650 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7651 try {
7652 if (VDBG) {
7653 log("Setting default network for " + nri
7654 + " using UIDs " + nri.getUids()
7655 + " with old network " + (oldDefaultNetwork != null
7656 ? oldDefaultNetwork.network().getNetId() : "null")
7657 + " and new network " + (newDefaultNetwork != null
7658 ? newDefaultNetwork.network().getNetId() : "null"));
7659 }
7660 if (nri.getUids().isEmpty()) {
7661 throw new IllegalStateException("makeDefaultForApps called without specifying"
7662 + " any applications to set as the default." + nri);
7663 }
7664 if (null != newDefaultNetwork) {
7665 mNetd.networkAddUidRanges(
7666 newDefaultNetwork.network.getNetId(),
7667 toUidRangeStableParcels(nri.getUids()));
7668 }
7669 if (null != oldDefaultNetwork) {
7670 mNetd.networkRemoveUidRanges(
7671 oldDefaultNetwork.network.getNetId(),
7672 toUidRangeStableParcels(nri.getUids()));
7673 }
7674 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09007675 loge("Exception setting app default network", e);
James Mattis1238af22020-12-23 16:37:26 -08007676 }
7677 }
7678
7679 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7680 try {
7681 if (null != newDefaultNetwork) {
7682 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7683 } else {
7684 mNetd.networkClearDefault();
7685 }
7686 } catch (RemoteException | ServiceSpecificException e) {
7687 loge("Exception setting default network :" + e);
7688 }
7689 }
7690
Chalard Jeanb9c02722019-12-09 11:50:38 +09007691 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007692 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007693 processNewlyLostListenRequests(nai);
Chalard Jeanb9c02722019-12-09 11:50:38 +09007694 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007695 processNewlySatisfiedListenRequests(nai);
7696 }
7697
7698 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattis622428c2020-12-02 14:12:41 -08007699 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7700 if (nri.isMultilayerRequest()) {
7701 continue;
7702 }
7703 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007704 if (!nr.isListen()) continue;
7705 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattis622428c2020-12-02 14:12:41 -08007706 nai.removeRequest(nr.requestId);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007707 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7708 }
7709 }
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007710 }
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007711
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007712 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattis622428c2020-12-02 14:12:41 -08007713 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7714 if (nri.isMultilayerRequest()) {
7715 continue;
7716 }
7717 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007718 if (!nr.isListen()) continue;
7719 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7720 nai.addRequest(nr);
Erik Kline81fdc8a2017-02-15 19:59:17 +09007721 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007722 }
7723 }
7724 }
7725
Chalard Jean63cb44d2019-12-02 15:34:05 +09007726 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean63cb44d2019-12-02 15:34:05 +09007727 private static class NetworkReassignment {
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007728 static class RequestReassignment {
James Mattis622428c2020-12-02 14:12:41 -08007729 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jean018dbe42021-03-01 22:16:08 +09007730 @Nullable public final NetworkRequest mOldNetworkRequest;
7731 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007732 @Nullable public final NetworkAgentInfo mOldNetwork;
7733 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattis622428c2020-12-02 14:12:41 -08007734 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jean018dbe42021-03-01 22:16:08 +09007735 @Nullable final NetworkRequest oldNetworkRequest,
7736 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007737 @Nullable final NetworkAgentInfo oldNetwork,
7738 @Nullable final NetworkAgentInfo newNetwork) {
James Mattis622428c2020-12-02 14:12:41 -08007739 mNetworkRequestInfo = networkRequestInfo;
7740 mOldNetworkRequest = oldNetworkRequest;
7741 mNewNetworkRequest = newNetworkRequest;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007742 mOldNetwork = oldNetwork;
7743 mNewNetwork = newNetwork;
7744 }
Chalard Jean373391b2019-12-10 21:07:02 +09007745
7746 public String toString() {
Chalard Jeanad0a6e62021-03-01 22:06:04 +09007747 final NetworkRequest requestToShow = null != mNewNetworkRequest
7748 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7749 return requestToShow.requestId + " : "
Serik Beketayev284cb872020-12-07 22:43:07 -08007750 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7751 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean373391b2019-12-10 21:07:02 +09007752 }
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007753 }
7754
Chalard Jean8049afd2019-12-10 21:25:24 +09007755 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean63cb44d2019-12-02 15:34:05 +09007756
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007757 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean8049afd2019-12-10 21:25:24 +09007758 return mReassignments;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007759 }
7760
7761 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN53e02712021-04-07 19:40:31 +09007762 if (Build.isDebuggable()) {
Chalard Jean8049afd2019-12-10 21:25:24 +09007763 // The code is never supposed to add two reassignments of the same request. Make
7764 // sure this stays true, but without imposing this expensive check on all
7765 // reassignments on all user devices.
7766 for (final RequestReassignment existing : mReassignments) {
James Mattis622428c2020-12-02 14:12:41 -08007767 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean8049afd2019-12-10 21:25:24 +09007768 throw new IllegalStateException("Trying to reassign ["
7769 + reassignment + "] but already have ["
7770 + existing + "]");
7771 }
7772 }
Chalard Jean69369aa2019-12-03 22:16:26 +09007773 }
Chalard Jean8049afd2019-12-10 21:25:24 +09007774 mReassignments.add(reassignment);
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007775 }
7776
Chalard Jean3952fb12019-12-03 14:43:57 +09007777 // Will return null if this reassignment does not change the network assigned to
Chalard Jean337a8032019-12-03 20:45:30 +09007778 // the passed request.
7779 @Nullable
7780 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean3952fb12019-12-03 14:43:57 +09007781 for (final RequestReassignment event : getRequestReassignments()) {
James Mattis622428c2020-12-02 14:12:41 -08007782 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean3952fb12019-12-03 14:43:57 +09007783 }
7784 return null;
7785 }
Chalard Jean373391b2019-12-10 21:07:02 +09007786
7787 public String toString() {
7788 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7789 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jean88e5b872019-12-11 14:12:30 +09007790 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean373391b2019-12-10 21:07:02 +09007791 for (final RequestReassignment rr : getRequestReassignments()) {
7792 sj.add(rr.toString());
7793 }
7794 return sj.toString();
7795 }
7796
7797 public String debugString() {
7798 final StringBuilder sb = new StringBuilder();
7799 sb.append("NetworkReassignment :");
Chalard Jean88e5b872019-12-11 14:12:30 +09007800 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean373391b2019-12-10 21:07:02 +09007801 for (final RequestReassignment rr : getRequestReassignments()) {
7802 sb.append("\n ").append(rr);
7803 }
7804 return sb.append("\n").toString();
7805 }
Chalard Jean63cb44d2019-12-02 15:34:05 +09007806 }
7807
Chalard Jeanf57b9692019-12-04 13:32:31 +09007808 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean018dbe42021-03-01 22:16:08 +09007809 @Nullable final NetworkRequest previousRequest,
7810 @Nullable final NetworkRequest newRequest,
Chalard Jeanf57b9692019-12-04 13:32:31 +09007811 @Nullable final NetworkAgentInfo previousSatisfier,
7812 @Nullable final NetworkAgentInfo newSatisfier,
7813 final long now) {
James Mattis1238af22020-12-23 16:37:26 -08007814 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean373391b2019-12-10 21:07:02 +09007815 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jean018dbe42021-03-01 22:16:08 +09007816 if (null != previousRequest && null != previousSatisfier) {
Chalard Jeanf57b9692019-12-04 13:32:31 +09007817 if (VDBG || DDBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007818 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jeanf57b9692019-12-04 13:32:31 +09007819 }
James Mattis622428c2020-12-02 14:12:41 -08007820 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jeane634b282021-03-05 23:07:53 +09007821 previousSatisfier.lingerRequest(previousRequest.requestId, now);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007822 } else {
7823 if (VDBG || DDBG) log(" accepting network in place of null");
7824 }
junyulaif6d98ec2020-12-14 18:41:52 +08007825
7826 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7827 // and immediately satisfies a request then remove the timer. This will happen for
7828 // all networks except in the case of an underlying network for a VCN.
7829 if (newSatisfier.isNascent()) {
7830 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai2f4a5b32021-03-26 00:40:48 +08007831 newSatisfier.unsetInactive();
junyulaif6d98ec2020-12-14 18:41:52 +08007832 }
7833
Chalard Jeandc974072021-03-01 22:00:20 +09007834 // if newSatisfier is not null, then newRequest may not be null.
James Mattis622428c2020-12-02 14:12:41 -08007835 newSatisfier.unlingerRequest(newRequest.requestId);
7836 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang11e9a312020-10-30 22:04:25 +08007837 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattis622428c2020-12-02 14:12:41 -08007838 + newRequest);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007839 }
Chalard Jean018dbe42021-03-01 22:16:08 +09007840 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jeanf57b9692019-12-04 13:32:31 +09007841 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007842 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattis622428c2020-12-02 14:12:41 -08007843 + " request " + previousRequest.requestId);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007844 }
James Mattis622428c2020-12-02 14:12:41 -08007845 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007846 }
James Mattis622428c2020-12-02 14:12:41 -08007847 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007848 }
7849
James Mattis622428c2020-12-02 14:12:41 -08007850 /**
7851 * This function is triggered when something can affect what network should satisfy what
7852 * request, and it computes the network reassignment from the passed collection of requests to
7853 * network match to the one that the system should now have. That data is encoded in an
7854 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
7855 * satisfier.
7856 *
7857 * After the reassignment is computed, it is applied to the state objects.
7858 *
7859 * @param networkRequests the nri objects to evaluate for possible network reassignment
7860 * @return NetworkReassignment listing of proposed network assignment changes
7861 */
Chalard Jean42909302019-12-10 18:56:30 +09007862 @NonNull
James Mattis622428c2020-12-02 14:12:41 -08007863 private NetworkReassignment computeNetworkReassignment(
7864 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean013fb142019-12-10 21:08:07 +09007865 final NetworkReassignment changes = new NetworkReassignment();
7866
Chalard Jean3d71e302021-04-07 17:06:19 +09007867 // Gather the list of all relevant agents.
Chalard Jean013fb142019-12-10 21:08:07 +09007868 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007869 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis622428c2020-12-02 14:12:41 -08007870 if (!nai.everConnected) {
7871 continue;
7872 }
Chalard Jean013fb142019-12-10 21:08:07 +09007873 nais.add(nai);
Chalard Jean013fb142019-12-10 21:08:07 +09007874 }
Chalard Jean013fb142019-12-10 21:08:07 +09007875
James Mattis622428c2020-12-02 14:12:41 -08007876 for (final NetworkRequestInfo nri : networkRequests) {
7877 // Non-multilayer listen requests can be ignored.
7878 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
7879 continue;
7880 }
7881 NetworkAgentInfo bestNetwork = null;
7882 NetworkRequest bestRequest = null;
7883 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeanb887f602021-03-29 17:03:59 +09007884 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattis622428c2020-12-02 14:12:41 -08007885 // Stop evaluating as the highest possible priority request is satisfied.
7886 if (null != bestNetwork) {
7887 bestRequest = req;
7888 break;
7889 }
7890 }
James Mattis1238af22020-12-23 16:37:26 -08007891 if (null == bestNetwork && isDefaultBlocked(nri)) {
7892 // Remove default networking if disallowed for managed default requests.
7893 bestNetwork = mNoServiceNetwork;
7894 }
7895 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean58d486c2019-12-10 22:16:53 +09007896 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean013fb142019-12-10 21:08:07 +09007897 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattis622428c2020-12-02 14:12:41 -08007898 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean013fb142019-12-10 21:08:07 +09007899 }
Chalard Jean42909302019-12-10 18:56:30 +09007900 }
7901 return changes;
7902 }
7903
James Mattis622428c2020-12-02 14:12:41 -08007904 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
7905 return new HashSet<>(mNetworkRequests.values());
7906 }
7907
Paul Jensen50f38772015-06-16 14:27:36 -04007908 /**
James Mattis622428c2020-12-02 14:12:41 -08007909 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensen50f38772015-06-16 14:27:36 -04007910 * being disconnected.
Paul Jensen50f38772015-06-16 14:27:36 -04007911 */
Chalard Jean60902092019-11-07 18:54:49 +09007912 private void rematchAllNetworksAndRequests() {
James Mattis622428c2020-12-02 14:12:41 -08007913 rematchNetworksAndRequests(getNrisFromGlobalRequests());
7914 }
7915
7916 /**
7917 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
7918 * being disconnected.
7919 */
7920 private void rematchNetworksAndRequests(
7921 @NonNull final Set<NetworkRequestInfo> networkRequests) {
7922 ensureRunningOnConnectivityServiceThread();
Chalard Jean013fb142019-12-10 21:08:07 +09007923 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007924 final long now = SystemClock.elapsedRealtime();
James Mattis622428c2020-12-02 14:12:41 -08007925 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean373391b2019-12-10 21:07:02 +09007926 if (VDBG || DDBG) {
7927 log(changes.debugString());
7928 } else if (DBG) {
7929 log(changes.toString()); // Shorter form, only one line of log
7930 }
Chalard Jean32c20902019-12-10 22:01:31 +09007931 applyNetworkReassignment(changes, now);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09007932 issueNetworkNeeds();
Chalard Jeand4a4a302019-12-10 19:01:29 +09007933 }
Chalard Jean208f81b2019-12-04 19:55:32 +09007934
Chalard Jeand4a4a302019-12-10 19:01:29 +09007935 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jean32c20902019-12-10 22:01:31 +09007936 final long now) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007937 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jean88e5b872019-12-11 14:12:30 +09007938
7939 // Since most of the time there are only 0 or 1 background networks, it would probably
7940 // be more efficient to just use an ArrayList here. TODO : measure performance
7941 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
7942 for (final NetworkAgentInfo nai : nais) {
7943 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
7944 }
7945
Chalard Jeand4a4a302019-12-10 19:01:29 +09007946 // First, update the lists of satisfied requests in the network agents. This is necessary
7947 // because some code later depends on this state to be correct, most prominently computing
7948 // the linger status.
Chalard Jean208f81b2019-12-04 19:55:32 +09007949 for (final NetworkReassignment.RequestReassignment event :
7950 changes.getRequestReassignments()) {
James Mattis622428c2020-12-02 14:12:41 -08007951 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
7952 event.mOldNetworkRequest, event.mNewNetworkRequest,
7953 event.mOldNetwork, event.mNewNetwork,
7954 now);
Chalard Jeana03df692019-11-07 19:05:18 +09007955 }
Chalard Jeandc623312019-11-07 23:16:12 +09007956
James Mattis8af2d602020-12-20 11:09:58 -08007957 // Process default network changes if applicable.
7958 processDefaultNetworkChanges(changes);
Chalard Jean76b04162019-11-19 19:16:48 +09007959
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007960 // Notify requested networks are available after the default net is switched, but
7961 // before LegacyTypeTracker sends legacy broadcasts
7962 for (final NetworkReassignment.RequestReassignment event :
7963 changes.getRequestReassignments()) {
7964 if (null != event.mNewNetwork) {
James Mattis622428c2020-12-02 14:12:41 -08007965 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jeanc1da9302019-12-03 15:55:14 +09007966 } else {
James Mattis622428c2020-12-02 14:12:41 -08007967 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jeanc1da9302019-12-03 15:55:14 +09007968 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007969 }
7970 }
7971
junyulaif6d98ec2020-12-14 18:41:52 +08007972 // Update the inactivity state before processing listen callbacks, because the background
7973 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean1a1d2782019-12-04 20:01:46 +09007974 // just yet though, because they have to be sent after the listens are processed to keep
7975 // backward compatibility.
junyulaif6d98ec2020-12-14 18:41:52 +08007976 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean41bae5c2019-11-19 20:01:10 +09007977 for (final NetworkAgentInfo nai : nais) {
junyulaif6d98ec2020-12-14 18:41:52 +08007978 // Rematching may have altered the inactivity state of some networks, so update all
7979 // inactivity timers. updateInactivityState reads the state from the network agent
7980 // and does nothing if the state has not changed : the source of truth is controlled
7981 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
7982 // have been called while rematching the individual networks above.
junyulai2a4f0062021-02-03 20:15:30 +08007983 if (updateInactivityState(nai, now)) {
junyulaif6d98ec2020-12-14 18:41:52 +08007984 inactiveNetworks.add(nai);
Chalard Jeand915e362019-12-04 18:49:18 +09007985 }
7986 }
7987
Chalard Jean88e5b872019-12-11 14:12:30 +09007988 for (final NetworkAgentInfo nai : nais) {
7989 if (!nai.everConnected) continue;
7990 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007991 // Process listen requests and update capabilities if the background state has
7992 // changed for this network. For consistency with previous behavior, send onLost
7993 // callbacks before onAvailable.
Chalard Jean88e5b872019-12-11 14:12:30 +09007994 processNewlyLostListenRequests(nai);
7995 if (oldBackground != nai.isBackgroundNetwork()) {
7996 applyBackgroundChangeForRematch(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007997 }
Chalard Jean88e5b872019-12-11 14:12:30 +09007998 processNewlySatisfiedListenRequests(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007999 }
8000
junyulaif6d98ec2020-12-14 18:41:52 +08008001 for (final NetworkAgentInfo nai : inactiveNetworks) {
8002 // For nascent networks, if connecting with no foreground request, skip broadcasting
8003 // LOSING for backward compatibility. This is typical when mobile data connected while
8004 // wifi connected with mobile data always-on enabled.
8005 if (nai.isNascent()) continue;
Chalard Jeand915e362019-12-04 18:49:18 +09008006 notifyNetworkLosing(nai, now);
Chalard Jeandc623312019-11-07 23:16:12 +09008007 }
8008
James Mattis8af2d602020-12-20 11:09:58 -08008009 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jean4005aeb2019-11-19 19:23:38 +09008010
Chalard Jeandc623312019-11-07 23:16:12 +09008011 // Tear down all unneeded networks.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008012 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jeana03df692019-11-07 19:05:18 +09008013 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2a4f0062021-02-03 20:15:30 +08008014 if (nai.getInactivityExpiry() > 0) {
Chalard Jeana03df692019-11-07 19:05:18 +09008015 // This network has active linger timers and no requests, but is not
8016 // lingering. Linger it.
8017 //
8018 // One way (the only way?) this can happen if this network is unvalidated
8019 // and became unneeded due to another network improving its score to the
8020 // point where this network will no longer be able to satisfy any requests
8021 // even if it validates.
junyulai2a4f0062021-02-03 20:15:30 +08008022 if (updateInactivityState(nai, now)) {
Chalard Jeand915e362019-12-04 18:49:18 +09008023 notifyNetworkLosing(nai, now);
8024 }
Chalard Jeana03df692019-11-07 19:05:18 +09008025 } else {
Chalard Jean373391b2019-12-10 21:07:02 +09008026 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jeana03df692019-11-07 19:05:18 +09008027 teardownUnneededNetwork(nai);
8028 }
8029 }
Paul Jensen19d1d362014-09-11 11:00:39 -04008030 }
8031 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008032
Chalard Jeana00029d2019-12-02 18:39:29 +09008033 /**
8034 * Apply a change in background state resulting from rematching networks with requests.
8035 *
8036 * During rematch, a network may change background states by starting to satisfy or stopping
8037 * to satisfy a foreground request. Listens don't count for this. When a network changes
8038 * background states, its capabilities need to be updated and callbacks fired for the
8039 * capability change.
8040 *
8041 * @param nai The network that changed background states
8042 */
8043 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8044 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8045 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8046 updateNetworkPermissions(nai, newNc);
8047 nai.getAndSetNetworkCapabilities(newNc);
8048 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8049 }
8050
Chalard Jean4005aeb2019-11-19 19:23:38 +09008051 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattis8af2d602020-12-20 11:09:58 -08008052 @NonNull final NetworkReassignment changes,
Chalard Jean42909302019-12-10 18:56:30 +09008053 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09008054 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8055 changes.getReassignment(mDefaultRequest);
8056 final NetworkAgentInfo oldDefaultNetwork =
8057 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8058 final NetworkAgentInfo newDefaultNetwork =
8059 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattis8af2d602020-12-20 11:09:58 -08008060
Chalard Jean1bc77a92021-02-04 13:12:59 +09008061 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jean76b04162019-11-19 19:16:48 +09008062 // Maintain the illusion : since the legacy API only understands one network at a time,
8063 // if the default network changed, apps should see a disconnected broadcast for the
8064 // old default network before they see a connected broadcast for the new one.
Chalard Jean1bc77a92021-02-04 13:12:59 +09008065 if (oldDefaultNetwork != null) {
8066 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8067 oldDefaultNetwork, true);
Chalard Jean76b04162019-11-19 19:16:48 +09008068 }
Chalard Jean1bc77a92021-02-04 13:12:59 +09008069 if (newDefaultNetwork != null) {
Chalard Jean76b04162019-11-19 19:16:48 +09008070 // The new default network can be newly null if and only if the old default
8071 // network doesn't satisfy the default request any more because it lost a
8072 // capability.
Chalard Jean1bc77a92021-02-04 13:12:59 +09008073 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattis8af2d602020-12-20 11:09:58 -08008074 mLegacyTypeTracker.add(
Chalard Jean1bc77a92021-02-04 13:12:59 +09008075 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jean76b04162019-11-19 19:16:48 +09008076 }
8077 }
8078
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008079 // Now that all the callbacks have been sent, send the legacy network broadcasts
8080 // as needed. This is necessary so that legacy requests correctly bind dns
8081 // requests to this network. The legacy users are listening for this broadcast
8082 // and will generally do a dns request so they can ensureRouteToHost and if
8083 // they do that before the callbacks happen they'll use the default network.
8084 //
8085 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8086 // callbacks, but if apps can receive the broadcast before the callback, they still might
8087 // have an inconsistent view of networking.
8088 //
8089 // This *does* introduce a race where if the user uses the new api
8090 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8091 // they may get old info. Reverse this after the old startUsing api is removed.
8092 // This is on top of the multiple intent sequencing referenced in the todo above.
8093 for (NetworkAgentInfo nai : nais) {
Chalard Jean88e5b872019-12-11 14:12:30 +09008094 if (nai.everConnected) {
8095 addNetworkToLegacyTypeTracker(nai);
8096 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008097 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008098 }
8099
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008100 private void issueNetworkNeeds() {
8101 ensureRunningOnConnectivityServiceThread();
8102 for (final NetworkOfferInfo noi : mNetworkOffers) {
8103 issueNetworkNeeds(noi);
8104 }
8105 }
8106
8107 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8108 ensureRunningOnConnectivityServiceThread();
8109 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8110 informOffer(nri, noi.offer, mNetworkRanker);
8111 }
8112 }
8113
8114 /**
8115 * Inform a NetworkOffer about any new situation of a request.
8116 *
8117 * This function handles updates to offers. A number of events may happen that require
8118 * updating the registrant for this offer about the situation :
8119 * • The offer itself was updated. This may lead the offer to no longer being able
8120 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8121 * or conversely being strengthened enough to beat the satisfier (and therefore
8122 * start being needed)
8123 * • The network satisfying a request changed (including cases where the request
8124 * starts or stops being satisfied). The new network may be a stronger or weaker
8125 * match than the old one, possibly affecting whether the offer is needed.
8126 * • The network satisfying a request updated their score. This may lead the offer
8127 * to no longer be able to beat it if the current satisfier got better, or
8128 * conversely start being a good choice if the current satisfier got weaker.
8129 *
8130 * @param nri The request
8131 * @param offer The offer. This may be an updated offer.
8132 */
8133 private static void informOffer(@NonNull NetworkRequestInfo nri,
8134 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8135 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8136 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008137
8138 // Multi-layer requests have a currently active request, the one being satisfied.
8139 // Since the system will try to bring up a better network than is currently satisfying
8140 // the request, NetworkProviders need to be told the offers matching the requests *above*
8141 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8142 // not needed, and the offer is needed for the active request iff the offer can beat
8143 // the satisfier.
8144 // For non-multilayer requests, the logic above gracefully degenerates to only the
8145 // last case.
8146 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8147 // providers that the offer is needed for this request, until the active request is found.
8148 // In a second phase, deal with the currently active request. In a third phase, inform
8149 // the providers that offer is unneeded for the remaining requests.
8150
8151 // First phase : inform providers of all requests above the active request.
8152 int i;
8153 for (i = 0; nri.mRequests.size() > i; ++i) {
8154 final NetworkRequest request = nri.mRequests.get(i);
8155 if (activeRequest == request) break; // Found the active request : go to phase 2
8156 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8157 // Since this request is higher-priority than the one currently satisfied, if the
8158 // offer can satisfy it, the provider should try and bring up the network for sure ;
8159 // no need to even ask the ranker – an offer that can satisfy is always better than
8160 // no network. Hence tell the provider so unless it already knew.
8161 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8162 offer.onNetworkNeeded(request);
8163 }
8164 }
8165
8166 // Second phase : deal with the active request (if any)
8167 if (null != activeRequest && activeRequest.isRequest()) {
8168 final boolean oldNeeded = offer.neededFor(activeRequest);
8169 // An offer is needed if it is currently served by this provider or if this offer
8170 // can beat the current satisfier.
8171 final boolean currentlyServing = satisfier != null
8172 && satisfier.factorySerialNumber == offer.providerId;
8173 final boolean newNeeded = (currentlyServing
8174 || (activeRequest.canBeSatisfiedBy(offer.caps)
Chalard Jeanb887f602021-03-29 17:03:59 +09008175 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008176 if (newNeeded != oldNeeded) {
8177 if (newNeeded) {
8178 offer.onNetworkNeeded(activeRequest);
8179 } else {
8180 // The offer used to be able to beat the satisfier. Now it can't.
8181 offer.onNetworkUnneeded(activeRequest);
8182 }
8183 }
8184 }
8185
8186 // Third phase : inform the providers that the offer isn't needed for any request
8187 // below the active one.
8188 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8189 final NetworkRequest request = nri.mRequests.get(i);
8190 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8191 // Since this request is lower-priority than the one currently satisfied, if the
8192 // offer can satisfy it, the provider should not try and bring up the network.
8193 // Hence tell the provider so unless it already knew.
8194 if (offer.neededFor(request)) {
8195 offer.onNetworkUnneeded(request);
8196 }
8197 }
8198 }
8199
Chalard Jean9fdd38a2019-11-07 23:07:32 +09008200 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8201 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8202 NetworkRequest nr = nai.requestAt(i);
8203 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8204 // legacy type tracker filters out repeat adds
8205 mLegacyTypeTracker.add(nr.legacyType, nai);
8206 }
8207 }
8208
8209 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean1bc77a92021-02-04 13:12:59 +09008210 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean9fdd38a2019-11-07 23:07:32 +09008211 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8212 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8213 if (nai.isVPN()) {
8214 mLegacyTypeTracker.add(TYPE_VPN, nai);
8215 }
8216 }
8217
Lorenzo Colittiaf3f8552014-12-17 11:26:49 +09008218 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen5877e732014-09-05 12:06:44 -04008219 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colitti80a0b532014-12-17 11:14:42 +09008220 if (!nai.everValidated) return;
Chalard Jean1bc77a92021-02-04 13:12:59 +09008221 // For now only update icons for the default connection.
Paul Jensen5877e732014-09-05 12:06:44 -04008222 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean1bc77a92021-02-04 13:12:59 +09008223 if (!isDefaultNetwork(nai)) return;
Paul Jensen5877e732014-09-05 12:06:44 -04008224
Lorenzo Colittiaf3f8552014-12-17 11:26:49 +09008225 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen5877e732014-09-05 12:06:44 -04008226 // Don't repeat publish.
8227 if (newInetCondition == mDefaultInetConditionPublished) return;
8228
8229 mDefaultInetConditionPublished = newInetCondition;
8230 sendInetConditionBroadcast(nai.networkInfo);
8231 }
8232
Chalard Jeanfa33a752020-01-14 22:46:36 +09008233 @NonNull
8234 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8235 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanc212ed12020-01-15 00:49:43 +09008236 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeanfa33a752020-01-14 22:46:36 +09008237 final boolean suspended =
8238 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8239 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8240 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8241 // state. This is because the network could have been suspended before connecting,
8242 // or it could be disconnecting while being suspended, and in both these cases
8243 // the state should not be overridden. Note that the only detailed state that
8244 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8245 // worry about multiple different substates of CONNECTED.
8246 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8247 info.getExtraInfo());
Chiachang Wang59f5d112020-02-12 17:01:59 +08008248 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8249 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8250 // network agent is created, then goes to suspended, then goes out of suspended without
8251 // ever setting connected. Check if network agent is ever connected to update the state.
8252 newInfo.setDetailedState(nai.everConnected
8253 ? NetworkInfo.DetailedState.CONNECTED
8254 : NetworkInfo.DetailedState.CONNECTING,
8255 info.getReason(),
8256 info.getExtraInfo());
Chalard Jeanfa33a752020-01-14 22:46:36 +09008257 }
Chalard Jeanc212ed12020-01-15 00:49:43 +09008258 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeanfa33a752020-01-14 22:46:36 +09008259 return newInfo;
8260 }
8261
8262 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8263 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8264
Erik Kline81fdc8a2017-02-15 19:59:17 +09008265 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07008266 NetworkInfo oldInfo = null;
8267 synchronized (networkAgent) {
8268 oldInfo = networkAgent.networkInfo;
8269 networkAgent.networkInfo = newInfo;
8270 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008271
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008272 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09008273 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8274 + oldInfo.getState() + " to " + state);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008275 }
Robert Greenwalt54d534f2014-05-13 21:41:06 -07008276
Robin Leebc024e52016-05-01 23:00:00 +01008277 if (!networkAgent.created
8278 && (state == NetworkInfo.State.CONNECTED
8279 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09008280
8281 // A network that has just connected has zero requests and is thus a foreground network.
8282 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8283
Luke Huang135c5262019-04-09 18:41:49 +08008284 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti01d37632020-12-02 00:48:09 +09008285 if (networkAgent.supportsUnderlyingNetworks()) {
8286 // Initialize the network's capabilities to their starting values according to the
8287 // underlying networks. This ensures that the capabilities are correct before
8288 // anything happens to the network.
8289 updateCapabilitiesForNetwork(networkAgent);
Chalard Jean8c5e4582020-05-07 12:07:03 +09008290 }
Paul Jensen956fa9f2014-08-04 12:21:19 -04008291 networkAgent.created = true;
Chiachang Wang85d72bd2021-03-24 18:39:17 +08008292 networkAgent.onNetworkCreated();
Robin Leebc024e52016-05-01 23:00:00 +01008293 }
8294
8295 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8296 networkAgent.everConnected = true;
8297
lucaslinb2d10842019-04-03 17:09:28 +08008298 // NetworkCapabilities need to be set before sending the private DNS config to
8299 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean8ffefba2019-11-22 22:39:56 +09008300 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8301
Erik Kline076bd3d2018-03-21 07:18:33 -07008302 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin34cd3942018-11-28 12:51:55 +08008303 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8304 null);
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008305
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09008306 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8307 // command must be sent after updating LinkProperties to maximize chances of
8308 // NetworkMonitor seeing the correct LinkProperties when starting.
8309 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colitticf595362020-01-12 22:28:37 +09008310 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti260d9982019-05-31 15:41:29 +09008311 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09008312 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09008313 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VAN3b1d8b42020-05-10 16:11:11 +09008314 new LinkProperties(networkAgent.linkProperties,
8315 true /* parcelSensitiveFields */),
8316 networkAgent.networkCapabilities);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09008317 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008318
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09008319 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8320 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8321 // capabilities, so it only needs to be done once on initial connect, not every time the
8322 // network's capabilities change. Note that we do this before rematching the network,
8323 // so we could decide to tear it down immediately afterwards. That's fine though - on
8324 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8325 // doing.
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09008326 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09008327
junyulaif6d98ec2020-12-14 18:41:52 +08008328 // Before first rematching networks, put an inactivity timer without any request, this
8329 // allows {@code updateInactivityState} to update the state accordingly and prevent
8330 // tearing down for any {@code unneeded} evaluation in this period.
8331 // Note that the timer will not be rescheduled since the expiry time is
8332 // fixed after connection regardless of the network satisfying other requests or not.
8333 // But it will be removed as soon as the network satisfies a request for the first time.
8334 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8335 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai2f4a5b32021-03-26 00:40:48 +08008336 networkAgent.setInactive();
junyulaif6d98ec2020-12-14 18:41:52 +08008337
Paul Jensen19d1d362014-09-11 11:00:39 -04008338 // Consider network even though it is not yet validated.
Chalard Jean60902092019-11-07 18:54:49 +09008339 rematchAllNetworksAndRequests();
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008340
8341 // This has to happen after matching the requests, because callbacks are just requests.
8342 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008343 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008344 networkAgent.disconnect();
Paul Jensena8a49e02014-05-07 15:27:40 -04008345 if (networkAgent.isVPN()) {
Chalard Jeana39c91c2018-01-16 18:43:05 +09008346 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensena8a49e02014-05-07 15:27:40 -04008347 }
Chalard Jeanefaf6532018-05-11 20:19:20 +09008348 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00008349 if (networkAgent.isVPN()) {
8350 // As the active or bound network changes for apps, broadcast the default proxy, as
8351 // apps may need to update their proxy data. This is called after disconnecting from
8352 // VPN to make sure we do not broadcast the old proxy data.
8353 // TODO(b/122649188): send the broadcast only to VPN users.
8354 mProxyTracker.sendProxyBroadcast();
8355 }
Yintang Gu4bb19242019-06-18 14:24:32 +08008356 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8357 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008358 mLegacyTypeTracker.update(networkAgent);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008359 }
8360 }
8361
Chalard Jeandd753522020-12-21 18:36:52 +09008362 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jeande419812020-03-04 17:45:08 +09008363 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8364 nai.setScore(score);
Chalard Jean60902092019-11-07 18:54:49 +09008365 rematchAllNetworksAndRequests();
Robert Greenwaltcf82b832014-05-27 13:20:24 -07008366 }
8367
Erik Kline81fdc8a2017-02-15 19:59:17 +09008368 // Notify only this one new request of the current state. Transfer all the
8369 // current state by calling NetworkCapabilities and LinkProperties callbacks
8370 // so that callers can be guaranteed to have as close to atomicity in state
8371 // transfer as can be supported by this current API.
8372 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen88087222016-10-27 15:05:50 -07008373 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline81fdc8a2017-02-15 19:59:17 +09008374 if (nri.mPendingIntent != null) {
8375 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8376 // Attempt no subsequent state pushes where intents are involved.
8377 return;
Jeremy Joslin94c30992014-11-05 10:32:09 -08008378 }
Erik Kline81fdc8a2017-02-15 19:59:17 +09008379
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008380 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulai5ab727b2018-08-07 19:50:45 +08008381 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008382 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8383 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8384 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulai5ab727b2018-08-07 19:50:45 +08008385 }
8386
Chalard Jeand915e362019-12-04 18:49:18 +09008387 // Notify the requests on this NAI that the network is now lingered.
8388 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2a4f0062021-02-03 20:15:30 +08008389 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jeand915e362019-12-04 18:49:18 +09008390 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8391 }
8392
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008393 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8394 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8395 return vpnBlocked
8396 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8397 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8398 }
8399
8400 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8401 if (blockedReasons == BLOCKED_REASON_NONE) {
8402 mUidBlockedReasons.delete(uid);
8403 } else {
8404 mUidBlockedReasons.put(uid, blockedReasons);
8405 }
8406 }
8407
junyulai5ab727b2018-08-07 19:50:45 +08008408 /**
8409 * Notify of the blocked state apps with a registered callback matching a given NAI.
8410 *
8411 * Unlike other callbacks, blocked status is different between each individual uid. So for
8412 * any given nai, all requests need to be considered according to the uid who filed it.
8413 *
8414 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008415 * @param oldMetered True if the previous network capabilities were metered.
8416 * @param newMetered True if the current network capabilities are metered.
8417 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8418 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulai5ab727b2018-08-07 19:50:45 +08008419 */
8420 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008421 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8422 List<UidRange> newBlockedUidRanges) {
junyulai5ab727b2018-08-07 19:50:45 +08008423
8424 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8425 NetworkRequest nr = nai.requestAt(i);
8426 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008427
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008428 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8429 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8430 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colittif2514122021-03-12 22:50:57 +09008431 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008432 : oldVpnBlocked;
8433
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008434 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8435 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8436 if (oldBlockedState != newBlockedState) {
junyulai5ab727b2018-08-07 19:50:45 +08008437 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008438 newBlockedState);
junyulai5ab727b2018-08-07 19:50:45 +08008439 }
8440 }
8441 }
8442
8443 /**
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008444 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulai5ab727b2018-08-07 19:50:45 +08008445 * @param uid The uid for which the rules changed.
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008446 * @param blockedReasons The reasons for why an uid is blocked.
junyulai5ab727b2018-08-07 19:50:45 +08008447 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008448 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008449 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai5ab727b2018-08-07 19:50:45 +08008450 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008451 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008452
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008453 final int oldBlockedState = getBlockedState(
8454 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8455 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8456 if (oldBlockedState == newBlockedState) {
junyulaiec82da12019-04-08 16:58:22 +08008457 continue;
junyulai5ab727b2018-08-07 19:50:45 +08008458 }
junyulai5ab727b2018-08-07 19:50:45 +08008459 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8460 NetworkRequest nr = nai.requestAt(i);
8461 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colittif2514122021-03-12 22:50:57 +09008462 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008463 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8464 newBlockedState);
junyulai5ab727b2018-08-07 19:50:45 +08008465 }
8466 }
8467 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07008468 }
8469
Chalard Jean8cc4e872019-04-10 23:07:55 +09008470 @VisibleForTesting
8471 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittid55162b2014-07-31 23:20:17 +09008472 // The NetworkInfo we actually send out has no bearing on the real
8473 // state of affairs. For example, if the default connection is mobile,
8474 // and a request for HIPRI has just gone away, we need to pretend that
8475 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8476 // the state to DISCONNECTED, even though the network is of type MOBILE
8477 // and is still connected.
8478 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8479 info.setType(type);
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09008480 filterForLegacyLockdown(info);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008481 if (state != DetailedState.DISCONNECTED) {
8482 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klinee2d50122014-12-08 16:25:20 +09008483 sendConnectedBroadcast(info);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008484 } else {
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008485 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt5a367872014-06-02 15:32:02 -07008486 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8487 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8488 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8489 if (info.isFailover()) {
8490 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8491 nai.networkInfo.setFailover(false);
8492 }
8493 if (info.getReason() != null) {
8494 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8495 }
8496 if (info.getExtraInfo() != null) {
8497 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8498 }
8499 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean1bc77a92021-02-04 13:12:59 +09008500 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattisf61f7be2021-01-31 17:06:19 -08008501 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt5a367872014-06-02 15:32:02 -07008502 if (newDefaultAgent != null) {
8503 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8504 newDefaultAgent.networkInfo);
8505 } else {
8506 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8507 }
8508 }
8509 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8510 mDefaultInetConditionPublished);
Erik Klinee2d50122014-12-08 16:25:20 +09008511 sendStickyBroadcast(intent);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008512 if (newDefaultAgent != null) {
Erik Klinee2d50122014-12-08 16:25:20 +09008513 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008514 }
8515 }
8516 }
8517
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008518 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09008519 if (VDBG || DDBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09008520 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean373391b2019-12-10 21:07:02 +09008521 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09008522 }
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09008523 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8524 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07008525 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8526 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin94c30992014-11-05 10:32:09 -08008527 if (nri.mPendingIntent == null) {
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008528 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin94c30992014-11-05 10:32:09 -08008529 } else {
8530 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8531 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008532 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008533 }
Robert Greenwalt54d534f2014-05-13 21:41:06 -07008534
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008535 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8536 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8537 }
8538
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008539 /**
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008540 * Returns the list of all interfaces that could be used by network traffic that does not
8541 * explicitly specify a network. This includes the default network, but also all VPNs that are
8542 * currently connected.
8543 *
8544 * Must be called on the handler thread.
8545 */
junyulaic9a235a2021-01-26 15:29:15 +08008546 @NonNull
8547 private ArrayList<Network> getDefaultNetworks() {
Varun Anand5e980f42019-02-07 14:13:13 -08008548 ensureRunningOnConnectivityServiceThread();
James Mattis8af2d602020-12-20 11:09:58 -08008549 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattisf61f7be2021-01-31 17:06:19 -08008550 final Set<Integer> activeNetIds = new ArraySet<>();
8551 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8552 if (nri.isBeingSatisfied()) {
8553 activeNetIds.add(nri.getSatisfier().network().netId);
8554 }
8555 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008556 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisf61f7be2021-01-31 17:06:19 -08008557 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008558 defaultNetworks.add(nai.network);
8559 }
8560 }
junyulaic9a235a2021-01-26 15:29:15 +08008561 return defaultNetworks;
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008562 }
8563
8564 /**
Lorenzo Colittif8a48e12019-06-24 13:50:45 +09008565 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8566 * active iface's tracked properties has changed.
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008567 */
Jeff Davidson9804c892016-01-20 11:35:38 -08008568 private void notifyIfacesChangedForNetworkStats() {
Varun Anand5e980f42019-02-07 14:13:13 -08008569 ensureRunningOnConnectivityServiceThread();
8570 String activeIface = null;
8571 LinkProperties activeLinkProperties = getActiveLinkProperties();
8572 if (activeLinkProperties != null) {
8573 activeIface = activeLinkProperties.getInterfaceName();
8574 }
Benedict Wongb98e0692019-06-12 17:46:31 +00008575
junyulai62d35f72021-01-23 09:46:34 +08008576 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008577 try {
junyulai527859f2021-01-22 22:46:01 +08008578 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai92aff0d2021-03-05 14:46:25 +08008579 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulai527859f2021-01-22 22:46:01 +08008580 snapshots.add(snapshot);
8581 }
junyulaic9a235a2021-01-26 15:29:15 +08008582 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8583 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008584 } catch (Exception ignored) {
8585 }
8586 }
8587
Sreeram Ramachandran1892fa52014-07-27 14:18:26 -07008588 @Override
Udam Saini53b71ee2016-01-04 12:16:14 -08008589 public String getCaptivePortalServerUrl() {
paulhud70b7dd2019-08-12 16:25:11 +08008590 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09008591 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09008592 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgren741013d2018-12-07 11:08:04 +01008593
8594 if (!TextUtils.isEmpty(settingUrl)) {
8595 return settingUrl;
8596 }
8597
8598 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08008599 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgren741013d2018-12-07 11:08:04 +01008600 if (!TextUtils.isEmpty(settingUrl)) {
8601 return settingUrl;
8602 }
8603
8604 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Saini53b71ee2016-01-04 12:16:14 -08008605 }
8606
8607 @Override
junyulai9f872232019-01-16 20:23:34 +08008608 public void startNattKeepalive(Network network, int intervalSeconds,
8609 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008610 enforceKeepalivePermission();
8611 mKeepaliveTracker.startNattKeepalive(
junyulai61143782019-03-04 22:45:36 +08008612 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai9f872232019-01-16 20:23:34 +08008613 intervalSeconds, cb,
junyulai21c06d02019-01-03 18:50:15 +08008614 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008615 }
8616
8617 @Override
Chiachang Wang979f46a2021-01-19 15:35:03 +08008618 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai9f872232019-01-16 20:23:34 +08008619 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai48a59382019-01-15 11:32:44 +08008620 String dstAddr) {
Josh Gaobd97cc82020-06-16 15:58:11 -07008621 try {
Chiachang Wang979f46a2021-01-19 15:35:03 +08008622 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gaobd97cc82020-06-16 15:58:11 -07008623 mKeepaliveTracker.startNattKeepalive(
8624 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8625 intervalSeconds, cb,
8626 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8627 } finally {
8628 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8629 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang979f46a2021-01-19 15:35:03 +08008630 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8631 IoUtils.closeQuietly(pfd);
Josh Gaobd97cc82020-06-16 15:58:11 -07008632 }
8633 }
junyulai48a59382019-01-15 11:32:44 +08008634 }
8635
8636 @Override
Chiachang Wang979f46a2021-01-19 15:35:03 +08008637 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai9f872232019-01-16 20:23:34 +08008638 ISocketKeepaliveCallback cb) {
Josh Gaobd97cc82020-06-16 15:58:11 -07008639 try {
8640 enforceKeepalivePermission();
Chiachang Wang979f46a2021-01-19 15:35:03 +08008641 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gaobd97cc82020-06-16 15:58:11 -07008642 mKeepaliveTracker.startTcpKeepalive(
8643 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8644 } finally {
8645 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8646 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang979f46a2021-01-19 15:35:03 +08008647 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8648 IoUtils.closeQuietly(pfd);
Josh Gaobd97cc82020-06-16 15:58:11 -07008649 }
8650 }
junyulaic7ea1242019-01-08 20:04:33 +08008651 }
8652
8653 @Override
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008654 public void stopKeepalive(Network network, int slot) {
8655 mHandler.sendMessage(mHandler.obtainMessage(
junyulai21c06d02019-01-03 18:50:15 +08008656 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008657 }
8658
8659 @Override
Stuart Scottca888bf2015-04-02 18:00:02 -07008660 public void factoryReset() {
paulhud70b7dd2019-08-12 16:25:11 +08008661 enforceSettingsPermission();
Stuart Scott493cca02015-04-20 14:07:45 -07008662
8663 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
8664 return;
8665 }
8666
lucaslin86086772020-12-17 04:14:35 +08008667 final long token = Binder.clearCallingIdentity();
8668 try {
Heemin Seogd5085f32019-06-12 09:21:44 -07008669 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8670 ipMemoryStore.factoryReset();
lucaslin86086772020-12-17 04:14:35 +08008671 } finally {
8672 Binder.restoreCallingIdentity(token);
8673 }
Xiao Ma51410062019-04-10 19:01:52 +09008674
Stuart Scottca888bf2015-04-02 18:00:02 -07008675 // Turn airplane mode off
8676 setAirplaneMode(false);
8677
Xiao Ma00ed6182019-06-12 16:31:14 +09008678 // restore private DNS settings to default mode (opportunistic)
8679 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_PRIVATE_DNS)) {
lucaslin30779882021-04-23 21:03:39 +08008680 ConnectivitySettingsManager.setPrivateDnsMode(mContext, PRIVATE_DNS_MODE_OPPORTUNISTIC);
Xiao Ma00ed6182019-06-12 16:31:14 +09008681 }
8682
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09008683 Settings.Global.putString(mContext.getContentResolver(),
paulhu1510c9c2021-03-17 17:19:09 +08008684 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottca888bf2015-04-02 18:00:02 -07008685 }
Paul Jensen8c23d5f2015-07-01 14:16:32 -04008686
Ricky Waid53cf002018-01-23 04:09:45 +00008687 @Override
8688 public byte[] getNetworkWatchlistConfigHash() {
8689 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8690 if (nwm == null) {
8691 loge("Unable to get NetworkWatchlistManager");
8692 return null;
8693 }
8694 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8695 return nwm.getWatchlistConfigHash();
8696 }
8697
Hugo Benichi3bdc8352016-05-31 16:28:06 +09008698 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiad9dc5b2017-11-11 08:06:43 +09008699 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayev284cb872020-12-07 22:43:07 -08008700 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Kline2e815d32016-04-14 17:30:59 +09008701 }
Hugo Benichi7f919fe2017-04-21 15:07:12 +09008702
8703 private static boolean toBool(int encodedBoolean) {
8704 return encodedBoolean != 0; // Only 0 means false.
8705 }
8706
8707 private static int encodeBool(boolean b) {
8708 return b ? 1 : 0;
8709 }
mswest46c6a5bcf2018-03-12 10:34:34 -07008710
8711 @Override
Chiachang Wang0efaff82020-10-12 15:20:07 +08008712 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8713 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8714 @NonNull String[] args) {
8715 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8716 err.getFileDescriptor(), args);
mswest46c6a5bcf2018-03-12 10:34:34 -07008717 }
8718
Chiachang Wang0efaff82020-10-12 15:20:07 +08008719 private class ShellCmd extends BasicShellCommandHandler {
mswest46c6a5bcf2018-03-12 10:34:34 -07008720 @Override
8721 public int onCommand(String cmd) {
8722 if (cmd == null) {
8723 return handleDefaultCommands(cmd);
8724 }
8725 final PrintWriter pw = getOutPrintWriter();
8726 try {
8727 switch (cmd) {
8728 case "airplane-mode":
8729 final String action = getNextArg();
8730 if ("enable".equals(action)) {
8731 setAirplaneMode(true);
8732 return 0;
8733 } else if ("disable".equals(action)) {
8734 setAirplaneMode(false);
8735 return 0;
8736 } else if (action == null) {
8737 final ContentResolver cr = mContext.getContentResolver();
8738 final int enabled = Settings.Global.getInt(cr,
8739 Settings.Global.AIRPLANE_MODE_ON);
8740 pw.println(enabled == 0 ? "disabled" : "enabled");
8741 return 0;
8742 } else {
8743 onHelp();
8744 return -1;
8745 }
8746 default:
8747 return handleDefaultCommands(cmd);
8748 }
8749 } catch (Exception e) {
8750 pw.println(e);
8751 }
8752 return -1;
8753 }
8754
8755 @Override
8756 public void onHelp() {
8757 PrintWriter pw = getOutPrintWriter();
8758 pw.println("Connectivity service commands:");
8759 pw.println(" help");
8760 pw.println(" Print this help text.");
8761 pw.println(" airplane-mode [enable|disable]");
8762 pw.println(" Turn airplane mode on or off.");
8763 pw.println(" airplane-mode");
8764 pw.println(" Get airplane mode.");
8765 }
8766 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008767
Remi NGUYEN VAN52950ed2021-03-06 00:11:24 +09008768 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittibd015f42021-02-04 00:18:27 +09008769 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8770 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8771 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang2e98f6c2021-04-20 15:41:24 +08008772 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008773 }
8774
8775 /**
8776 * @param connectionInfo the connection to resolve.
8777 * @return {@code uid} if the connection is found and the app has permission to observe it
8778 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8779 * connection is not found.
8780 */
8781 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008782 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8783 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8784 }
8785
Lorenzo Colittidbcd5d62021-02-04 01:47:38 +09008786 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008787 connectionInfo.local, connectionInfo.remote);
8788
Lorenzo Colittibd015f42021-02-04 00:18:27 +09008789 if (uid == INVALID_UID) return uid; // Not found.
8790
8791 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8792 // VPN, if any, that applies to the UID that owns the connection.
8793 if (checkNetworkStackPermission()) return uid;
8794
8795 final NetworkAgentInfo vpn = getVpnForUid(uid);
8796 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colittie0857092021-03-12 22:39:08 +09008797 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008798 return INVALID_UID;
8799 }
8800
8801 return uid;
8802 }
Pavel Grafov23d65702018-12-14 13:51:07 +00008803
Benedict Wong7f6071d2018-11-09 14:45:34 -08008804 /**
8805 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8806 *
8807 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8808 */
8809 @Override
8810 public IBinder startOrGetTestNetworkService() {
8811 synchronized (mTNSLock) {
8812 TestNetworkService.enforceTestNetworkPermissions(mContext);
8813
8814 if (mTNS == null) {
lucaslind5d3dc12021-02-24 13:49:42 +08008815 mTNS = new TestNetworkService(mContext);
Benedict Wong7f6071d2018-11-09 14:45:34 -08008816 }
8817
8818 return mTNS;
8819 }
8820 }
Cody Kesting9c69dd42019-12-17 12:55:28 -08008821
Cody Kesting0ffbf922019-12-18 10:57:50 -08008822 /**
8823 * Handler used for managing all Connectivity Diagnostics related functions.
8824 *
8825 * @see android.net.ConnectivityDiagnosticsManager
8826 *
8827 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8828 */
8829 @VisibleForTesting
8830 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kestinga58c07c2020-01-07 11:18:54 -08008831 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8832
Cody Kesting0ffbf922019-12-18 10:57:50 -08008833 /**
8834 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8835 * android.net.ConnectivityDiagnosticsManager}.
8836 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8837 * NetworkRequestInfo to be registered
8838 */
8839 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8840
8841 /**
8842 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
8843 * android.net.ConnectivityDiagnosticsManager}.
8844 * obj = the IConnectivityDiagnosticsCallback to be unregistered
8845 * arg1 = the uid of the caller
8846 */
8847 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
8848
Cody Kestingd292a332020-01-05 14:06:39 -08008849 /**
8850 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
8851 * after processing {@link #EVENT_NETWORK_TESTED} events.
8852 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
8853 * NetworkMonitor.
8854 * data = PersistableBundle of extras passed from NetworkMonitor.
8855 *
8856 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
8857 */
8858 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
8859
Cody Kesting1d326382020-01-06 16:55:35 -08008860 /**
8861 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
8862 * been detected on the network.
8863 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
8864 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
8865 * arg2 = NetID.
8866 * data = PersistableBundle of extras passed from NetworkMonitor.
8867 */
8868 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
8869
Cody Kestinga58c07c2020-01-07 11:18:54 -08008870 /**
8871 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
8872 * the platform. This event will invoke {@link
8873 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
8874 * callbacks.
8875 * obj = Network that was reported on
8876 * arg1 = boolint for the quality reported
8877 */
8878 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
8879
Cody Kesting0ffbf922019-12-18 10:57:50 -08008880 private ConnectivityDiagnosticsHandler(Looper looper) {
8881 super(looper);
8882 }
8883
8884 @Override
8885 public void handleMessage(Message msg) {
8886 switch (msg.what) {
8887 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8888 handleRegisterConnectivityDiagnosticsCallback(
8889 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
8890 break;
8891 }
8892 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8893 handleUnregisterConnectivityDiagnosticsCallback(
8894 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
8895 break;
8896 }
Cody Kestingd292a332020-01-05 14:06:39 -08008897 case EVENT_NETWORK_TESTED: {
8898 final ConnectivityReportEvent reportEvent =
8899 (ConnectivityReportEvent) msg.obj;
8900
Aaron Huang0d1be642021-01-21 15:47:41 +08008901 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kestingd292a332020-01-05 14:06:39 -08008902 break;
8903 }
Cody Kesting1d326382020-01-06 16:55:35 -08008904 case EVENT_DATA_STALL_SUSPECTED: {
8905 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang0d1be642021-01-21 15:47:41 +08008906 final Pair<Long, PersistableBundle> arg =
8907 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kesting1d326382020-01-06 16:55:35 -08008908 if (nai == null) break;
8909
Aaron Huang0d1be642021-01-21 15:47:41 +08008910 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kesting1d326382020-01-06 16:55:35 -08008911 break;
8912 }
Cody Kestinga58c07c2020-01-07 11:18:54 -08008913 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
8914 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
8915 break;
8916 }
8917 default: {
8918 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
8919 }
Cody Kesting0ffbf922019-12-18 10:57:50 -08008920 }
8921 }
8922 }
8923
8924 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
8925 @VisibleForTesting
8926 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
8927 @NonNull private final IConnectivityDiagnosticsCallback mCb;
8928 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kestingd292a332020-01-05 14:06:39 -08008929 @NonNull private final String mCallingPackageName;
Cody Kesting0ffbf922019-12-18 10:57:50 -08008930
8931 @VisibleForTesting
8932 ConnectivityDiagnosticsCallbackInfo(
Cody Kestingd292a332020-01-05 14:06:39 -08008933 @NonNull IConnectivityDiagnosticsCallback cb,
8934 @NonNull NetworkRequestInfo nri,
8935 @NonNull String callingPackageName) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08008936 mCb = cb;
8937 mRequestInfo = nri;
Cody Kestingd292a332020-01-05 14:06:39 -08008938 mCallingPackageName = callingPackageName;
Cody Kesting0ffbf922019-12-18 10:57:50 -08008939 }
8940
8941 @Override
8942 public void binderDied() {
8943 log("ConnectivityDiagnosticsCallback IBinder died.");
8944 unregisterConnectivityDiagnosticsCallback(mCb);
8945 }
8946 }
8947
Cody Kestingd292a332020-01-05 14:06:39 -08008948 /**
8949 * Class used for sending information from {@link
8950 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
8951 */
8952 private static class NetworkTestedResults {
8953 private final int mNetId;
8954 private final int mTestResult;
8955 private final long mTimestampMillis;
8956 @Nullable private final String mRedirectUrl;
8957
8958 private NetworkTestedResults(
8959 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
8960 mNetId = netId;
8961 mTestResult = testResult;
8962 mTimestampMillis = timestampMillis;
8963 mRedirectUrl = redirectUrl;
8964 }
8965 }
8966
8967 /**
8968 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
8969 * ConnectivityDiagnosticsHandler}.
8970 */
8971 private static class ConnectivityReportEvent {
8972 private final long mTimestampMillis;
8973 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang0d1be642021-01-21 15:47:41 +08008974 private final PersistableBundle mExtras;
Cody Kestingd292a332020-01-05 14:06:39 -08008975
Aaron Huang0d1be642021-01-21 15:47:41 +08008976 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
8977 PersistableBundle p) {
Cody Kestingd292a332020-01-05 14:06:39 -08008978 mTimestampMillis = timestampMillis;
8979 mNai = nai;
Aaron Huang0d1be642021-01-21 15:47:41 +08008980 mExtras = p;
Cody Kestingd292a332020-01-05 14:06:39 -08008981 }
8982 }
8983
Cody Kesting0ffbf922019-12-18 10:57:50 -08008984 private void handleRegisterConnectivityDiagnosticsCallback(
8985 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
8986 ensureRunningOnConnectivityServiceThread();
8987
8988 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting0c55a302020-03-05 10:46:02 -08008989 final IBinder iCb = cb.asBinder();
Cody Kesting0ffbf922019-12-18 10:57:50 -08008990 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
8991
James Mattis65d0d1c2020-11-24 17:40:49 -08008992 // Connectivity Diagnostics are meant to be used with a single network request. It would be
8993 // confusing for these networks to change when an NRI is satisfied in another layer.
8994 if (nri.isMultilayerRequest()) {
8995 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
8996 + "network requests.");
8997 }
8998
Cody Kesting0ffbf922019-12-18 10:57:50 -08008999 // This means that the client registered the same callback multiple times. Do
9000 // not override the previous entry, and exit silently.
Cody Kesting0c55a302020-03-05 10:46:02 -08009001 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08009002 if (VDBG) log("Diagnostics callback is already registered");
9003
9004 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9005 // incremented when the NetworkRequestInfo is created as part of
9006 // enforceRequestCountLimit().
Chalard Jean70b2d9a2021-04-01 16:41:04 +09009007 nri.decrementRequestCount();
Cody Kesting0ffbf922019-12-18 10:57:50 -08009008 return;
9009 }
9010
Cody Kesting0c55a302020-03-05 10:46:02 -08009011 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009012
9013 try {
Cody Kesting0c55a302020-03-05 10:46:02 -08009014 iCb.linkToDeath(cbInfo, 0);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009015 } catch (RemoteException e) {
9016 cbInfo.binderDied();
Cody Kesting905b4752020-02-12 14:50:58 -08009017 return;
9018 }
9019
9020 // Once registered, provide ConnectivityReports for matching Networks
9021 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9022 synchronized (mNetworkForNetId) {
9023 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9024 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis65d0d1c2020-11-24 17:40:49 -08009025 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9026 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kesting905b4752020-02-12 14:50:58 -08009027 matchingNetworks.add(nai);
9028 }
9029 }
9030 }
9031 for (final NetworkAgentInfo nai : matchingNetworks) {
9032 final ConnectivityReport report = nai.getConnectivityReport();
9033 if (report == null) {
9034 continue;
9035 }
9036 if (!checkConnectivityDiagnosticsPermissions(
9037 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9038 continue;
9039 }
9040
9041 try {
9042 cb.onConnectivityReportAvailable(report);
9043 } catch (RemoteException e) {
9044 // Exception while sending the ConnectivityReport. Move on to the next network.
9045 }
Cody Kesting0ffbf922019-12-18 10:57:50 -08009046 }
9047 }
9048
9049 private void handleUnregisterConnectivityDiagnosticsCallback(
9050 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9051 ensureRunningOnConnectivityServiceThread();
Cody Kesting0c55a302020-03-05 10:46:02 -08009052 final IBinder iCb = cb.asBinder();
Cody Kesting0ffbf922019-12-18 10:57:50 -08009053
Cody Kesting970e7792020-03-30 12:43:49 -07009054 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9055 mConnectivityDiagnosticsCallbacks.remove(iCb);
9056 if (cbInfo == null) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08009057 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9058 return;
9059 }
9060
Cody Kesting970e7792020-03-30 12:43:49 -07009061 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting0ffbf922019-12-18 10:57:50 -08009062
Cody Kesting054451e2020-12-02 12:16:56 -08009063 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9064 // (if the Binder died)
9065 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9066 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting0ffbf922019-12-18 10:57:50 -08009067 return;
9068 }
9069
Cody Kestingfc14fbe2020-03-04 13:35:20 -08009070 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9071 // incremented when the NetworkRequestInfo is created as part of
9072 // enforceRequestCountLimit().
Chalard Jean70b2d9a2021-04-01 16:41:04 +09009073 nri.decrementRequestCount();
Cody Kestingfc14fbe2020-03-04 13:35:20 -08009074
Cody Kesting0c55a302020-03-05 10:46:02 -08009075 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009076 }
9077
Cody Kestingd292a332020-01-05 14:06:39 -08009078 private void handleNetworkTestedWithExtras(
9079 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9080 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting2abe6112020-02-11 10:03:26 -08009081 final NetworkCapabilities networkCapabilities =
Cody Kesting70897532020-03-05 22:13:31 -08009082 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingd292a332020-01-05 14:06:39 -08009083 final ConnectivityReport report =
9084 new ConnectivityReport(
9085 reportEvent.mNai.network,
9086 reportEvent.mTimestampMillis,
9087 nai.linkProperties,
Cody Kesting2abe6112020-02-11 10:03:26 -08009088 networkCapabilities,
Cody Kestingd292a332020-01-05 14:06:39 -08009089 extras);
Cody Kesting905b4752020-02-12 14:50:58 -08009090 nai.setConnectivityReport(report);
Cody Kestingd292a332020-01-05 14:06:39 -08009091 final List<IConnectivityDiagnosticsCallback> results =
9092 getMatchingPermissionedCallbacks(nai);
9093 for (final IConnectivityDiagnosticsCallback cb : results) {
9094 try {
Cody Kestinge4d2df52020-03-05 15:19:48 -08009095 cb.onConnectivityReportAvailable(report);
Cody Kestingd292a332020-01-05 14:06:39 -08009096 } catch (RemoteException ex) {
9097 loge("Error invoking onConnectivityReport", ex);
9098 }
9099 }
9100 }
9101
Cody Kesting1d326382020-01-06 16:55:35 -08009102 private void handleDataStallSuspected(
9103 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9104 @NonNull PersistableBundle extras) {
Cody Kesting2abe6112020-02-11 10:03:26 -08009105 final NetworkCapabilities networkCapabilities =
Cody Kesting70897532020-03-05 22:13:31 -08009106 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting1d326382020-01-06 16:55:35 -08009107 final DataStallReport report =
Cody Kesting4a773072020-02-04 21:52:09 -08009108 new DataStallReport(
9109 nai.network,
9110 timestampMillis,
9111 detectionMethod,
9112 nai.linkProperties,
Cody Kesting2abe6112020-02-11 10:03:26 -08009113 networkCapabilities,
Cody Kesting4a773072020-02-04 21:52:09 -08009114 extras);
Cody Kesting1d326382020-01-06 16:55:35 -08009115 final List<IConnectivityDiagnosticsCallback> results =
9116 getMatchingPermissionedCallbacks(nai);
9117 for (final IConnectivityDiagnosticsCallback cb : results) {
9118 try {
9119 cb.onDataStallSuspected(report);
9120 } catch (RemoteException ex) {
9121 loge("Error invoking onDataStallSuspected", ex);
9122 }
9123 }
9124 }
9125
Cody Kestinga58c07c2020-01-07 11:18:54 -08009126 private void handleNetworkConnectivityReported(
9127 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9128 final List<IConnectivityDiagnosticsCallback> results =
9129 getMatchingPermissionedCallbacks(nai);
9130 for (final IConnectivityDiagnosticsCallback cb : results) {
9131 try {
9132 cb.onNetworkConnectivityReported(nai.network, connectivity);
9133 } catch (RemoteException ex) {
9134 loge("Error invoking onNetworkConnectivityReported", ex);
9135 }
9136 }
9137 }
9138
Cody Kesting70897532020-03-05 22:13:31 -08009139 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colittib8756a82021-05-10 00:49:14 +09009140 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9141 NetworkCapabilities.REDACT_ALL);
Cody Kesting70897532020-03-05 22:13:31 -08009142 sanitized.setUids(null);
9143 sanitized.setAdministratorUids(new int[0]);
9144 sanitized.setOwnerUid(Process.INVALID_UID);
9145 return sanitized;
Cody Kesting2abe6112020-02-11 10:03:26 -08009146 }
9147
Cody Kestingd292a332020-01-05 14:06:39 -08009148 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9149 @NonNull NetworkAgentInfo nai) {
9150 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting0c55a302020-03-05 10:46:02 -08009151 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kestingd292a332020-01-05 14:06:39 -08009152 mConnectivityDiagnosticsCallbacks.entrySet()) {
9153 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9154 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
James Mattis65d0d1c2020-11-24 17:40:49 -08009155 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9156 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingd292a332020-01-05 14:06:39 -08009157 if (checkConnectivityDiagnosticsPermissions(
9158 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
Cody Kesting0c55a302020-03-05 10:46:02 -08009159 results.add(entry.getValue().mCb);
Cody Kestingd292a332020-01-05 14:06:39 -08009160 }
9161 }
9162 }
9163 return results;
9164 }
9165
9166 @VisibleForTesting
9167 boolean checkConnectivityDiagnosticsPermissions(
9168 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9169 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9170 return true;
9171 }
9172
Cody Kesting5df8e982020-02-07 14:49:34 -08009173 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9174 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9175 // call in a try-catch.
9176 try {
9177 if (!mLocationPermissionChecker.checkLocationPermission(
9178 callbackPackageName, null /* featureId */, callbackUid, null /* message */)) {
9179 return false;
9180 }
9181 } catch (SecurityException e) {
Cody Kestingd292a332020-01-05 14:06:39 -08009182 return false;
9183 }
9184
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09009185 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colitti82f9a002020-11-16 23:41:21 +09009186 if (virtual.supportsUnderlyingNetworks()
9187 && virtual.networkCapabilities.getOwnerUid() == callbackUid
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09009188 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, nai.network)) {
Lorenzo Colitti82f9a002020-11-16 23:41:21 +09009189 return true;
9190 }
Cody Kestingd292a332020-01-05 14:06:39 -08009191 }
9192
9193 // Administrator UIDs also contains the Owner UID
Cody Kestingc5cadf62020-03-16 18:15:28 -07009194 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09009195 return CollectionUtils.contains(administratorUids, callbackUid);
Cody Kestingd292a332020-01-05 14:06:39 -08009196 }
9197
Cody Kesting9c69dd42019-12-17 12:55:28 -08009198 @Override
9199 public void registerConnectivityDiagnosticsCallback(
Cody Kestingd292a332020-01-05 14:06:39 -08009200 @NonNull IConnectivityDiagnosticsCallback callback,
9201 @NonNull NetworkRequest request,
9202 @NonNull String callingPackageName) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08009203 if (request.legacyType != TYPE_NONE) {
9204 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9205 + " Please use NetworkCapabilities instead.");
9206 }
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009207 final int callingUid = mDeps.getCallingUid();
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08009208 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009209
9210 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9211 // and administrator uids to be safe.
9212 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08009213 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009214
9215 final NetworkRequest requestWithId =
9216 new NetworkRequest(
9217 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9218
9219 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9220 //
9221 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9222 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9223 // callback's binder death.
Lorenzo Colittif2514122021-03-12 22:50:57 +09009224 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009225 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kestingd292a332020-01-05 14:06:39 -08009226 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009227
9228 mConnectivityDiagnosticsHandler.sendMessage(
9229 mConnectivityDiagnosticsHandler.obtainMessage(
9230 ConnectivityDiagnosticsHandler
9231 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9232 cbInfo));
Cody Kesting9c69dd42019-12-17 12:55:28 -08009233 }
9234
9235 @Override
9236 public void unregisterConnectivityDiagnosticsCallback(
9237 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huang6a16a412021-04-09 12:06:42 +08009238 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting0ffbf922019-12-18 10:57:50 -08009239 mConnectivityDiagnosticsHandler.sendMessage(
9240 mConnectivityDiagnosticsHandler.obtainMessage(
9241 ConnectivityDiagnosticsHandler
9242 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009243 mDeps.getCallingUid(),
Cody Kesting0ffbf922019-12-18 10:57:50 -08009244 0,
9245 callback));
Cody Kesting9c69dd42019-12-17 12:55:28 -08009246 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009247
9248 @Override
9249 public void simulateDataStall(int detectionMethod, long timestampMillis,
9250 @NonNull Network network, @NonNull PersistableBundle extras) {
9251 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9252 android.Manifest.permission.NETWORK_STACK);
9253 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9254 if (!nc.hasTransport(TRANSPORT_TEST)) {
9255 throw new SecurityException("Data Stall simluation is only possible for test networks");
9256 }
9257
9258 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009259 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009260 throw new SecurityException("Data Stall simulation is only possible for network "
9261 + "creators");
9262 }
9263
Cody Kesting51691052020-05-21 12:08:21 -07009264 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9265 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9266 // Data Stall information as a DataStallReportParcelable and passing to
9267 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9268 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kesting43a47ef2020-05-15 10:36:01 -07009269 final DataStallReportParcelable p = new DataStallReportParcelable();
9270 p.timestampMillis = timestampMillis;
9271 p.detectionMethod = detectionMethod;
9272
9273 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9274 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9275 }
9276 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9277 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9278 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9279 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9280 }
9281
Serik Beketayev284cb872020-12-07 22:43:07 -08009282 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009283 }
lucaslin6d502ed2021-01-21 02:02:55 +08009284
lucaslindb201da2021-02-23 01:12:55 +08009285 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9286 @Override
lucasline17f3472021-02-25 15:10:29 +08009287 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslindb201da2021-02-23 01:12:55 +08009288 long timestampNs, int uid) {
lucasline17f3472021-02-25 15:10:29 +08009289 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslindb201da2021-02-23 01:12:55 +08009290 }
lucaslin357f5862021-01-21 19:48:09 +08009291
9292 @Override
9293 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucasline17f3472021-02-25 15:10:29 +08009294 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin357f5862021-01-21 19:48:09 +08009295 nai.clatd.interfaceLinkStateChanged(iface, up);
9296 }
9297 }
9298
9299 @Override
9300 public void onInterfaceRemoved(String iface) {
lucasline17f3472021-02-25 15:10:29 +08009301 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin357f5862021-01-21 19:48:09 +08009302 nai.clatd.interfaceRemoved(iface);
9303 }
lucaslindb201da2021-02-23 01:12:55 +08009304 }
9305 }
9306
lucaslin6d502ed2021-01-21 02:02:55 +08009307 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9308
9309 /**
9310 * Class used for updating network activity tracking with netd and notify network activity
9311 * changes.
9312 */
9313 private static final class LegacyNetworkActivityTracker {
lucaslin32028e02021-01-21 02:03:17 +08009314 private static final int NO_UID = -1;
lucaslin6d502ed2021-01-21 02:02:55 +08009315 private final Context mContext;
lucaslina5e9bdb2021-01-21 02:04:15 +08009316 private final INetd mNetd;
lucaslina5e9bdb2021-01-21 02:04:15 +08009317 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9318 new RemoteCallbackList<>();
9319 // Indicate the current system default network activity is active or not.
9320 @GuardedBy("mActiveIdleTimers")
9321 private boolean mNetworkActive;
9322 @GuardedBy("mActiveIdleTimers")
9323 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9324 private final Handler mHandler;
lucaslin6d502ed2021-01-21 02:02:55 +08009325
lucaslina5e9bdb2021-01-21 02:04:15 +08009326 private class IdleTimerParams {
9327 public final int timeout;
9328 public final int transportType;
9329
9330 IdleTimerParams(int timeout, int transport) {
9331 this.timeout = timeout;
9332 this.transportType = transport;
9333 }
9334 }
9335
9336 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslinea5378c2021-02-20 18:59:47 +08009337 @NonNull INetd netd) {
lucaslin6d502ed2021-01-21 02:02:55 +08009338 mContext = context;
lucaslina5e9bdb2021-01-21 02:04:15 +08009339 mNetd = netd;
9340 mHandler = handler;
lucaslin6d502ed2021-01-21 02:02:55 +08009341 }
9342
lucaslindb201da2021-02-23 01:12:55 +08009343 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9344 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9345 synchronized (mActiveIdleTimers) {
9346 mNetworkActive = active;
9347 // If there are no idle timers, it means that system is not monitoring
9348 // activity, so the system default network for those default network
9349 // unspecified apps is always considered active.
9350 //
9351 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9352 // any network activity change event. Whenever this event is received,
9353 // the mActiveIdleTimers should be always not empty. The legacy behavior
9354 // is no-op. Remove to refer to mNetworkActive only.
9355 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9356 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9357 }
9358 }
9359 }
lucaslin6d502ed2021-01-21 02:02:55 +08009360
lucaslina5e9bdb2021-01-21 02:04:15 +08009361 // The network activity should only be updated from ConnectivityService handler thread
9362 // when mActiveIdleTimers lock is held.
9363 @GuardedBy("mActiveIdleTimers")
9364 private void reportNetworkActive() {
9365 final int length = mNetworkActivityListeners.beginBroadcast();
9366 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9367 try {
9368 for (int i = 0; i < length; i++) {
9369 try {
9370 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9371 } catch (RemoteException | RuntimeException e) {
9372 loge("Fail to send network activie to listener " + e);
9373 }
9374 }
9375 } finally {
9376 mNetworkActivityListeners.finishBroadcast();
9377 }
9378 }
9379
9380 @GuardedBy("mActiveIdleTimers")
9381 public void handleReportNetworkActivity() {
9382 synchronized (mActiveIdleTimers) {
9383 reportNetworkActive();
9384 }
9385 }
9386
lucaslin6d502ed2021-01-21 02:02:55 +08009387 // This is deprecated and only to support legacy use cases.
9388 private int transportTypeToLegacyType(int type) {
9389 switch (type) {
9390 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009391 return TYPE_MOBILE;
lucaslin6d502ed2021-01-21 02:02:55 +08009392 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009393 return TYPE_WIFI;
lucaslin6d502ed2021-01-21 02:02:55 +08009394 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009395 return TYPE_BLUETOOTH;
lucaslin6d502ed2021-01-21 02:02:55 +08009396 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009397 return TYPE_ETHERNET;
lucaslin6d502ed2021-01-21 02:02:55 +08009398 default:
9399 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9400 }
9401 return ConnectivityManager.TYPE_NONE;
9402 }
9403
9404 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9405 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9406 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9407 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9408 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9409 final long ident = Binder.clearCallingIdentity();
9410 try {
9411 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9412 RECEIVE_DATA_ACTIVITY_CHANGE,
9413 null /* resultReceiver */,
9414 null /* scheduler */,
9415 0 /* initialCode */,
9416 null /* initialData */,
9417 null /* initialExtra */);
9418 } finally {
9419 Binder.restoreCallingIdentity(ident);
9420 }
9421 }
9422
9423 /**
9424 * Setup data activity tracking for the given network.
9425 *
9426 * Every {@code setupDataActivityTracking} should be paired with a
9427 * {@link #removeDataActivityTracking} for cleanup.
9428 */
9429 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9430 final String iface = networkAgent.linkProperties.getInterfaceName();
9431
9432 final int timeout;
9433 final int type;
9434
9435 if (networkAgent.networkCapabilities.hasTransport(
9436 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9437 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08009438 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin6d502ed2021-01-21 02:02:55 +08009439 10);
9440 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9441 } else if (networkAgent.networkCapabilities.hasTransport(
9442 NetworkCapabilities.TRANSPORT_WIFI)) {
9443 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08009444 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin6d502ed2021-01-21 02:02:55 +08009445 15);
9446 type = NetworkCapabilities.TRANSPORT_WIFI;
9447 } else {
9448 return; // do not track any other networks
9449 }
9450
lucaslin32028e02021-01-21 02:03:17 +08009451 updateRadioPowerState(true /* isActive */, type);
9452
lucaslin6d502ed2021-01-21 02:02:55 +08009453 if (timeout > 0 && iface != null) {
9454 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08009455 synchronized (mActiveIdleTimers) {
9456 // Networks start up.
9457 mNetworkActive = true;
9458 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9459 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9460 reportNetworkActive();
9461 }
lucaslin6d502ed2021-01-21 02:02:55 +08009462 } catch (Exception e) {
9463 // You shall not crash!
9464 loge("Exception in setupDataActivityTracking " + e);
9465 }
9466 }
9467 }
9468
9469 /**
9470 * Remove data activity tracking when network disconnects.
9471 */
9472 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9473 final String iface = networkAgent.linkProperties.getInterfaceName();
9474 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9475
lucaslin32028e02021-01-21 02:03:17 +08009476 if (iface == null) return;
9477
9478 final int type;
9479 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9480 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9481 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9482 type = NetworkCapabilities.TRANSPORT_WIFI;
9483 } else {
9484 return; // do not track any other networks
9485 }
9486
9487 try {
9488 updateRadioPowerState(false /* isActive */, type);
lucaslina5e9bdb2021-01-21 02:04:15 +08009489 synchronized (mActiveIdleTimers) {
9490 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9491 // The call fails silently if no idle timer setup for this interface
9492 mNetd.idletimerRemoveInterface(iface, params.timeout,
9493 Integer.toString(params.transportType));
lucaslin6d502ed2021-01-21 02:02:55 +08009494 }
lucaslin32028e02021-01-21 02:03:17 +08009495 } catch (Exception e) {
9496 // You shall not crash!
9497 loge("Exception in removeDataActivityTracking " + e);
lucaslin6d502ed2021-01-21 02:02:55 +08009498 }
9499 }
9500
9501 /**
9502 * Update data activity tracking when network state is updated.
9503 */
9504 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9505 NetworkAgentInfo oldNetwork) {
9506 if (newNetwork != null) {
9507 setupDataActivityTracking(newNetwork);
9508 }
9509 if (oldNetwork != null) {
9510 removeDataActivityTracking(oldNetwork);
9511 }
9512 }
lucaslin32028e02021-01-21 02:03:17 +08009513
9514 private void updateRadioPowerState(boolean isActive, int transportType) {
9515 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9516 switch (transportType) {
9517 case NetworkCapabilities.TRANSPORT_CELLULAR:
9518 bs.reportMobileRadioPowerState(isActive, NO_UID);
9519 break;
9520 case NetworkCapabilities.TRANSPORT_WIFI:
9521 bs.reportWifiRadioPowerState(isActive, NO_UID);
9522 break;
9523 default:
9524 logw("Untracked transport type:" + transportType);
9525 }
9526 }
lucaslina5e9bdb2021-01-21 02:04:15 +08009527
9528 public boolean isDefaultNetworkActive() {
9529 synchronized (mActiveIdleTimers) {
9530 // If there are no idle timers, it means that system is not monitoring activity,
9531 // so the default network is always considered active.
9532 //
9533 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9534 // tracking is disabled (negative idle timer value configured), or no active default
9535 // network. In the latter case, this reports active but it should report inactive.
9536 return mNetworkActive || mActiveIdleTimers.isEmpty();
9537 }
9538 }
9539
9540 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9541 mNetworkActivityListeners.register(l);
9542 }
9543
9544 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9545 mNetworkActivityListeners.unregister(l);
9546 }
lucaslin3756fcc2021-01-21 02:04:35 +08009547
9548 public void dump(IndentingPrintWriter pw) {
9549 synchronized (mActiveIdleTimers) {
9550 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9551 pw.println("Idle timers:");
9552 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9553 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9554 final IdleTimerParams params = ent.getValue();
9555 pw.print(" timeout="); pw.print(params.timeout);
9556 pw.print(" type="); pw.println(params.transportType);
9557 }
9558 }
9559 }
lucaslin6d502ed2021-01-21 02:02:55 +08009560 }
James Mattised87a672021-01-01 14:13:35 -08009561
Daniel Bright60f02ed2020-06-15 16:10:01 -07009562 /**
9563 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9564 *
9565 * @param socketInfo the socket information
9566 * @param callback the callback to register
9567 */
9568 @Override
9569 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9570 @NonNull final IQosCallback callback) {
9571 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9572 if (nai == null || nai.networkCapabilities == null) {
9573 try {
9574 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9575 } catch (final RemoteException ex) {
9576 loge("registerQosCallbackInternal: RemoteException", ex);
9577 }
9578 return;
9579 }
9580 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9581 }
9582
9583 /**
9584 * Register a {@link IQosCallback} with base {@link QosFilter}.
9585 *
9586 * @param filter the filter to register
9587 * @param callback the callback to register
9588 * @param nai the agent information related to the filter's network
9589 */
9590 @VisibleForTesting
9591 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9592 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9593 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9594 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9595
9596 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9597 enforceConnectivityRestrictedNetworksPermission();
9598 }
9599 mQosCallbackTracker.registerCallback(callback, filter, nai);
9600 }
9601
9602 /**
9603 * Unregisters the given callback.
9604 *
9605 * @param callback the callback to unregister
9606 */
9607 @Override
9608 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huang6a16a412021-04-09 12:06:42 +08009609 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07009610 mQosCallbackTracker.unregisterCallback(callback);
9611 }
James Mattised87a672021-01-01 14:13:35 -08009612
Chalard Jean9d968182021-02-25 21:46:34 +09009613 // Network preference per-profile and OEM network preferences can't be set at the same
9614 // time, because it is unclear what should happen if both preferences are active for
9615 // one given UID. To make it possible, the stack would have to clarify what would happen
9616 // in case both are active at the same time. The implementation may have to be adjusted
9617 // to implement the resulting rules. For example, a priority could be defined between them,
9618 // where the OEM preference would be considered less or more important than the enterprise
9619 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9620 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9621 // are set at the right level. Other solutions are possible, e.g. merging of the
9622 // preferences for the relevant UIDs.
9623 private static void throwConcurrentPreferenceException() {
9624 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9625 + "set OemNetworkPreference at the same time");
James Mattis6e6fabf2021-01-10 14:24:24 -08009626 }
9627
9628 /**
Chalard Jean03433052021-02-25 17:23:40 +09009629 * Request that a user profile is put by default on a network matching a given preference.
9630 *
9631 * See the documentation for the individual preferences for a description of the supported
9632 * behaviors.
9633 *
9634 * @param profile the profile concerned.
9635 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9636 * constants.
9637 * @param listener an optional listener to listen for completion of the operation.
9638 */
9639 @Override
9640 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9641 @ConnectivityManager.ProfileNetworkPreference final int preference,
9642 @Nullable final IOnCompleteListener listener) {
Chalard Jean9d968182021-02-25 21:46:34 +09009643 Objects.requireNonNull(profile);
9644 PermissionUtils.enforceNetworkStackPermission(mContext);
9645 if (DBG) {
9646 log("setProfileNetworkPreference " + profile + " to " + preference);
9647 }
9648 if (profile.getIdentifier() < 0) {
9649 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9650 + "UserHandle.CURRENT not supported)");
9651 }
Chalard Jean0a04bdb2021-04-02 19:24:44 +09009652 final UserManager um = mContext.getSystemService(UserManager.class);
9653 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jean9d968182021-02-25 21:46:34 +09009654 throw new IllegalArgumentException("Profile must be a managed profile");
9655 }
9656 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9657 // handler thread. However it is an immutable object, so reading the reference is
9658 // safe - it's just possible the value is slightly outdated. For the final check,
9659 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9660 // lot easier to understand, so opportunistically check it.
9661 if (!mOemNetworkPreferences.isEmpty()) {
9662 throwConcurrentPreferenceException();
9663 }
9664 final NetworkCapabilities nc;
9665 switch (preference) {
9666 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9667 nc = null;
9668 break;
9669 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9670 final UidRange uids = UidRange.createForUser(profile);
9671 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9672 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9673 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9674 break;
9675 default:
9676 throw new IllegalArgumentException(
9677 "Invalid preference in setProfileNetworkPreference");
9678 }
9679 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9680 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9681 }
9682
9683 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9684 @Nullable final NetworkCapabilities nc) {
9685 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9686 ensureRequestableCapabilities(nc);
9687 }
9688
9689 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9690 @NonNull final ProfileNetworkPreferences prefs) {
9691 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9692 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9693 // The NRI for a user should be comprised of two layers:
9694 // - The request for the capabilities
9695 // - The request for the default network, for fallback. Create an image of it to
9696 // have the correct UIDs in it (also a request can only be part of one NRI, because
9697 // of lookups in 1:1 associations like mNetworkRequests).
9698 // Note that denying a fallback can be implemented simply by not adding the second
9699 // request.
9700 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9701 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
James Mattis6402e582021-04-20 17:26:30 -07009702 nrs.add(createDefaultInternetRequestForTransport(
9703 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Chiachang Wangd5034c72021-02-22 18:36:38 +08009704 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
Lorenzo Colittif2514122021-03-12 22:50:57 +09009705 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
Chalard Jean9d968182021-02-25 21:46:34 +09009706 result.add(nri);
9707 }
9708 return result;
9709 }
9710
9711 private void handleSetProfileNetworkPreference(
9712 @NonNull final ProfileNetworkPreferences.Preference preference,
9713 @Nullable final IOnCompleteListener listener) {
9714 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9715 // particular because it's not clear what preference should win in case both apply
9716 // to the same app.
9717 // The binder call has already checked this, but as mOemNetworkPreferences is only
9718 // touched on the handler thread, it's theoretically not impossible that it has changed
9719 // since.
9720 if (!mOemNetworkPreferences.isEmpty()) {
Chalard Jean6bb468c2021-03-09 21:09:20 +09009721 // This may happen on a device with an OEM preference set when a user is removed.
9722 // In this case, it's safe to ignore. In particular this happens in the tests.
9723 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
Chalard Jean9d968182021-02-25 21:46:34 +09009724 return;
9725 }
9726
9727 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9728
9729 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
James Mattisfff0b7c2021-03-28 17:41:09 -07009730 mSystemNetworkRequestCounter.transact(
9731 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9732 () -> {
9733 final ArraySet<NetworkRequestInfo> nris =
9734 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9735 replaceDefaultNetworkRequestsForPreference(nris);
9736 });
Chalard Jean9d968182021-02-25 21:46:34 +09009737 // Finally, rematch.
9738 rematchAllNetworksAndRequests();
9739
9740 if (null != listener) {
9741 try {
9742 listener.onComplete();
9743 } catch (RemoteException e) {
9744 loge("Listener for setProfileNetworkPreference has died");
9745 }
9746 }
9747 }
9748
James Mattis6e6fabf2021-01-10 14:24:24 -08009749 private void enforceAutomotiveDevice() {
9750 final boolean isAutomotiveDevice =
9751 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9752 if (!isAutomotiveDevice) {
9753 throw new UnsupportedOperationException(
9754 "setOemNetworkPreference() is only available on automotive devices.");
9755 }
9756 }
9757
9758 /**
9759 * Used by automotive devices to set the network preferences used to direct traffic at an
9760 * application level as per the given OemNetworkPreferences. An example use-case would be an
9761 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9762 * vehicle via a particular network.
9763 *
9764 * Calling this will overwrite the existing preference.
9765 *
James Mattis7a253542021-01-26 16:23:52 -08009766 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jeancc9ad152021-03-03 16:37:13 +09009767 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis6e6fabf2021-01-10 14:24:24 -08009768 * to communicate completion of setOemNetworkPreference();
James Mattis6e6fabf2021-01-10 14:24:24 -08009769 */
James Mattised87a672021-01-01 14:13:35 -08009770 @Override
James Mattis6e6fabf2021-01-10 14:24:24 -08009771 public void setOemNetworkPreference(
9772 @NonNull final OemNetworkPreferences preference,
Chalard Jeancc9ad152021-03-03 16:37:13 +09009773 @Nullable final IOnCompleteListener listener) {
James Mattis981865c2021-01-26 14:05:36 -08009774
James Mattis6e6fabf2021-01-10 14:24:24 -08009775 enforceAutomotiveDevice();
James Mattis7a253542021-01-26 16:23:52 -08009776 enforceOemNetworkPreferencesPermission();
James Mattis6e6fabf2021-01-10 14:24:24 -08009777
Chalard Jean9d968182021-02-25 21:46:34 +09009778 if (!mProfileNetworkPreferences.isEmpty()) {
9779 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9780 // handler thread. However it is an immutable object, so reading the reference is
9781 // safe - it's just possible the value is slightly outdated. For the final check,
9782 // see #handleSetOemPreference. But if this can be caught here it is a
9783 // lot easier to understand, so opportunistically check it.
9784 throwConcurrentPreferenceException();
9785 }
9786
James Mattis6e6fabf2021-01-10 14:24:24 -08009787 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9788 validateOemNetworkPreferences(preference);
9789 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9790 new Pair<>(preference, listener)));
9791 }
9792
9793 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9794 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9795 : preference.getNetworkPreferences().values()) {
9796 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9797 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9798 throw new IllegalArgumentException(msg);
9799 }
9800 }
9801 }
9802
9803 private void handleSetOemNetworkPreference(
9804 @NonNull final OemNetworkPreferences preference,
Chalard Jeancc9ad152021-03-03 16:37:13 +09009805 @Nullable final IOnCompleteListener listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08009806 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9807 if (DBG) {
9808 log("set OEM network preferences :" + preference.toString());
9809 }
Chalard Jean9d968182021-02-25 21:46:34 +09009810 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9811 // particular because it's not clear what preference should win in case both apply
9812 // to the same app.
9813 // The binder call has already checked this, but as mOemNetworkPreferences is only
9814 // touched on the handler thread, it's theoretically not impossible that it has changed
9815 // since.
9816 if (!mProfileNetworkPreferences.isEmpty()) {
9817 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9818 return;
9819 }
9820
James Mattis6e4405f2021-04-06 17:07:42 -07009821 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
James Mattisfff0b7c2021-03-28 17:41:09 -07009822 final int uniquePreferenceCount = new ArraySet<>(
9823 preference.getNetworkPreferences().values()).size();
9824 mSystemNetworkRequestCounter.transact(
9825 mDeps.getCallingUid(), uniquePreferenceCount,
9826 () -> {
9827 final ArraySet<NetworkRequestInfo> nris =
9828 new OemNetworkRequestFactory()
9829 .createNrisFromOemNetworkPreferences(preference);
9830 replaceDefaultNetworkRequestsForPreference(nris);
9831 });
James Mattis6e6fabf2021-01-10 14:24:24 -08009832 mOemNetworkPreferences = preference;
James Mattis6e6fabf2021-01-10 14:24:24 -08009833
9834 if (null != listener) {
Chalard Jeandc974072021-03-01 22:00:20 +09009835 try {
9836 listener.onComplete();
9837 } catch (RemoteException e) {
James Mattis3bf8b7a2021-03-01 17:09:11 -08009838 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jeandc974072021-03-01 22:00:20 +09009839 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009840 }
9841 }
9842
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009843 private void replaceDefaultNetworkRequestsForPreference(
James Mattise494cbb2021-02-09 18:18:28 -08009844 @NonNull final Set<NetworkRequestInfo> nris) {
James Mattis15c1b212021-02-20 14:40:51 -08009845 // Pass in a defensive copy as this collection will be updated on remove.
9846 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
James Mattise494cbb2021-02-09 18:18:28 -08009847 addPerAppDefaultNetworkRequests(nris);
James Mattis6e6fabf2021-01-10 14:24:24 -08009848 }
9849
James Mattise494cbb2021-02-09 18:18:28 -08009850 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9851 ensureRunningOnConnectivityServiceThread();
9852 mDefaultNetworkRequests.addAll(nris);
9853 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9854 getPerAppCallbackRequestsToUpdate();
James Mattise494cbb2021-02-09 18:18:28 -08009855 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
James Mattisfff0b7c2021-03-28 17:41:09 -07009856 mSystemNetworkRequestCounter.transact(
9857 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9858 () -> {
9859 nrisToRegister.addAll(
9860 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9861 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9862 handleRegisterNetworkRequests(nrisToRegister);
9863 });
James Mattise494cbb2021-02-09 18:18:28 -08009864 }
9865
9866 /**
9867 * All current requests that are tracking the default network need to be assessed as to whether
9868 * or not the current set of per-application default requests will be changing their default
9869 * network. If so, those requests will need to be updated so that they will send callbacks for
9870 * default network changes at the appropriate time. Additionally, those requests tracking the
9871 * default that were previously updated by this flow will need to be reassessed.
9872 * @return the nris which will need to be updated.
9873 */
9874 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9875 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9876 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9877 // same nri in the map's values for each of its NetworkRequest objects.
9878 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis6e6fabf2021-01-10 14:24:24 -08009879 for (final NetworkRequestInfo nri : nris) {
James Mattise494cbb2021-02-09 18:18:28 -08009880 // Include this nri if it is currently being tracked.
9881 if (isPerAppTrackedNri(nri)) {
9882 defaultCallbackRequests.add(nri);
9883 continue;
9884 }
9885 // We only track callbacks for requests tracking the default.
9886 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9887 continue;
9888 }
9889 // Include this nri if it will be tracked by the new per-app default requests.
9890 final boolean isNriGoingToBeTracked =
Lorenzo Colittif2514122021-03-12 22:50:57 +09009891 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattise494cbb2021-02-09 18:18:28 -08009892 if (isNriGoingToBeTracked) {
9893 defaultCallbackRequests.add(nri);
James Mattis6e6fabf2021-01-10 14:24:24 -08009894 }
9895 }
James Mattise494cbb2021-02-09 18:18:28 -08009896 return defaultCallbackRequests;
James Mattis6e6fabf2021-01-10 14:24:24 -08009897 }
9898
James Mattise494cbb2021-02-09 18:18:28 -08009899 /**
9900 * Create nris for those network requests that are currently tracking the default network that
9901 * are being controlled by a per-application default.
9902 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
9903 * foundation when creating the nri. Important items include the calling uid's original
9904 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
9905 * requests are assumed to have already been validated as needing to be updated.
9906 * @return the Set of nris to use when registering network requests.
9907 */
9908 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
9909 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
9910 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
9911 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
9912 final NetworkRequestInfo trackingNri =
Lorenzo Colittif2514122021-03-12 22:50:57 +09009913 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattise494cbb2021-02-09 18:18:28 -08009914
9915 // If this nri is not being tracked, the change it back to an untracked nri.
9916 if (trackingNri == mDefaultRequest) {
9917 callbackRequestsToRegister.add(new NetworkRequestInfo(
9918 callbackRequest,
9919 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
9920 continue;
9921 }
9922
Lorenzo Colittif2514122021-03-12 22:50:57 +09009923 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattise494cbb2021-02-09 18:18:28 -08009924 callbackRequestsToRegister.add(new NetworkRequestInfo(
9925 callbackRequest,
9926 copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09009927 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colittib199b962021-03-12 22:48:07 +09009928 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattise494cbb2021-02-09 18:18:28 -08009929 }
9930 return callbackRequestsToRegister;
James Mattis6e6fabf2021-01-10 14:24:24 -08009931 }
9932
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009933 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
9934 @NonNull final Set<UidRange> uids) {
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009935 for (final NetworkRequest req : requests) {
Chiachang Wangd5034c72021-02-22 18:36:38 +08009936 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009937 }
9938 }
9939
James Mattis6e6fabf2021-01-10 14:24:24 -08009940 /**
9941 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
9942 */
9943 @VisibleForTesting
9944 final class OemNetworkRequestFactory {
James Mattise494cbb2021-02-09 18:18:28 -08009945 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis6e6fabf2021-01-10 14:24:24 -08009946 @NonNull final OemNetworkPreferences preference) {
James Mattise494cbb2021-02-09 18:18:28 -08009947 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis6e6fabf2021-01-10 14:24:24 -08009948 final SparseArray<Set<Integer>> uids =
9949 createUidsFromOemNetworkPreferences(preference);
9950 for (int i = 0; i < uids.size(); i++) {
9951 final int key = uids.keyAt(i);
9952 final Set<Integer> value = uids.valueAt(i);
9953 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
9954 // No need to add an nri without any requests.
9955 if (0 == nri.mRequests.size()) {
9956 continue;
9957 }
9958 nris.add(nri);
9959 }
9960
9961 return nris;
9962 }
9963
9964 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
9965 @NonNull final OemNetworkPreferences preference) {
9966 final SparseArray<Set<Integer>> uids = new SparseArray<>();
9967 final PackageManager pm = mContext.getPackageManager();
James Mattis3bf8b7a2021-03-01 17:09:11 -08009968 final List<UserHandle> users =
9969 mContext.getSystemService(UserManager.class).getUserHandles(true);
9970 if (null == users || users.size() == 0) {
9971 if (VDBG || DDBG) {
9972 log("No users currently available for setting the OEM network preference.");
9973 }
9974 return uids;
9975 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009976 for (final Map.Entry<String, Integer> entry :
9977 preference.getNetworkPreferences().entrySet()) {
9978 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
9979 try {
9980 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
9981 if (!uids.contains(pref)) {
9982 uids.put(pref, new ArraySet<>());
9983 }
James Mattis3bf8b7a2021-03-01 17:09:11 -08009984 for (final UserHandle ui : users) {
9985 // Add the rules for all users as this policy is device wide.
Chiachang Wang97565cf2021-04-08 11:10:51 +08009986 uids.get(pref).add(ui.getUid(uid));
James Mattis3bf8b7a2021-03-01 17:09:11 -08009987 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009988 } catch (PackageManager.NameNotFoundException e) {
9989 // Although this may seem like an error scenario, it is ok that uninstalled
9990 // packages are sent on a network preference as the system will watch for
9991 // package installations associated with this network preference and update
9992 // accordingly. This is done so as to minimize race conditions on app install.
James Mattis6e6fabf2021-01-10 14:24:24 -08009993 continue;
9994 }
9995 }
9996 return uids;
9997 }
9998
9999 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10000 @OemNetworkPreferences.OemNetworkPreference final int preference,
10001 @NonNull final Set<Integer> uids) {
10002 final List<NetworkRequest> requests = new ArrayList<>();
10003 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10004 switch (preference) {
10005 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10006 requests.add(createUnmeteredNetworkRequest());
10007 requests.add(createOemPaidNetworkRequest());
James Mattis6402e582021-04-20 17:26:30 -070010008 requests.add(createDefaultInternetRequestForTransport(
10009 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis6e6fabf2021-01-10 14:24:24 -080010010 break;
10011 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10012 requests.add(createUnmeteredNetworkRequest());
10013 requests.add(createOemPaidNetworkRequest());
10014 break;
10015 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10016 requests.add(createOemPaidNetworkRequest());
10017 break;
10018 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10019 requests.add(createOemPrivateNetworkRequest());
10020 break;
10021 default:
10022 // This should never happen.
10023 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10024 + " called with invalid preference of " + preference);
10025 }
10026
Chalard Jean9a3a0ea2021-03-01 14:06:28 +090010027 final ArraySet ranges = new ArraySet<Integer>();
10028 for (final int uid : uids) {
10029 ranges.add(new UidRange(uid, uid));
10030 }
10031 setNetworkRequestUids(requests, ranges);
Lorenzo Colittif2514122021-03-12 22:50:57 +090010032 return new NetworkRequestInfo(Process.myUid(), requests);
James Mattis6e6fabf2021-01-10 14:24:24 -080010033 }
10034
10035 private NetworkRequest createUnmeteredNetworkRequest() {
10036 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10037 .addCapability(NET_CAPABILITY_NOT_METERED)
10038 .addCapability(NET_CAPABILITY_VALIDATED);
10039 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10040 }
10041
10042 private NetworkRequest createOemPaidNetworkRequest() {
10043 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10044 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10045 .addCapability(NET_CAPABILITY_OEM_PAID)
10046 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10047 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10048 }
10049
10050 private NetworkRequest createOemPrivateNetworkRequest() {
10051 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10052 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10053 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10054 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10055 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10056 }
10057
10058 private NetworkCapabilities createDefaultPerAppNetCap() {
10059 final NetworkCapabilities netCap = new NetworkCapabilities();
10060 netCap.addCapability(NET_CAPABILITY_INTERNET);
10061 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10062 return netCap;
10063 }
James Mattised87a672021-01-01 14:13:35 -080010064 }
Nathan Harold6179b142018-07-30 13:38:01 -070010065}