blob: c259c170e2c7c735e6fb4807501b20baa353be27 [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;
Aaron Huang9ca37f52021-04-14 01:25:55 +0800108import android.net.ConnectivityAnnotations.RestrictBackgroundStatus;
Cody Kestingd292a332020-01-05 14:06:39 -0800109import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kesting1d326382020-01-06 16:55:35 -0800110import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800111import android.net.ConnectivityManager;
Lorenzo Colitti60104f52021-03-18 00:54:57 +0900112import android.net.ConnectivityManager.BlockedReason;
Roshan Pius7992afd2020-12-22 15:10:42 -0800113import android.net.ConnectivityManager.NetworkCallback;
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);
Remi NGUYEN VAN4806af52021-05-19 12:05:13 +09001504 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001505 }
1506
Erik Kline74d68ef2015-04-30 12:58:40 +09001507 private void registerSettingsCallbacks() {
1508 // Watch for global HTTP proxy changes.
1509 mSettingsObserver.observe(
1510 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1511 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1512
1513 // Watch for whether or not to keep mobile data always on.
1514 mSettingsObserver.observe(
paulhu79260c22021-03-17 20:30:33 +08001515 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001516 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1517
1518 // Watch for whether or not to keep wifi always on.
1519 mSettingsObserver.observe(
paulhu79260c22021-03-17 20:30:33 +08001520 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001521 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Kline74d68ef2015-04-30 12:58:40 +09001522 }
1523
Erik Klinec06d4f92018-01-11 21:07:29 +09001524 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline076bd3d2018-03-21 07:18:33 -07001525 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1526 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinec06d4f92018-01-11 21:07:29 +09001527 }
1528 }
1529
Robert Greenwalt469fa2a2014-05-18 16:22:10 -07001530 private synchronized int nextNetworkRequestId() {
junyulai5ef392c2020-12-14 18:51:02 +08001531 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1532 // doing that.
Robert Greenwalt469fa2a2014-05-18 16:22:10 -07001533 return mNextNetworkRequestId++;
1534 }
1535
junyulaica1fbb62018-06-13 15:00:37 +08001536 @VisibleForTesting
1537 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001538 if (network == null) {
1539 return null;
1540 }
Serik Beketayev284cb872020-12-07 22:43:07 -08001541 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline076bd3d2018-03-21 07:18:33 -07001542 }
1543
1544 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001545 synchronized (mNetworkForNetId) {
Erik Kline076bd3d2018-03-21 07:18:33 -07001546 return mNetworkForNetId.get(netId);
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001547 }
Jeff Sharkeyea403782016-04-22 09:50:16 -06001548 }
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001549
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001550 // TODO: determine what to do when more than one VPN applies to |uid|.
1551 private NetworkAgentInfo getVpnForUid(int uid) {
1552 synchronized (mNetworkForNetId) {
1553 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1554 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1555 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1556 return nai;
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001557 }
1558 }
1559 }
1560 return null;
1561 }
1562
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001563 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09001564 if (mLockdownEnabled) return null;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001565 final NetworkAgentInfo nai = getVpnForUid(uid);
1566 if (nai != null) return nai.declaredUnderlyingNetworks;
1567 return null;
1568 }
1569
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001570 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattisf61f7be2021-01-31 17:06:19 -08001571 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandranaf655d92014-11-11 16:09:21 -08001572
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001573 final Network[] networks = getVpnUnderlyingNetworks(uid);
1574 if (networks != null) {
1575 // getUnderlyingNetworks() returns:
1576 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1577 // empty array => the VPN explicitly said "no default network".
1578 // non-empty array => the VPN specified one or more default networks; we use the
1579 // first one.
1580 if (networks.length > 0) {
1581 nai = getNetworkAgentInfoForNetwork(networks[0]);
1582 } else {
1583 nai = null;
Sreeram Ramachandranaf655d92014-11-11 16:09:21 -08001584 }
1585 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001586 return nai;
Paul Jensen57d231c2014-08-29 09:54:01 -04001587 }
1588
1589 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001590 * Check if UID should be blocked from using the specified network.
Paul Jensen57d231c2014-08-29 09:54:01 -04001591 */
paulhu3b063e32020-12-30 00:42:19 +08001592 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1593 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001594 // Networks aren't blocked when ignoring blocked status
Hugo Benichi0a28d302017-02-11 17:04:43 +09001595 if (ignoreBlocked) {
1596 return false;
1597 }
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001598 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu3b063e32020-12-30 00:42:19 +08001599 final long ident = Binder.clearCallingIdentity();
1600 try {
1601 final boolean metered = nc == null ? true : nc.isMetered();
1602 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1603 } finally {
1604 Binder.restoreCallingIdentity(ident);
1605 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001606 }
1607
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001608 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichi7b3bf372016-07-11 11:05:12 +09001609 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1610 return;
1611 }
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001612 final boolean blocked;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001613 synchronized (mBlockedAppUids) {
1614 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001615 blocked = true;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001616 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001617 blocked = false;
1618 } else {
1619 return;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001620 }
1621 }
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001622 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1623 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1624 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001625 }
1626
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001627 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulai5ab727b2018-08-07 19:50:45 +08001628 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1629 return;
1630 }
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001631 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattis622428c2020-12-02 14:12:41 -08001632 final int requestId = nri.getActiveRequest() != null
1633 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai02025672020-05-29 14:44:42 +08001634 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001635 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankab9c396e2021-04-21 07:23:54 +00001636 Integer.toHexString(blocked)));
junyulai5ab727b2018-08-07 19:50:45 +08001637 }
1638
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001639 /**
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001640 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkeyea403782016-04-22 09:50:16 -06001641 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu3b063e32020-12-30 00:42:19 +08001642 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001643 */
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001644 @NonNull
1645 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1646 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti36567092021-03-03 14:39:04 +09001647 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1648 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1649 // but only exists if an app asks about them or requests them. Ensure the requesting app
1650 // gets the type it asks for.
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001651 filtered.setType(type);
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09001652 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1653 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1654 null /* extraInfo */);
1655 }
1656 filterForLegacyLockdown(filtered);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001657 return filtered;
1658 }
1659
1660 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1661 boolean ignoreBlocked) {
1662 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1663 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001664 }
1665
1666 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001667 * Return NetworkInfo for the active (i.e., connected) network interface.
1668 * It is assumed that at most one network is active at a time. If more
1669 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001670 * @return the info for the active network, or {@code null} if none is
1671 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001673 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001674 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001675 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001676 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001677 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1678 if (nai == null) return null;
1679 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1680 maybeLogBlockedNetworkInfo(networkInfo, uid);
1681 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001682 }
1683
Paul Jensenc2569432015-02-13 14:18:39 -05001684 @Override
1685 public Network getActiveNetwork() {
1686 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001687 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Leeda4d2e22016-03-24 12:07:00 +00001688 }
1689
1690 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001691 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu5e094422021-01-25 18:53:17 +08001692 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001693 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001694 }
1695
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001696 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001697 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1698 if (vpnNai != null) {
1699 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1700 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1701 return vpnNai.network;
Chalard Jeand9605fb2018-04-18 20:18:38 +09001702 }
Paul Jensenc2569432015-02-13 14:18:39 -05001703 }
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001704
James Mattisf61f7be2021-01-31 17:06:19 -08001705 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001706 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1707 ignoreBlocked)) {
1708 return null;
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001709 }
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001710 return nai.network;
Paul Jensenc2569432015-02-13 14:18:39 -05001711 }
1712
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001713 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001714 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu5e094422021-01-25 18:53:17 +08001715 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001716 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1717 if (nai == null) return null;
1718 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001719 }
1720
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001721 /** Returns a NetworkInfo object for a network that doesn't exist. */
1722 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1723 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1724 getNetworkTypeName(networkType), "" /* subtypeName */);
1725 info.setIsAvailable(true);
1726 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1727 // background data is restricted.
1728 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1729 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1730 ? DetailedState.BLOCKED
1731 : DetailedState.DISCONNECTED;
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09001732 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1733 filterForLegacyLockdown(info);
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001734 return info;
1735 }
1736
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001737 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001738 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1739 return null;
1740 }
1741 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001742 if (nai == null) {
1743 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001744 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001745 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1746 false);
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001747 }
1748
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001749 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001750 public NetworkInfo getNetworkInfo(int networkType) {
1751 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001752 final int uid = mDeps.getCallingUid();
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001753 if (getVpnUnderlyingNetworks(uid) != null) {
1754 // A VPN is active, so we may need to return one of its underlying networks. This
1755 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001756 // getNetworkAgentInfoForUid.
1757 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1758 if (nai == null) return null;
1759 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1760 if (networkInfo.getType() == networkType) {
1761 return networkInfo;
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001762 }
1763 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001764 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001765 }
1766
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001767 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001768 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001769 enforceAccessPermission();
Jeff Sharkeyea403782016-04-22 09:50:16 -06001770 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001771 if (nai == null) return null;
1772 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001773 }
1774
1775 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001776 public NetworkInfo[] getAllNetworkInfo() {
1777 enforceAccessPermission();
Serik Beketayeveb7e8c62021-01-15 16:47:25 -08001778 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensene8015422014-09-19 11:14:12 -04001779 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1780 networkType++) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001781 NetworkInfo info = getNetworkInfo(networkType);
1782 if (info != null) {
1783 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001784 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001786 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001787 }
1788
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001789 @Override
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001790 public Network getNetworkForType(int networkType) {
1791 enforceAccessPermission();
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001792 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1793 return null;
1794 }
1795 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1796 if (nai == null) {
1797 return null;
1798 }
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001799 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001800 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1801 return null;
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001802 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001803 return nai.network;
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001804 }
1805
1806 @Override
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001807 public Network[] getAllNetworks() {
1808 enforceAccessPermission();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001809 synchronized (mNetworkForNetId) {
Paul Jensen71299dd2015-04-06 11:54:53 -04001810 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001811 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensen71299dd2015-04-06 11:54:53 -04001812 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001813 }
Paul Jensen71299dd2015-04-06 11:54:53 -04001814 return result;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001815 }
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001816 }
1817
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001818 @Override
Qingxi Libf6bf082020-01-08 12:51:49 -08001819 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001820 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001821 // The basic principle is: if an app's traffic could possibly go over a
1822 // network, without the app doing anything multinetwork-specific,
1823 // (hence, by "default"), then include that network's capabilities in
1824 // the array.
1825 //
1826 // In the normal case, app traffic only goes over the system's default
1827 // network connection, so that's the only network returned.
1828 //
1829 // With a VPN in force, some app traffic may go into the VPN, and thus
1830 // over whatever underlying networks the VPN specifies, while other app
1831 // traffic may go over the system default network (e.g.: a split-tunnel
1832 // VPN, or an app disallowed by the VPN), so the set of networks
1833 // returned includes the VPN's underlying networks and the system
1834 // default.
1835 enforceAccessPermission();
1836
Chalard Jean4ec33bf2018-06-04 13:33:12 +09001837 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001838
James Mattisf61f7be2021-01-31 17:06:19 -08001839 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1840 if (!nri.isBeingSatisfied()) {
1841 continue;
1842 }
1843 final NetworkAgentInfo nai = nri.getSatisfier();
1844 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1845 if (null != nc
1846 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1847 && !result.containsKey(nai.network)) {
1848 result.put(
1849 nai.network,
1850 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08001851 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001852 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1853 callingAttributionTag));
James Mattisf61f7be2021-01-31 17:06:19 -08001854 }
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001855 }
1856
Lorenzo Colitti011f29d2020-12-15 00:49:41 +09001857 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colittie0857092021-03-12 22:39:08 +09001858 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattisf61f7be2021-01-31 17:06:19 -08001859 if (null != networks) {
1860 for (final Network network : networks) {
1861 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1862 if (null != nc) {
Roshan Pius423fff62020-12-28 09:01:49 -08001863 result.put(
1864 network,
1865 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08001866 nc,
1867 false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001868 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08001869 callingAttributionTag));
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001870 }
1871 }
1872 }
1873
1874 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1875 out = result.values().toArray(out);
1876 return out;
1877 }
1878
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001879 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001880 public boolean isNetworkSupported(int networkType) {
1881 enforceAccessPermission();
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001882 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001883 }
1884
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001885 /**
1886 * Return LinkProperties for the active (i.e., connected) default
James Mattisf61f7be2021-01-31 17:06:19 -08001887 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001888 * @return the ip properties for the active network, or {@code null} if
1889 * none is active
1890 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001891 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001892 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001893 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001894 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001895 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1896 if (nai == null) return null;
1897 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001898 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001899 }
1900
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001901 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001902 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001903 enforceAccessPermission();
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001904 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001905 final LinkProperties lp = getLinkProperties(nai);
1906 if (lp == null) return null;
1907 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001908 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001909 }
1910
Robert Greenwalt54d534f2014-05-13 21:41:06 -07001911 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07001912 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001913 public LinkProperties getLinkProperties(Network network) {
1914 enforceAccessPermission();
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001915 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1916 if (lp == null) return null;
1917 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001918 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9a35d82017-04-06 16:01:44 +09001919 }
1920
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001921 @Nullable
1922 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09001923 if (nai == null) {
1924 return null;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001925 }
Hugo Benichie9a35d82017-04-06 16:01:44 +09001926 synchronized (nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001927 return nai.linkProperties;
Hugo Benichie9a35d82017-04-06 16:01:44 +09001928 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001929 }
1930
Qingxi Libf6bf082020-01-08 12:51:49 -08001931 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1932 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1933 }
1934
Lorenzo Colitti98097292015-05-14 17:28:27 +09001935 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001936 if (nai == null) return null;
1937 synchronized (nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001938 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001939 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001940 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001941 }
1942
1943 @Override
Roshan Piusc97d8062020-12-17 14:53:09 -08001944 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1945 @Nullable String callingAttributionTag) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001946 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colitti98097292015-05-14 17:28:27 +09001947 enforceAccessPermission();
Roshan Pius423fff62020-12-28 09:01:49 -08001948 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Libf6bf082020-01-08 12:51:49 -08001949 getNetworkCapabilitiesInternal(network),
Roshan Pius7992afd2020-12-22 15:10:42 -08001950 false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001951 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colitti98097292015-05-14 17:28:27 +09001952 }
1953
Qingxi Libb3347b2020-01-17 17:54:27 -08001954 @VisibleForTesting
1955 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean88953062018-02-21 18:43:54 +09001956 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean058cd312018-04-11 21:09:10 +09001957 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jeand9605fb2018-04-18 20:18:38 +09001958 if (!checkSettingsPermission(callerPid, callerUid)) {
1959 newNc.setUids(null);
1960 newNc.setSSID(null);
1961 }
Etan Cohenc069b062018-12-30 17:59:59 -08001962 if (newNc.getNetworkSpecifier() != null) {
1963 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1964 }
Cody Kestingc5cadf62020-03-16 18:15:28 -07001965 newNc.setAdministratorUids(new int[0]);
Benedict Wong4310e452021-03-24 14:01:51 -07001966 if (!checkAnyPermissionOf(
1967 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai58153cc2021-04-14 23:33:31 +08001968 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong4310e452021-03-24 14:01:51 -07001969 }
Qingxi Libb3347b2020-01-17 17:54:27 -08001970
Chalard Jean058cd312018-04-11 21:09:10 +09001971 return newNc;
Chalard Jeanb70f7cc2018-01-26 19:24:40 +09001972 }
1973
Roshan Pius332e7a22021-03-21 17:55:29 +00001974 /**
1975 * Wrapper used to cache the permission check results performed for the corresponding
1976 * app. This avoid performing multiple permission checks for different fields in
1977 * NetworkCapabilities.
1978 * Note: This wrapper does not support any sort of invalidation and thus must not be
1979 * persistent or long-lived. It may only be used for the time necessary to
1980 * compute the redactions required by one particular NetworkCallback or
1981 * synchronous call.
1982 */
1983 private class RedactionPermissionChecker {
1984 private final int mCallingPid;
1985 private final int mCallingUid;
1986 @NonNull private final String mCallingPackageName;
1987 @Nullable private final String mCallingAttributionTag;
1988
1989 private Boolean mHasLocationPermission = null;
1990 private Boolean mHasLocalMacAddressPermission = null;
1991 private Boolean mHasSettingsPermission = null;
1992
1993 RedactionPermissionChecker(int callingPid, int callingUid,
1994 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
1995 mCallingPid = callingPid;
1996 mCallingUid = callingUid;
1997 mCallingPackageName = callingPackageName;
1998 mCallingAttributionTag = callingAttributionTag;
Roshan Pius423fff62020-12-28 09:01:49 -08001999 }
Roshan Pius332e7a22021-03-21 17:55:29 +00002000
2001 private boolean hasLocationPermissionInternal() {
2002 final long token = Binder.clearCallingIdentity();
2003 try {
2004 return mLocationPermissionChecker.checkLocationPermission(
2005 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2006 null /* message */);
2007 } finally {
2008 Binder.restoreCallingIdentity(token);
2009 }
2010 }
2011
2012 /**
2013 * Returns whether the app holds location permission or not (might return cached result
2014 * if the permission was already checked before).
2015 */
2016 public boolean hasLocationPermission() {
2017 if (mHasLocationPermission == null) {
2018 // If there is no cached result, perform the check now.
2019 mHasLocationPermission = hasLocationPermissionInternal();
2020 }
2021 return mHasLocationPermission;
2022 }
2023
2024 /**
2025 * Returns whether the app holds local mac address permission or not (might return cached
2026 * result if the permission was already checked before).
2027 */
2028 public boolean hasLocalMacAddressPermission() {
2029 if (mHasLocalMacAddressPermission == null) {
2030 // If there is no cached result, perform the check now.
2031 mHasLocalMacAddressPermission =
2032 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2033 }
2034 return mHasLocalMacAddressPermission;
2035 }
2036
2037 /**
2038 * Returns whether the app holds settings permission or not (might return cached
2039 * result if the permission was already checked before).
2040 */
2041 public boolean hasSettingsPermission() {
2042 if (mHasSettingsPermission == null) {
2043 // If there is no cached result, perform the check now.
2044 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2045 }
2046 return mHasSettingsPermission;
2047 }
2048 }
2049
2050 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2051 @NetworkCapabilities.NetCapability long redaction) {
2052 return (redactions & redaction) != 0;
2053 }
2054
2055 /**
2056 * Use the provided |applicableRedactions| to check the receiving app's
2057 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2058 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2059 * before being sent to the corresponding app.
2060 */
2061 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2062 @NetworkCapabilities.RedactionType long applicableRedactions,
2063 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2064 boolean includeLocationSensitiveInfo) {
2065 long redactions = applicableRedactions;
2066 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2067 if (includeLocationSensitiveInfo
2068 && redactionPermissionChecker.hasLocationPermission()) {
2069 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2070 }
2071 }
2072 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2073 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2074 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2075 }
2076 }
2077 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2078 if (redactionPermissionChecker.hasSettingsPermission()) {
2079 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2080 }
2081 }
2082 return redactions;
Roshan Pius423fff62020-12-28 09:01:49 -08002083 }
2084
Qingxi Libf6bf082020-01-08 12:51:49 -08002085 @VisibleForTesting
2086 @Nullable
Roshan Pius423fff62020-12-28 09:01:49 -08002087 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08002088 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius332e7a22021-03-21 17:55:29 +00002089 int callingPid, int callingUid, @NonNull String callingPkgName,
2090 @Nullable String callingAttributionTag) {
Qingxi Libf6bf082020-01-08 12:51:49 -08002091 if (nc == null) {
2092 return null;
2093 }
Roshan Pius423fff62020-12-28 09:01:49 -08002094 // Avoid doing location permission check if the transport info has no location sensitive
2095 // data.
Roshan Pius332e7a22021-03-21 17:55:29 +00002096 final RedactionPermissionChecker redactionPermissionChecker =
2097 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2098 callingAttributionTag);
2099 final long redactions = retrieveRequiredRedactions(
2100 nc.getApplicableRedactions(), redactionPermissionChecker,
2101 includeLocationSensitiveInfo);
2102 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius423fff62020-12-28 09:01:49 -08002103 // Reset owner uid if not destined for the owner app.
Roshan Pius332e7a22021-03-21 17:55:29 +00002104 if (callingUid != nc.getOwnerUid()) {
Qingxi Libf6bf082020-01-08 12:51:49 -08002105 newNc.setOwnerUid(INVALID_UID);
2106 return newNc;
2107 }
Benedict Wonge3bcbc02020-06-08 11:55:38 -07002108 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2109 if (nc.hasTransport(TRANSPORT_VPN)) {
2110 // Owner UIDs already checked above. No need to re-check.
2111 return newNc;
2112 }
Roshan Pius332e7a22021-03-21 17:55:29 +00002113 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2114 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius7992afd2020-12-22 15:10:42 -08002115 // compatibility for older apps.
2116 if (!includeLocationSensitiveInfo
2117 && isTargetSdkAtleast(
Roshan Pius332e7a22021-03-21 17:55:29 +00002118 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius7992afd2020-12-22 15:10:42 -08002119 newNc.setOwnerUid(INVALID_UID);
2120 return newNc;
2121 }
Roshan Pius423fff62020-12-28 09:01:49 -08002122 // Reset owner uid if the app has no location permission.
Roshan Pius332e7a22021-03-21 17:55:29 +00002123 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius423fff62020-12-28 09:01:49 -08002124 newNc.setOwnerUid(INVALID_UID);
2125 }
Qingxi Libf6bf082020-01-08 12:51:49 -08002126 return newNc;
Qingxi Libb3347b2020-01-17 17:54:27 -08002127 }
2128
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09002129 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2130 LinkProperties lp, int callerPid, int callerUid) {
2131 if (lp == null) return new LinkProperties();
2132
2133 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2134 final boolean needsSanitization =
2135 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2136 if (!needsSanitization) {
2137 return new LinkProperties(lp);
2138 }
2139
2140 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VANc3895462020-03-16 14:48:37 +09002141 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09002142 }
2143
2144 final LinkProperties newLp = new LinkProperties(lp);
2145 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2146 // object gets parceled.
2147 newLp.setCaptivePortalApiUrl(null);
2148 newLp.setCaptivePortalData(null);
2149 return newLp;
2150 }
2151
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002152 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2153 int callerUid, String callerPackageName) {
Chalard Jean88953062018-02-21 18:43:54 +09002154 if (!checkSettingsPermission()) {
Lorenzo Colittif2514122021-03-12 22:50:57 +09002155 // There is no need to track the effective UID of the request here. If the caller lacks
2156 // the settings permission, the effective UID is the same as the calling ID.
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002157 nc.setSingleUid(callerUid);
Chalard Jean88953062018-02-21 18:43:54 +09002158 }
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002159 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kestingc5cadf62020-03-16 18:15:28 -07002160 nc.setAdministratorUids(new int[0]);
Qingxi Libb3347b2020-01-17 17:54:27 -08002161
2162 // Clear owner UID; this can never come from an app.
2163 nc.setOwnerUid(INVALID_UID);
Chalard Jean88953062018-02-21 18:43:54 +09002164 }
2165
Chalard Jeana43eede2018-03-20 19:13:57 +09002166 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002167 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jeana43eede2018-03-20 19:13:57 +09002168 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2169 }
2170 }
2171
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09002172 @Override
2173 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2174 enforceAccessPermission();
2175 final int callerUid = Binder.getCallingUid();
2176 final long token = Binder.clearCallingIdentity();
2177 try {
2178 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2179 } finally {
2180 Binder.restoreCallingIdentity(token);
2181 }
2182 }
2183
junyulai57840802021-03-03 12:09:05 +08002184 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colitti98097292015-05-14 17:28:27 +09002185 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002186 public NetworkState[] getAllNetworkState() {
paulhud70b7dd2019-08-12 16:25:11 +08002187 // This contains IMSI details, so make sure the caller is privileged.
paulhu5e094422021-01-25 18:53:17 +08002188 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfe0b08d2014-12-02 18:30:14 -08002189
Serik Beketayeveb7e8c62021-01-15 16:47:25 -08002190 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huang20605e52021-04-17 13:46:25 +08002191 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulai57840802021-03-03 12:09:05 +08002192 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2193 // NetworkAgentInfo.
Aaron Huangc8081e92021-04-20 17:19:46 +08002194 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaidddf2b62020-12-29 19:17:01 +08002195 if (nai != null && nai.networkInfo.isConnected()) {
junyulai57840802021-03-03 12:09:05 +08002196 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangc8081e92021-04-20 17:19:46 +08002197 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2198 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002199 }
2200 }
2201 return result.toArray(new NetworkState[result.size()]);
2202 }
2203
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002204 @Override
junyulai57840802021-03-03 12:09:05 +08002205 @NonNull
Aaron Huang20605e52021-04-17 13:46:25 +08002206 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulai57840802021-03-03 12:09:05 +08002207 // This contains IMSI details, so make sure the caller is privileged.
2208 PermissionUtils.enforceNetworkStackPermission(mContext);
2209
2210 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2211 for (Network network : getAllNetworks()) {
2212 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2213 // TODO: Consider include SUSPENDED networks, which should be considered as
2214 // temporary shortage of connectivity of a connected network.
2215 if (nai != null && nai.networkInfo.isConnected()) {
2216 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2217 // NetworkCapabilities, which may contain UIDs of apps to which the
2218 // network applies. Should the UIDs be cleared so as not to leak or
2219 // interfere ?
2220 result.add(nai.getNetworkStateSnapshot());
2221 }
2222 }
2223 return result;
2224 }
2225
2226 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002227 public boolean isActiveNetworkMetered() {
2228 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002229
Qingxi Libf6bf082020-01-08 12:51:49 -08002230 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkey41a72692017-07-12 10:50:42 -06002231 if (caps != null) {
2232 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2233 } else {
2234 // Always return the most conservative value
2235 return true;
2236 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002237 }
2238
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002239 /**
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002240 * Ensures that the system cannot call a particular method.
2241 */
2242 private boolean disallowedBecauseSystemCaller() {
2243 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admal6d761f92019-04-05 10:06:37 -07002244 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2245 // for devices launched with Q and above. However, existing devices upgrading to Q and
2246 // above must continued to be supported for few more releases.
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002247 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admal6d761f92019-04-05 10:06:37 -07002248 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002249 log("This method exists only for app backwards compatibility"
2250 + " and must not be called by system services.");
2251 return true;
2252 }
2253 return false;
2254 }
2255
2256 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002257 * Ensure that a network route exists to deliver traffic to the specified
2258 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002259 * @param networkType the type of the network over which traffic to the
2260 * specified host is to be routed
2261 * @param hostAddress the IP address of the host to which the route is
2262 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002263 * @return {@code true} on success, {@code false} on failure
2264 */
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09002265 @Override
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002266 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2267 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002268 if (disallowedBecauseSystemCaller()) {
2269 return false;
2270 }
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002271 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002272 if (mProtectedNetworks.contains(networkType)) {
paulhud70b7dd2019-08-12 16:25:11 +08002273 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002274 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002275
Chad Brubaker83ec7fc2014-02-14 13:24:29 -08002276 InetAddress addr;
2277 try {
2278 addr = InetAddress.getByAddress(hostAddress);
2279 } catch (UnknownHostException e) {
2280 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2281 return false;
2282 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002283
The Android Open Source Project28527d22009-03-03 19:31:44 -08002284 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002285 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002286 return false;
2287 }
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002288
2289 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2290 if (nai == null) {
2291 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2292 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2293 } else {
2294 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2295 }
2296 return false;
Ken Mixter7caa36a2013-11-07 22:08:24 -08002297 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002298
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002299 DetailedState netState;
2300 synchronized (nai) {
2301 netState = nai.networkInfo.getDetailedState();
2302 }
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002303
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002304 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002305 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07002306 log("requestRouteToHostAddress on down network "
2307 + "(" + networkType + ") - dropped"
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002308 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002309 }
2310 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002311 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002312
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002313 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002314 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002315 try {
Paul Jensen8b6260f2014-07-11 08:17:29 -04002316 LinkProperties lp;
2317 int netId;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002318 synchronized (nai) {
2319 lp = nai.linkProperties;
Serik Beketayev284cb872020-12-07 22:43:07 -08002320 netId = nai.network.getNetId();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002321 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002322 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colitti7e27c542021-04-10 01:01:43 +09002323 if (DBG) {
2324 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2325 }
Wink Saville690cb182013-06-29 21:10:57 -07002326 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002327 } finally {
2328 Binder.restoreCallingIdentity(token);
2329 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002330 }
2331
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002332 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002333 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002334 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002335 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002336 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002337 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002338 if (bestRoute.getGateway().equals(addr)) {
2339 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08002340 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002341 } else {
2342 // if we will connect to this through another route, add a direct route
2343 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08002344 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002345 }
2346 }
Lorenzo Colittice3a70b2015-09-04 13:12:42 +09002347 if (DBG) log("Adding legacy route " + bestRoute +
2348 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wangfd3fa0a2020-11-06 14:48:30 +08002349
2350 final String dst = bestRoute.getDestinationLinkAddress().toString();
2351 final String nextHop = bestRoute.hasGateway()
2352 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002353 try {
Chiachang Wangfd3fa0a2020-11-06 14:48:30 +08002354 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2355 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002356 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002357 return false;
2358 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002359 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002360 }
2361
paulhu0a2aa802021-01-08 00:51:49 +08002362 class DnsResolverUnsolicitedEventCallback extends
2363 IDnsResolverUnsolicitedEventListener.Stub {
dalykf4977492018-03-05 12:42:22 -05002364 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002365 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalykf4977492018-03-05 12:42:22 -05002366 try {
2367 mHandler.sendMessage(mHandler.obtainMessage(
2368 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu0a2aa802021-01-08 00:51:49 +08002369 new PrivateDnsValidationUpdate(event.netId,
2370 InetAddresses.parseNumericAddress(event.ipAddress),
2371 event.hostname, event.validation)));
dalykf4977492018-03-05 12:42:22 -05002372 } catch (IllegalArgumentException e) {
2373 loge("Error parsing ip address in validation event");
2374 }
2375 }
Chiachang Wangea46de72018-11-27 18:00:05 +08002376
2377 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002378 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2379 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wangea46de72018-11-27 18:00:05 +08002380 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2381 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2382 // event callback for certain nai. e.g. cellular. Register here to pass to
2383 // NetworkMonitor instead.
Remi NGUYEN VAN76b14fd2019-02-04 10:25:11 +09002384 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2385 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2386 // multiple NetworkMonitor registrants.
Chalard Jean1bc77a92021-02-04 13:12:59 +09002387 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu0a2aa802021-01-08 00:51:49 +08002388 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wangea46de72018-11-27 18:00:05 +08002389 }
2390 }
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09002391
2392 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002393 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2394 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2395 event.prefixAddress, event.prefixLength));
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09002396 }
dalykf4977492018-03-05 12:42:22 -05002397
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002398 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002399 public int getInterfaceVersion() {
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002400 return this.VERSION;
2401 }
2402
2403 @Override
2404 public String getInterfaceHash() {
2405 return this.HASH;
2406 }
paulhu0a2aa802021-01-08 00:51:49 +08002407 }
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002408
2409 @VisibleForTesting
paulhu0a2aa802021-01-08 00:51:49 +08002410 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2411 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002412
paulhu0a2aa802021-01-08 00:51:49 +08002413 private void registerDnsResolverUnsolicitedEventListener() {
dalykf4977492018-03-05 12:42:22 -05002414 try {
paulhu0a2aa802021-01-08 00:51:49 +08002415 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalykf4977492018-03-05 12:42:22 -05002416 } catch (Exception e) {
paulhu0a2aa802021-01-08 00:51:49 +08002417 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalykf4977492018-03-05 12:42:22 -05002418 }
2419 }
2420
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002421 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002422 @Override
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002423 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2425 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002426 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002427 };
2428
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002429 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002430 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002431 setUidBlockedReasons(uid, blockedReasons);
junyulai5ab727b2018-08-07 19:50:45 +08002432 }
2433
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002434 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002435 for (String permission : permissions) {
2436 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002437 return true;
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002438 }
2439 }
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002440 return false;
2441 }
2442
paulhua9a6e2a2019-03-22 16:35:06 +08002443 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2444 for (String permission : permissions) {
2445 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2446 return true;
2447 }
2448 }
2449 return false;
2450 }
2451
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002452 private void enforceAnyPermissionOf(String... permissions) {
2453 if (!checkAnyPermissionOf(permissions)) {
2454 throw new SecurityException("Requires one of the following permissions: "
2455 + String.join(", ", permissions) + ".");
2456 }
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002457 }
2458
Paul Jensen57d231c2014-08-29 09:54:01 -04002459 private void enforceInternetPermission() {
2460 mContext.enforceCallingOrSelfPermission(
2461 android.Manifest.permission.INTERNET,
2462 "ConnectivityService");
2463 }
2464
The Android Open Source Project28527d22009-03-03 19:31:44 -08002465 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002466 mContext.enforceCallingOrSelfPermission(
2467 android.Manifest.permission.ACCESS_NETWORK_STATE,
2468 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002469 }
2470
paulhu4418c8e2021-02-22 15:40:43 +08002471 /**
2472 * Performs a strict and comprehensive check of whether a calling package is allowed to
2473 * change the state of network, as the condition differs for pre-M, M+, and
2474 * privileged/preinstalled apps. The caller is expected to have either the
2475 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2476 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2477 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2478 * permission and cannot be revoked. See http://b/23597341
2479 *
2480 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2481 * of this app will be updated to the current time.
2482 */
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002483 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhu4418c8e2021-02-22 15:40:43 +08002484 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2485 == PackageManager.PERMISSION_GRANTED) {
2486 return;
2487 }
2488
2489 if (callingPkg == null) {
2490 throw new SecurityException("Calling package name is null.");
2491 }
2492
2493 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2494 final int uid = mDeps.getCallingUid();
2495 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2496 callingPkg, callingAttributionTag, null /* message */);
2497
2498 if (mode == AppOpsManager.MODE_ALLOWED) {
2499 return;
2500 }
2501
2502 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2503 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2504 return;
2505 }
2506
2507 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2508 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2509 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002510 }
2511
Charles He729f0b42017-05-15 17:07:18 +01002512 private void enforceSettingsPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002513 enforceAnyPermissionOf(
Charles He729f0b42017-05-15 17:07:18 +01002514 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002515 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He729f0b42017-05-15 17:07:18 +01002516 }
2517
paulhud70b7dd2019-08-12 16:25:11 +08002518 private void enforceNetworkFactoryPermission() {
paulhu44939832020-03-04 09:43:41 +08002519 enforceAnyPermissionOf(
paulhud70b7dd2019-08-12 16:25:11 +08002520 android.Manifest.permission.NETWORK_FACTORY,
paulhu44939832020-03-04 09:43:41 +08002521 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhud70b7dd2019-08-12 16:25:11 +08002522 }
2523
Aaron Huange5c0ba32020-04-14 13:43:49 +08002524 private void enforceNetworkFactoryOrSettingsPermission() {
2525 enforceAnyPermissionOf(
2526 android.Manifest.permission.NETWORK_SETTINGS,
2527 android.Manifest.permission.NETWORK_FACTORY,
2528 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2529 }
2530
2531 private void enforceNetworkFactoryOrTestNetworksPermission() {
2532 enforceAnyPermissionOf(
2533 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2534 android.Manifest.permission.NETWORK_FACTORY,
2535 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2536 }
2537
Chalard Jean88953062018-02-21 18:43:54 +09002538 private boolean checkSettingsPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002539 return checkAnyPermissionOf(
2540 android.Manifest.permission.NETWORK_SETTINGS,
2541 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean88953062018-02-21 18:43:54 +09002542 }
2543
2544 private boolean checkSettingsPermission(int pid, int uid) {
2545 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002546 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2547 || PERMISSION_GRANTED == mContext.checkPermission(
2548 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean88953062018-02-21 18:43:54 +09002549 }
2550
paulhud70b7dd2019-08-12 16:25:11 +08002551 private void enforceNetworkStackOrSettingsPermission() {
2552 enforceAnyPermissionOf(
2553 android.Manifest.permission.NETWORK_SETTINGS,
2554 android.Manifest.permission.NETWORK_STACK,
2555 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2556 }
2557
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002558 private void enforceNetworkStackSettingsOrSetup() {
2559 enforceAnyPermissionOf(
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002560 android.Manifest.permission.NETWORK_SETTINGS,
2561 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov4753f402019-01-25 08:50:06 +00002562 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002563 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov4753f402019-01-25 08:50:06 +00002564 }
2565
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01002566 private void enforceAirplaneModePermission() {
2567 enforceAnyPermissionOf(
2568 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2569 android.Manifest.permission.NETWORK_SETTINGS,
2570 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2571 android.Manifest.permission.NETWORK_STACK,
2572 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2573 }
2574
James Mattis981865c2021-01-26 14:05:36 -08002575 private void enforceOemNetworkPreferencesPermission() {
2576 mContext.enforceCallingOrSelfPermission(
2577 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2578 "ConnectivityService");
2579 }
2580
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07002581 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002582 return checkAnyPermissionOf(
2583 android.Manifest.permission.NETWORK_STACK,
2584 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07002585 }
2586
Cody Kestingd292a332020-01-05 14:06:39 -08002587 private boolean checkNetworkStackPermission(int pid, int uid) {
2588 return checkAnyPermissionOf(pid, uid,
2589 android.Manifest.permission.NETWORK_STACK,
2590 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2591 }
2592
paulhua9a6e2a2019-03-22 16:35:06 +08002593 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2594 return checkAnyPermissionOf(pid, uid,
2595 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jeancbc7c5b2020-04-13 21:54:58 +09002596 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2597 android.Manifest.permission.NETWORK_SETTINGS);
paulhua9a6e2a2019-03-22 16:35:06 +08002598 }
2599
Hugo Benichic4899352016-07-19 15:59:27 +09002600 private void enforceConnectivityRestrictedNetworksPermission() {
2601 try {
2602 mContext.enforceCallingOrSelfPermission(
2603 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2604 "ConnectivityService");
2605 return;
2606 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhud70b7dd2019-08-12 16:25:11 +08002607 // TODO: Remove this fallback check after all apps have declared
2608 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2609 mContext.enforceCallingOrSelfPermission(
2610 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2611 "ConnectivityService");
Hugo Benichic4899352016-07-19 15:59:27 +09002612 }
2613
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002614 private void enforceKeepalivePermission() {
Lorenzo Colittib793d602015-09-08 13:21:48 +09002615 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002616 }
2617
Roshan Pius332e7a22021-03-21 17:55:29 +00002618 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2619 return PERMISSION_GRANTED == mContext.checkPermission(
2620 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2621 }
2622
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09002623 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002624 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002625 }
2626
2627 private void sendInetConditionBroadcast(NetworkInfo info) {
2628 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2629 }
2630
Wink Saville4f0de1e2011-08-04 15:01:58 -07002631 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002632 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002633 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002634 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002635 if (info.isFailover()) {
2636 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2637 info.setFailover(false);
2638 }
2639 if (info.getReason() != null) {
2640 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2641 }
2642 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002643 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2644 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002645 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002646 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002647 return intent;
2648 }
2649
2650 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2651 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2652 }
2653
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002654 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi47858762017-04-26 14:53:28 +09002655 synchronized (this) {
Chalard Jean9fbd93c2018-06-08 14:24:49 +09002656 if (!mSystemReady
2657 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002658 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002659 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002660 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09002661 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002662 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002663 }
2664
Dianne Hackborn6782e222015-12-09 17:22:26 -08002665 Bundle options = null;
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002666 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn2813a692014-12-04 17:46:42 -08002667 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte577c812015-09-01 08:23:04 -07002668 final NetworkInfo ni = intent.getParcelableExtra(
2669 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhud9ce33f2020-02-03 19:52:43 +08002670 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2671 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2672 options = opts.toBundle();
Chad Brubaker88a4e802018-03-08 10:37:09 -08002673 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn2813a692014-12-04 17:46:42 -08002674 }
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002675 try {
Paul Hu32fd2082021-01-26 02:53:06 +00002676 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002677 } finally {
2678 Binder.restoreCallingIdentity(ident);
2679 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002680 }
2681 }
2682
Remi NGUYEN VANebe52982019-06-20 18:29:36 +09002683 /**
Aaron Huang925d09b2020-06-27 07:18:23 +08002684 * Called by SystemServer through ConnectivityManager when the system is ready.
2685 */
2686 @Override
2687 public void systemReady() {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002688 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang925d09b2020-06-27 07:18:23 +08002689 throw new SecurityException("Calling Uid is not system uid.");
2690 }
2691 systemReadyInternal();
2692 }
2693
2694 /**
2695 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VANebe52982019-06-20 18:29:36 +09002696 */
2697 @VisibleForTesting
Aaron Huang925d09b2020-06-27 07:18:23 +08002698 public void systemReadyInternal() {
Aaron Huang5301b6f2020-12-08 10:03:29 +08002699 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2700 // listening network request which is sent by MultipathPolicyTracker won't be added
2701 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2702 // be called after PermissionMonitor#startMonitoring().
2703 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2704 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2705 // to ensure the tracking will be initialized correctly.
paulhubad55592019-11-19 17:55:31 +08002706 mPermissionMonitor.startMonitoring();
Chalard Jean7b09bbf2018-06-08 12:47:42 +09002707 mProxyTracker.loadGlobalProxy();
paulhu0a2aa802021-01-08 00:51:49 +08002708 registerDnsResolverUnsolicitedEventListener();
Wink Saville89c87b92013-08-29 08:55:16 -07002709
Hugo Benichi47858762017-04-26 14:53:28 +09002710 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002711 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002712 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002713 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002714 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002715 }
2716 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002717
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07002718 // Create network requests for always-on networks.
2719 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
The Android Open Source Project28527d22009-03-03 19:31:44 -08002720 }
2721
The Android Open Source Project28527d22009-03-03 19:31:44 -08002722 /**
Chiachang Wangb4bba712020-12-15 15:56:00 +08002723 * Start listening for default data network activity state changes.
2724 */
2725 @Override
2726 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslina5e9bdb2021-01-21 02:04:15 +08002727 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wangb4bba712020-12-15 15:56:00 +08002728 }
2729
2730 /**
2731 * Stop listening for default data network activity state changes.
2732 */
2733 @Override
2734 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslina5e9bdb2021-01-21 02:04:15 +08002735 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wangb4bba712020-12-15 15:56:00 +08002736 }
2737
2738 /**
2739 * Check whether the default network radio is currently active.
2740 */
2741 @Override
2742 public boolean isDefaultNetworkActive() {
lucaslina5e9bdb2021-01-21 02:04:15 +08002743 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wangb4bba712020-12-15 15:56:00 +08002744 }
2745
2746 /**
Chalard Jean73d9db72018-06-04 16:52:49 +09002747 * Reads the network specific MTU size from resources.
sy.yun30043282013-09-02 05:24:09 +09002748 * and set it on it's iface.
2749 */
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002750 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2751 final String iface = newLp.getInterfaceName();
2752 final int mtu = newLp.getMtu();
Pierre Imai98f9c2c2016-02-08 16:01:40 +09002753 if (oldLp == null && mtu == 0) {
2754 // Silently ignore unset MTU value.
2755 return;
2756 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002757 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2758 if (VDBG) log("identical MTU - not setting");
2759 return;
2760 }
paulhu9bb04802019-03-08 16:35:20 +08002761 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09002762 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002763 return;
2764 }
sy.yun30043282013-09-02 05:24:09 +09002765
w19976c3455c32014-08-05 15:18:11 -07002766 // Cannot set MTU without interface name
2767 if (TextUtils.isEmpty(iface)) {
2768 loge("Setting MTU size with null iface.");
2769 return;
2770 }
2771
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002772 try {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09002773 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wangfd478312020-10-26 17:13:09 +08002774 mNetd.interfaceSetMtu(iface, mtu);
2775 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang11e9a312020-10-30 22:04:25 +08002776 loge("exception in interfaceSetMtu()" + e);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002777 }
2778 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002779
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002780 @VisibleForTesting
2781 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensena871d062015-05-13 14:05:12 -04002782
lucaslin589964b2018-11-28 19:27:52 +08002783 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt03806862014-08-06 12:00:25 -07002784 String[] values = null;
2785 if (tcpBufferSizes != null) {
2786 values = tcpBufferSizes.split(",");
2787 }
2788
2789 if (values == null || values.length != 6) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07002790 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt03806862014-08-06 12:00:25 -07002791 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2792 values = tcpBufferSizes.split(",");
2793 }
2794
2795 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2796
2797 try {
Aaron Huang11e9a312020-10-30 22:04:25 +08002798 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt03806862014-08-06 12:00:25 -07002799
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002800 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2801 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2802 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt03806862014-08-06 12:00:25 -07002803 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002804 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt03806862014-08-06 12:00:25 -07002805 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002806 }
2807 }
2808
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07002809 @Override
2810 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti756a0222017-03-21 18:54:11 +09002811 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002812 NETWORK_RESTORE_DELAY_PROP_NAME);
2813 if(restoreDefaultNetworkDelayStr != null &&
2814 restoreDefaultNetworkDelayStr.length() != 0) {
2815 try {
Narayan Kamath846fa3e2016-04-15 18:32:45 +01002816 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002817 } catch (NumberFormatException e) {
2818 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002819 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002820 // if the system property isn't set, use the value for the apn type
2821 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2822
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09002823 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2824 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002825 }
2826 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002827 }
2828
Lorenzo Colittidad88972016-03-03 17:53:46 +09002829 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2830 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2831 final long DIAG_TIME_MS = 5000;
Hugo Benichi821785c2018-09-03 08:19:02 +09002832 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yud0e42212019-07-05 11:51:34 +08002833 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colittidad88972016-03-03 17:53:46 +09002834 // Start gathering diagnostic information.
2835 netDiags.add(new NetworkDiagnostics(
2836 nai.network,
2837 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yud0e42212019-07-05 11:51:34 +08002838 privateDnsCfg,
Lorenzo Colittidad88972016-03-03 17:53:46 +09002839 DIAG_TIME_MS));
2840 }
2841
2842 for (NetworkDiagnostics netDiag : netDiags) {
2843 pw.println();
2844 netDiag.waitForMeasurements();
2845 netDiag.dump(pw);
2846 }
2847 }
2848
The Android Open Source Project28527d22009-03-03 19:31:44 -08002849 @Override
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09002850 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2851 @Nullable String[] args) {
Chiachang Wang70348a22021-04-19 10:59:24 +08002852 if (!checkDumpPermission(mContext, TAG, writer)) return;
2853
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08002854 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair9154a422017-10-26 10:08:50 -07002855 }
2856
lucaslin9d4b8642020-12-10 15:10:54 +08002857 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2858 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2859 != PackageManager.PERMISSION_GRANTED) {
2860 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002861 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin9d4b8642020-12-10 15:10:54 +08002862 + " due to missing android.permission.DUMP permission");
2863 return false;
2864 } else {
2865 return true;
2866 }
2867 }
2868
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08002869 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002870 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002871
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002872 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colittidad88972016-03-03 17:53:46 +09002873 dumpNetworkDiagnostics(pw);
2874 return;
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002875 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichif93f4482018-09-03 08:32:56 +09002876 dumpNetworks(pw);
2877 return;
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002878 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichif93f4482018-09-03 08:32:56 +09002879 dumpNetworkRequests(pw);
2880 return;
Lorenzo Colittidad88972016-03-03 17:53:46 +09002881 }
Erik Kline445cad12015-06-05 17:47:34 +09002882
Lorenzo Colitti94c93142020-01-10 00:40:28 +09002883 pw.print("NetworkProviders for:");
2884 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2885 pw.print(" " + npi.name);
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07002886 }
Lorenzo Colitti417c25c2015-06-03 11:18:24 +09002887 pw.println();
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07002888 pw.println();
2889
Chalard Jean1bc77a92021-02-04 13:12:59 +09002890 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalt31a40522014-05-13 15:36:27 -07002891 pw.print("Active default network: ");
Chalard Jean1bc77a92021-02-04 13:12:59 +09002892 if (defaultNai == null) {
Robert Greenwalt31a40522014-05-13 15:36:27 -07002893 pw.println("none");
2894 } else {
Chalard Jean1bc77a92021-02-04 13:12:59 +09002895 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002896 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002897 pw.println();
2898
James Mattis6e6fabf2021-01-10 14:24:24 -08002899 pw.print("Current per-app default networks: ");
2900 pw.increaseIndent();
2901 dumpPerAppNetworkPreferences(pw);
2902 pw.decreaseIndent();
2903 pw.println();
2904
Robert Greenwalt31a40522014-05-13 15:36:27 -07002905 pw.println("Current Networks:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002906 pw.increaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002907 dumpNetworks(pw);
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002908 pw.decreaseIndent();
Robert Greenwalt31a40522014-05-13 15:36:27 -07002909 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002910
junyulai5ab727b2018-08-07 19:50:45 +08002911 pw.println("Status for known UIDs:");
2912 pw.increaseIndent();
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002913 final int size = mUidBlockedReasons.size();
junyulai5ab727b2018-08-07 19:50:45 +08002914 for (int i = 0; i < size; i++) {
2915 // Don't crash if the array is modified while dumping in bugreports.
2916 try {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002917 final int uid = mUidBlockedReasons.keyAt(i);
2918 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2919 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankab9c396e2021-04-21 07:23:54 +00002920 + Integer.toHexString(blockedReasons));
junyulai5ab727b2018-08-07 19:50:45 +08002921 } catch (ArrayIndexOutOfBoundsException e) {
2922 pw.println(" ArrayIndexOutOfBoundsException");
2923 } catch (ConcurrentModificationException e) {
2924 pw.println(" ConcurrentModificationException");
2925 }
2926 }
2927 pw.println();
2928 pw.decreaseIndent();
2929
Robert Greenwalt31a40522014-05-13 15:36:27 -07002930 pw.println("Network Requests:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002931 pw.increaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002932 dumpNetworkRequests(pw);
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002933 pw.decreaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002934 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002935
Robert Greenwaltdbd5f312014-07-30 16:31:24 -07002936 mLegacyTypeTracker.dump(pw);
Robert Greenwaltdbd5f312014-07-30 16:31:24 -07002937
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002938 pw.println();
markchien497a0622019-09-30 14:40:57 +08002939 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002940
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002941 pw.println();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09002942 dumpAvoidBadWifiSettings(pw);
Lorenzo Colittidad88972016-03-03 17:53:46 +09002943
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09002944 pw.println();
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09002945
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002946 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt2784ed62015-06-23 15:03:33 -07002947 pw.println();
Erik Kline47401fa2015-07-09 18:24:03 +09002948 pw.println("mNetworkRequestInfoLogs (most recent first):");
2949 pw.increaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002950 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Kline47401fa2015-07-09 18:24:03 +09002951 pw.decreaseIndent();
Hugo Benichi7b3bf372016-07-11 11:05:12 +09002952
2953 pw.println();
2954 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2955 pw.increaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002956 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichi7b3bf372016-07-11 11:05:12 +09002957 pw.decreaseIndent();
Hugo Benichi23ec1c92017-03-30 10:46:05 +09002958
2959 pw.println();
2960 pw.println("NetTransition WakeLock activity (most recent first):");
2961 pw.increaseIndent();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09002962 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2963 pw.println("total releases: " + mTotalWakelockReleases);
2964 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2965 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2966 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2967 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2968 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2969 }
James Mattis6e4405f2021-04-06 17:07:42 -07002970 mWakelockLogs.reverseDump(pw);
Nathan Harold6179b142018-07-30 13:38:01 -07002971
2972 pw.println();
2973 pw.println("bandwidth update requests (by uid):");
2974 pw.increaseIndent();
2975 synchronized (mBandwidthRequests) {
2976 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2977 pw.println("[" + mBandwidthRequests.keyAt(i)
2978 + "]: " + mBandwidthRequests.valueAt(i));
2979 }
2980 }
2981 pw.decreaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002982 pw.decreaseIndent();
Nathan Harold6179b142018-07-30 13:38:01 -07002983
James Mattis6e4405f2021-04-06 17:07:42 -07002984 pw.println();
2985 pw.println("mOemNetworkPreferencesLogs (most recent first):");
2986 pw.increaseIndent();
2987 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi23ec1c92017-03-30 10:46:05 +09002988 pw.decreaseIndent();
Robert Greenwalt2784ed62015-06-23 15:03:33 -07002989 }
Remi NGUYEN VANa00a3f22019-02-18 11:20:28 +09002990
2991 pw.println();
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00002992
2993 pw.println();
2994 pw.println("Permission Monitor:");
2995 pw.increaseIndent();
2996 mPermissionMonitor.dump(pw);
2997 pw.decreaseIndent();
lucaslin3756fcc2021-01-21 02:04:35 +08002998
2999 pw.println();
3000 pw.println("Legacy network activity:");
3001 pw.increaseIndent();
3002 mNetworkActivityTracker.dump(pw);
3003 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003004 }
3005
Hugo Benichif93f4482018-09-03 08:32:56 +09003006 private void dumpNetworks(IndentingPrintWriter pw) {
3007 for (NetworkAgentInfo nai : networksSortedById()) {
3008 pw.println(nai.toString());
3009 pw.increaseIndent();
3010 pw.println(String.format(
3011 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3012 nai.numForegroundNetworkRequests(),
3013 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3014 nai.numBackgroundNetworkRequests(),
3015 nai.numNetworkRequests()));
3016 pw.increaseIndent();
3017 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3018 pw.println(nai.requestAt(i).toString());
3019 }
3020 pw.decreaseIndent();
junyulai2a4f0062021-02-03 20:15:30 +08003021 pw.println("Inactivity Timers:");
Hugo Benichif93f4482018-09-03 08:32:56 +09003022 pw.increaseIndent();
junyulai2a4f0062021-02-03 20:15:30 +08003023 nai.dumpInactivityTimers(pw);
Hugo Benichif93f4482018-09-03 08:32:56 +09003024 pw.decreaseIndent();
3025 pw.decreaseIndent();
3026 }
3027 }
3028
James Mattis6e6fabf2021-01-10 14:24:24 -08003029 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3030 pw.println("Per-App Network Preference:");
3031 pw.increaseIndent();
3032 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3033 pw.println("none");
3034 } else {
3035 pw.println(mOemNetworkPreferences.toString());
3036 }
3037 pw.decreaseIndent();
3038
3039 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3040 if (mDefaultRequest == defaultRequest) {
3041 continue;
3042 }
3043
3044 final boolean isActive = null != defaultRequest.getSatisfier();
3045 pw.println("Is per-app network active:");
3046 pw.increaseIndent();
3047 pw.println(isActive);
3048 if (isActive) {
3049 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3050 }
3051 pw.println("Tracked UIDs:");
3052 pw.increaseIndent();
3053 if (0 == defaultRequest.mRequests.size()) {
3054 pw.println("none, this should never occur.");
3055 } else {
Chiachang Wangd5034c72021-02-22 18:36:38 +08003056 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
James Mattis6e6fabf2021-01-10 14:24:24 -08003057 }
3058 pw.decreaseIndent();
3059 pw.decreaseIndent();
3060 }
3061 }
3062
Hugo Benichif93f4482018-09-03 08:32:56 +09003063 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3064 for (NetworkRequestInfo nri : requestsSortedById()) {
3065 pw.println(nri.toString());
3066 }
3067 }
3068
Hugo Benichi821785c2018-09-03 08:19:02 +09003069 /**
3070 * Return an array of all current NetworkAgentInfos sorted by network id.
3071 */
3072 private NetworkAgentInfo[] networksSortedById() {
3073 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003074 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayev284cb872020-12-07 22:43:07 -08003075 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichi821785c2018-09-03 08:19:02 +09003076 return networks;
3077 }
3078
3079 /**
3080 * Return an array of all current NetworkRequest sorted by request id.
3081 */
James Mattisf8eb49a2020-11-15 15:04:40 -08003082 @VisibleForTesting
James Mattisc449dde2020-11-20 16:08:10 -08003083 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichi821785c2018-09-03 08:19:02 +09003084 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattis622428c2020-12-02 14:12:41 -08003085 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattisf8eb49a2020-11-15 15:04:40 -08003086 // Sort the array based off the NRI containing the min requestId in its requests.
3087 Arrays.sort(requests,
3088 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3089 Comparator.comparingInt(req -> req.requestId)).requestId
3090 )
3091 );
Hugo Benichi821785c2018-09-03 08:19:02 +09003092 return requests;
3093 }
3094
Lorenzo Colittif0461852016-04-05 17:52:16 +09003095 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08003096 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwaltcf971852014-08-19 18:58:04 -07003097 if (officialNai != null && officialNai.equals(nai)) return true;
3098 if (officialNai != null || VDBG) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09003099 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwaltcf971852014-08-19 18:58:04 -07003100 " - " + nai);
3101 }
3102 return false;
3103 }
3104
Robert Greenwalt2034b912009-08-12 16:08:25 -07003105 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003106 private class NetworkStateTrackerHandler extends Handler {
3107 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003108 super(looper);
3109 }
3110
Lorenzo Colittif0461852016-04-05 17:52:16 +09003111 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003112 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3113 final NetworkAgentInfo nai = arg.first;
3114 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittif0461852016-04-05 17:52:16 +09003115 if (VDBG) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09003116 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittif0461852016-04-05 17:52:16 +09003117 }
3118 return;
3119 }
3120
3121 switch (msg.what) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003122 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003123 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin25a50472019-03-12 13:08:03 +08003124 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang11e9a312020-10-30 22:04:25 +08003125 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt948aea52014-04-11 15:53:27 -07003126 }
Chalard Jeanb5b172f2020-03-09 21:25:37 +09003127 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3128 // Make sure the original object is not mutated. NetworkAgent normally
3129 // makes a copy of the capabilities when sending the message through
3130 // the Messenger, but if this ever changes, not making a defensive copy
3131 // here will give attack vectors to clients using this code path.
3132 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Cody Kestingba343362020-04-07 16:07:33 -07003133 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
Chalard Jeanb5b172f2020-03-09 21:25:37 +09003134 }
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003135 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichi810f4912016-09-15 18:18:48 +09003136 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt948aea52014-04-11 15:53:27 -07003137 break;
3138 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003139 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003140 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09003141 processLinkPropertiesFromAgent(nai, newLp);
3142 handleUpdateLinkProperties(nai, newLp);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003143 break;
3144 }
3145 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003146 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003147 updateNetworkInfo(nai, info);
3148 break;
3149 }
Robert Greenwaltcf82b832014-05-27 13:20:24 -07003150 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jeandd753522020-12-21 18:36:52 +09003151 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwaltcf82b832014-05-27 13:20:24 -07003152 break;
3153 }
Robert Greenwaltcea86b02014-09-07 16:50:01 -07003154 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colitti72792e22019-06-04 14:37:26 +09003155 if (nai.everConnected) {
3156 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jean67b66082021-01-20 20:47:32 +09003157 // Note that if the NAI had been connected, this would affect the
3158 // score, and therefore would require re-mixing the score and performing
3159 // a rematch.
Paul Jensend4e077c2014-09-26 10:10:22 -04003160 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003161 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3162 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin25a50472019-03-12 13:08:03 +08003163 // Mark the network as temporarily accepting partial connectivity so that it
3164 // will be validated (and possibly become default) even if it only provides
3165 // partial internet access. Note that if user connects to partial connectivity
3166 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3167 // out of wifi coverage) and if the same wifi is available again, the device
3168 // will auto connect to this wifi even though the wifi has "no internet".
3169 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colitticf595362020-01-12 22:28:37 +09003170 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwaltcea86b02014-09-07 16:50:01 -07003171 break;
3172 }
junyulai21c06d02019-01-03 18:50:15 +08003173 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003174 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colittid1039d12015-06-15 14:29:22 +09003175 break;
3176 }
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003177 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09003178 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003179 if (!nai.supportsUnderlyingNetworks()) {
3180 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3181 break;
3182 }
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09003183
Remi NGUYEN VANd793eb32020-12-25 12:45:46 +09003184 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09003185
3186 if (isLegacyLockdownNai(nai)
3187 && (underlying == null || underlying.size() != 1)) {
3188 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3189 + " must have exactly one underlying network: " + underlying);
3190 }
3191
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003192 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3193 nai.declaredUnderlyingNetworks = (underlying != null)
3194 ? underlying.toArray(new Network[0]) : null;
3195
3196 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3197 if (DBG) {
3198 log(nai.toShortString() + " changed underlying networks to "
3199 + Arrays.toString(nai.declaredUnderlyingNetworks));
3200 }
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003201 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003202 notifyIfacesChangedForNetworkStats();
3203 }
Daniel Bright60f02ed2020-06-15 16:10:01 -07003204 break;
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003205 }
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003206 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3207 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3208 nai.teardownDelayMs = msg.arg1;
3209 } else {
3210 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3211 }
Chalard Jeane634b282021-03-05 23:07:53 +09003212 break;
3213 }
3214 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3215 nai.setLingerDuration((int) arg.second);
3216 break;
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003217 }
Lorenzo Colittif0461852016-04-05 17:52:16 +09003218 }
3219 }
3220
3221 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3222 switch (msg.what) {
3223 default:
3224 return false;
lucaslin8cf57f52019-10-22 18:27:33 +08003225 case EVENT_PROBE_STATUS_CHANGED: {
3226 final Integer netId = (Integer) msg.obj;
3227 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3228 if (nai == null) {
3229 break;
3230 }
3231 final boolean probePrivateDnsCompleted =
3232 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3233 final boolean privateDnsBroken =
3234 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3235 if (probePrivateDnsCompleted) {
3236 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3237 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003238 updateCapabilitiesForNetwork(nai);
lucaslin8cf57f52019-10-22 18:27:33 +08003239 }
3240 // Only show the notification when the private DNS is broken and the
3241 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colitticf595362020-01-12 22:28:37 +09003242 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucaslin8cf57f52019-10-22 18:27:33 +08003243 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3244 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003245 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucaslin8cf57f52019-10-22 18:27:33 +08003246 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3247 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3248 // private DNS is broken, it means this network is being reevaluated.
3249 // Either probing private DNS is not necessary any more or it hasn't been
3250 // done yet. In either case, the networkCapabilities should be updated to
3251 // reflect the new status.
3252 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003253 updateCapabilitiesForNetwork(nai);
Lorenzo Colitticf595362020-01-12 22:28:37 +09003254 nai.networkAgentConfig.hasShownBroken = false;
lucaslin8cf57f52019-10-22 18:27:33 +08003255 }
3256 break;
3257 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003258 case EVENT_NETWORK_TESTED: {
Cody Kestingd292a332020-01-05 14:06:39 -08003259 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3260
3261 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Klinec06d4f92018-01-11 21:07:29 +09003262 if (nai == null) break;
3263
Cody Kestingd292a332020-01-05 14:06:39 -08003264 handleNetworkTested(nai, results.mTestResult,
3265 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003266 break;
3267 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003268 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09003269 final int netId = msg.arg2;
Hugo Benichi7f919fe2017-04-21 15:07:12 +09003270 final boolean visible = toBool(msg.arg1);
Erik Kline076bd3d2018-03-21 07:18:33 -07003271 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin On3fd101e2016-10-11 15:10:46 -07003272 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen783c0e02015-06-16 14:27:36 -04003273 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3274 nai.lastCaptivePortalDetected = visible;
3275 nai.everCaptivePortalDetected |= visible;
Calvin On3fd101e2016-10-11 15:10:46 -07003276 if (nai.lastCaptivePortalDetected &&
paulhu79260c22021-03-17 20:30:33 +08003277 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3278 == getCaptivePortalMode()) {
Chalard Jean373391b2019-12-10 21:07:02 +09003279 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003280 nai.onPreventAutomaticReconnect();
Calvin On3fd101e2016-10-11 15:10:46 -07003281 teardownUnneededNetwork(nai);
3282 break;
3283 }
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003284 updateCapabilitiesForNetwork(nai);
Paul Jensen783c0e02015-06-16 14:27:36 -04003285 }
3286 if (!visible) {
lucaslin1ac72392019-01-24 15:55:30 +08003287 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin25a50472019-03-12 13:08:03 +08003288 // notifications belong to the same network may be cleared unexpectedly.
lucaslin1ac72392019-01-24 15:55:30 +08003289 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3290 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen8ba5ffb2014-07-15 12:07:36 -04003291 } else {
Paul Jensenc3deb112014-08-25 22:45:39 -04003292 if (nai == null) {
3293 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3294 break;
3295 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003296 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittib268f9f2016-08-22 16:46:40 +09003297 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitticf595362020-01-12 22:28:37 +09003298 (PendingIntent) msg.obj,
3299 nai.networkAgentConfig.explicitlySelected);
fionaxu5447c492016-05-23 16:33:16 -07003300 }
Paul Jensen77cbca52014-05-15 10:33:05 -04003301 }
Paul Jensen77cbca52014-05-15 10:33:05 -04003302 break;
3303 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003304 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline076bd3d2018-03-21 07:18:33 -07003305 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinec06d4f92018-01-11 21:07:29 +09003306 if (nai == null) break;
3307
Erik Kline076bd3d2018-03-21 07:18:33 -07003308 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinec06d4f92018-01-11 21:07:29 +09003309 break;
3310 }
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003311 case EVENT_CAPPORT_DATA_CHANGED: {
3312 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3313 if (nai == null) break;
Hai Shalom492febb2021-01-11 18:45:34 -08003314 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003315 break;
3316 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003317 }
Lorenzo Colittif0461852016-04-05 17:52:16 +09003318 return true;
3319 }
3320
Cody Kestingd292a332020-01-05 14:06:39 -08003321 private void handleNetworkTested(
3322 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3323 final boolean wasPartial = nai.partialConnectivity;
3324 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3325 final boolean partialConnectivityChanged =
3326 (wasPartial != nai.partialConnectivity);
3327
3328 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3329 final boolean wasValidated = nai.lastValidated;
Chalard Jean1bc77a92021-02-04 13:12:59 +09003330 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kestingd292a332020-01-05 14:06:39 -08003331
3332 if (DBG) {
3333 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3334 ? " with redirect to " + redirectUrl
3335 : "";
Chalard Jean373391b2019-12-10 21:07:02 +09003336 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kestingd292a332020-01-05 14:06:39 -08003337 }
3338 if (valid != nai.lastValidated) {
Cody Kestingd292a332020-01-05 14:06:39 -08003339 final int oldScore = nai.getCurrentScore();
3340 nai.lastValidated = valid;
3341 nai.everValidated |= valid;
3342 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kestingd292a332020-01-05 14:06:39 -08003343 if (valid) {
3344 handleFreshlyValidatedNetwork(nai);
3345 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3346 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayev284cb872020-12-07 22:43:07 -08003347 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003348 NotificationType.NO_INTERNET);
Serik Beketayev284cb872020-12-07 22:43:07 -08003349 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003350 NotificationType.LOST_INTERNET);
Serik Beketayev284cb872020-12-07 22:43:07 -08003351 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003352 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayev284cb872020-12-07 22:43:07 -08003353 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003354 NotificationType.PRIVATE_DNS_BROKEN);
3355 // If network becomes valid, the hasShownBroken should be reset for
3356 // that network so that the notification will be fired when the private
3357 // DNS is broken again.
3358 nai.networkAgentConfig.hasShownBroken = false;
3359 }
3360 } else if (partialConnectivityChanged) {
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003361 updateCapabilitiesForNetwork(nai);
Cody Kestingd292a332020-01-05 14:06:39 -08003362 }
3363 updateInetCondition(nai);
3364 // Let the NetworkAgent know the state of its network
Cody Kestingd292a332020-01-05 14:06:39 -08003365 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003366 nai.onValidationStatusChanged(
3367 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3368 redirectUrl);
Cody Kestingd292a332020-01-05 14:06:39 -08003369
3370 // If NetworkMonitor detects partial connectivity before
3371 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3372 // immediately. Re-notify partial connectivity silently if no internet
3373 // notification already there.
3374 if (!wasPartial && nai.partialConnectivity) {
3375 // Remove delayed message if there is a pending message.
3376 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3377 handlePromptUnvalidated(nai.network);
3378 }
3379
3380 if (wasValidated && !nai.lastValidated) {
3381 handleNetworkUnvalidated(nai);
3382 }
3383 }
3384
Calvin On3fd101e2016-10-11 15:10:46 -07003385 private int getCaptivePortalMode() {
3386 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08003387 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3388 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin On3fd101e2016-10-11 15:10:46 -07003389 }
3390
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003391 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3392 switch (msg.what) {
3393 default:
3394 return false;
3395 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3396 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3397 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3398 handleLingerComplete(nai);
3399 }
3400 break;
3401 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003402 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3403 handleNetworkAgentRegistered(msg);
3404 break;
3405 }
3406 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3407 handleNetworkAgentDisconnected(msg);
3408 break;
3409 }
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003410 }
3411 return true;
3412 }
3413
Lorenzo Colittif0461852016-04-05 17:52:16 +09003414 @Override
3415 public void handleMessage(Message msg) {
lifr1c0d9b22021-03-10 13:58:14 +08003416 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN8156bbe2020-01-14 19:48:18 +09003417 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittif0461852016-04-05 17:52:16 +09003418 maybeHandleNetworkAgentMessage(msg);
3419 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003420 }
3421 }
3422
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003423 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean15347192019-05-30 14:58:29 +09003424 private final int mNetId;
3425 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003426
3427 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayev284cb872020-12-07 22:43:07 -08003428 mNetId = nai.network.getNetId();
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09003429 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003430 }
3431
3432 @Override
3433 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3434 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean15347192019-05-30 14:58:29 +09003435 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003436 }
3437
3438 @Override
3439 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003440 // Legacy version of notifyNetworkTestedWithExtras.
3441 // Would only be called if the system has a NetworkStack module older than the
3442 // framework, which does not happen in practice.
Aaron Huang11e9a312020-10-30 22:04:25 +08003443 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kestingd292a332020-01-05 14:06:39 -08003444 }
3445
3446 @Override
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003447 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VANfb0774e2020-04-24 20:56:39 +09003448 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3449 // the same looper so messages will be processed in sequence.
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003450 final Message msg = mTrackerHandler.obtainMessage(
3451 EVENT_NETWORK_TESTED,
3452 new NetworkTestedResults(
3453 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kestingd292a332020-01-05 14:06:39 -08003454 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003455
3456 // Invoke ConnectivityReport generation for this Network test event.
3457 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3458 if (nai == null) return;
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003459
3460 final PersistableBundle extras = new PersistableBundle();
3461 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3462 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3463 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3464
Aaron Huang0d1be642021-01-21 15:47:41 +08003465 ConnectivityReportEvent reportEvent =
3466 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3467 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3468 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003469 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003470 }
3471
3472 @Override
3473 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3474 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3475 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean15347192019-05-30 14:58:29 +09003476 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003477 }
3478
3479 @Override
lucaslin8cf57f52019-10-22 18:27:33 +08003480 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3481 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3482 EVENT_PROBE_STATUS_CHANGED,
3483 probesCompleted, probesSucceeded, new Integer(mNetId)));
3484 }
3485
3486 @Override
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003487 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3488 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3489 EVENT_CAPPORT_DATA_CHANGED,
3490 0, mNetId, data));
3491 }
3492
3493 @Override
Remi NGUYEN VAN8b3999c2019-02-07 21:29:57 +09003494 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003495 final Intent intent = new Intent(action);
Remi NGUYEN VAN8b3999c2019-02-07 21:29:57 +09003496 intent.setPackage(packageName);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003497
3498 final PendingIntent pendingIntent;
3499 // Only the system server can register notifications with package "android"
3500 final long token = Binder.clearCallingIdentity();
3501 try {
paulhu68426192020-06-09 19:07:03 +08003502 pendingIntent = PendingIntent.getBroadcast(
3503 mContext,
3504 0 /* requestCode */,
3505 intent,
3506 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003507 } finally {
3508 Binder.restoreCallingIdentity(token);
3509 }
3510 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3511 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean15347192019-05-30 14:58:29 +09003512 mNetId, pendingIntent));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003513 }
3514
3515 @Override
3516 public void hideProvisioningNotification() {
3517 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean15347192019-05-30 14:58:29 +09003518 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003519 }
Remi NGUYEN VANe72fe2b2019-04-05 15:15:48 +09003520
3521 @Override
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003522 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kesting6784cf62020-05-11 10:06:51 -07003523 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kesting1d326382020-01-06 16:55:35 -08003524 }
3525
3526 @Override
Remi NGUYEN VANe72fe2b2019-04-05 15:15:48 +09003527 public int getInterfaceVersion() {
3528 return this.VERSION;
3529 }
Paul Trautrim69929da2020-01-23 14:55:57 +09003530
3531 @Override
3532 public String getInterfaceHash() {
3533 return this.HASH;
3534 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003535 }
3536
Cody Kesting6784cf62020-05-11 10:06:51 -07003537 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kesting43a47ef2020-05-15 10:36:01 -07003538 log("Data stall detected with methods: " + p.detectionMethod);
3539
Cody Kesting6784cf62020-05-11 10:06:51 -07003540 final PersistableBundle extras = new PersistableBundle();
Cody Kesting43a47ef2020-05-15 10:36:01 -07003541 int detectionMethod = 0;
3542 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3543 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3544 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3545 }
3546 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3547 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3548 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3549 p.tcpMetricsCollectionPeriodMillis);
3550 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kesting6784cf62020-05-11 10:06:51 -07003551 }
3552
Cody Kestingb5c7abd2020-04-15 12:33:28 -07003553 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kesting6784cf62020-05-11 10:06:51 -07003554 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang0d1be642021-01-21 15:47:41 +08003555 new Pair<>(p.timestampMillis, extras));
Cody Kestingb5c7abd2020-04-15 12:33:28 -07003556
3557 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3558 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3559 // the cost of going through two handlers.
3560 mConnectivityDiagnosticsHandler.sendMessage(msg);
3561 }
3562
Cody Kesting43a47ef2020-05-15 10:36:01 -07003563 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3564 return (p.detectionMethod & detectionMethod) != 0;
3565 }
3566
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003567 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3568 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline076bd3d2018-03-21 07:18:33 -07003569 }
3570
Erik Klinee6d899a2018-06-26 18:53:43 +09003571 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3572 if (nai == null) return;
3573 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3574 // in order to restart a validation pass from within netd.
3575 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3576 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayev284cb872020-12-07 22:43:07 -08003577 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinee6d899a2018-06-26 18:53:43 +09003578 }
3579 }
3580
Erik Klinec06d4f92018-01-11 21:07:29 +09003581 private void handlePrivateDnsSettingsChanged() {
3582 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3583
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003584 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline076bd3d2018-03-21 07:18:33 -07003585 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003586 if (networkRequiresPrivateDnsValidation(nai)) {
dalykf4977492018-03-05 12:42:22 -05003587 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3588 }
Erik Klinec06d4f92018-01-11 21:07:29 +09003589 }
3590 }
3591
Erik Kline076bd3d2018-03-21 07:18:33 -07003592 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3593 // Private DNS only ever applies to networks that might provide
3594 // Internet access and therefore also require validation.
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003595 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Klinec06d4f92018-01-11 21:07:29 +09003596
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003597 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline076bd3d2018-03-21 07:18:33 -07003598 // schedule DNS resolutions. If a DNS resolution is required the
3599 // result will be sent back to us.
Lorenzo Colitti260d9982019-05-31 15:41:29 +09003600 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline076bd3d2018-03-21 07:18:33 -07003601
3602 // With Private DNS bypass support, we can proceed to update the
3603 // Private DNS config immediately, even if we're in strict mode
3604 // and have not yet resolved the provider name into a set of IPs.
3605 updatePrivateDns(nai, cfg);
3606 }
3607
3608 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3609 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayev284cb872020-12-07 22:43:07 -08003610 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinec06d4f92018-01-11 21:07:29 +09003611 }
3612
dalykf4977492018-03-05 12:42:22 -05003613 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3614 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3615 if (nai == null) {
3616 return;
3617 }
3618 mDnsManager.updatePrivateDnsValidation(update);
3619 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3620 }
3621
paulhu0a2aa802021-01-08 00:51:49 +08003622 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003623 int prefixLength) {
3624 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3625 if (nai == null) return;
3626
paulhu0a2aa802021-01-08 00:51:49 +08003627 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3628 netId, operation, prefixAddress, prefixLength));
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003629
3630 IpPrefix prefix = null;
paulhu0a2aa802021-01-08 00:51:49 +08003631 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003632 try {
paulhu0a2aa802021-01-08 00:51:49 +08003633 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003634 prefixLength);
3635 } catch (IllegalArgumentException e) {
paulhu0a2aa802021-01-08 00:51:49 +08003636 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003637 return;
3638 }
3639 }
3640
Lorenzo Colittifff75392020-04-01 20:16:30 +09003641 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003642 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3643 }
3644
Hai Shalom492febb2021-01-11 18:45:34 -08003645 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003646 @Nullable final CaptivePortalData data) {
Hai Shalom492febb2021-01-11 18:45:34 -08003647 nai.capportApiData = data;
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003648 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3649 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3650 }
3651
Chalard Jeand915e362019-12-04 18:49:18 +09003652 /**
junyulai2a4f0062021-02-03 20:15:30 +08003653 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jeand915e362019-12-04 18:49:18 +09003654 * @param nai the agent info to update
3655 * @param now the timestamp of the event causing this update
junyulai2a4f0062021-02-03 20:15:30 +08003656 * @return whether the network was inactive as a result of this update
Chalard Jeand915e362019-12-04 18:49:18 +09003657 */
junyulai2a4f0062021-02-03 20:15:30 +08003658 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3659 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3660 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003661 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2a4f0062021-02-03 20:15:30 +08003662 // one lingered request, set inactive.
3663 nai.updateInactivityTimer();
junyulaif6d98ec2020-12-14 18:41:52 +08003664 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2a4f0062021-02-03 20:15:30 +08003665 if (DBG) log("Unsetting inactive " + nai.toShortString());
3666 nai.unsetInactive();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003667 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2a4f0062021-02-03 20:15:30 +08003668 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jeand915e362019-12-04 18:49:18 +09003669 if (DBG) {
junyulai2a4f0062021-02-03 20:15:30 +08003670 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3671 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jeand915e362019-12-04 18:49:18 +09003672 }
junyulai2a4f0062021-02-03 20:15:30 +08003673 nai.setInactive();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003674 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jeand915e362019-12-04 18:49:18 +09003675 return true;
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003676 }
Chalard Jeand915e362019-12-04 18:49:18 +09003677 return false;
Paul Jensen935ceef2014-11-25 15:26:53 -05003678 }
3679
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003680 private void handleNetworkAgentRegistered(Message msg) {
3681 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3682 if (!mNetworkAgentInfos.contains(nai)) {
3683 return;
3684 }
3685
3686 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3687 if (VDBG) log("NetworkAgent registered");
3688 } else {
3689 loge("Error connecting NetworkAgent");
3690 mNetworkAgentInfos.remove(nai);
3691 if (nai != null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09003692 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003693 synchronized (mNetworkForNetId) {
3694 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003695 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003696 mNetIdManager.releaseNetId(nai.network.getNetId());
3697 // Just in case.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003698 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003699 }
3700 }
3701 }
Paul Jensen935ceef2014-11-25 15:26:53 -05003702
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003703 private void handleNetworkAgentDisconnected(Message msg) {
3704 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3705 if (mNetworkAgentInfos.contains(nai)) {
3706 disconnectAndDestroyNetwork(nai);
3707 }
3708 }
3709
Chalard Jeanefaf6532018-05-11 20:19:20 +09003710 // Destroys a network, remove references to it from the internal state managed by
3711 // ConnectivityService, free its interfaces and clean up.
3712 // Must be called on the Handler thread.
3713 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean4deee632019-11-05 14:40:23 +09003714 ensureRunningOnConnectivityServiceThread();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003715 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09003716 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003717 }
lucaslinb5b671a2019-02-12 15:30:13 +08003718 // Clear all notifications of this network.
Serik Beketayev284cb872020-12-07 22:43:07 -08003719 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003720 // A network agent has disconnected.
3721 // TODO - if we move the logic to the network agent (have them disconnect
3722 // because they lost all their requests or because their score isn't good)
3723 // then they would disconnect organically, report their new state and then
3724 // disconnect the channel.
3725 if (nai.networkInfo.isConnected()) {
3726 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3727 null, null);
3728 }
Chalard Jean1bc77a92021-02-04 13:12:59 +09003729 final boolean wasDefault = isDefaultNetwork(nai);
3730 if (wasDefault) {
Chalard Jeanefaf6532018-05-11 20:19:20 +09003731 mDefaultInetConditionPublished = 0;
Chalard Jeanefaf6532018-05-11 20:19:20 +09003732 }
3733 notifyIfacesChangedForNetworkStats();
3734 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3735 // by other networks that are already connected. Perhaps that can be done by
3736 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3737 // of rematchAllNetworksAndRequests
3738 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai21c06d02019-01-03 18:50:15 +08003739 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Bright60f02ed2020-06-15 16:10:01 -07003740
3741 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003742 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3743 // Disable wakeup packet monitoring for each interface.
3744 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3745 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09003746 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003747 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti714b7862019-02-19 13:21:56 +09003748 nai.clatd.update();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003749 synchronized (mNetworkForNetId) {
3750 // Remove the NetworkAgent, but don't mark the netId as
3751 // available until we've told netd to delete it below.
Serik Beketayev284cb872020-12-07 22:43:07 -08003752 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003753 }
Lorenzo Colittic284b4b2021-01-12 00:34:44 +09003754 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003755 // Remove all previously satisfied requests.
3756 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattis1238af22020-12-23 16:37:26 -08003757 final NetworkRequest request = nai.requestAt(i);
Chalard Jeane8cf3bf2019-11-05 15:07:09 +09003758 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattis622428c2020-12-02 14:12:41 -08003759 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayev284cb872020-12-07 22:43:07 -08003760 if (currentNetwork != null
3761 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattis1238af22020-12-23 16:37:26 -08003762 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003763 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3764 // rematch not to keep disconnected agents instead of setting it here ; this
3765 // will also allow removing updating the offers below.
James Mattis622428c2020-12-02 14:12:41 -08003766 nri.setSatisfier(null, null);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003767 for (final NetworkOfferInfo noi : mNetworkOffers) {
3768 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis1238af22020-12-23 16:37:26 -08003769 }
James Mattis8af2d602020-12-20 11:09:58 -08003770
Chalard Jean1bc77a92021-02-04 13:12:59 +09003771 if (mDefaultRequest == nri) {
James Mattis8af2d602020-12-20 11:09:58 -08003772 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean1bc77a92021-02-04 13:12:59 +09003773 // active at the same time. For now keep calling this with the default
James Mattis8af2d602020-12-20 11:09:58 -08003774 // network, because while incorrect this is the closest to the old (also
3775 // incorrect) behavior.
3776 mNetworkActivityTracker.updateDataActivityTracking(
3777 null /* newNetwork */, nai);
James Mattis8af2d602020-12-20 11:09:58 -08003778 ensureNetworkTransitionWakelock(nai.toShortString());
3779 }
Chalard Jeanefaf6532018-05-11 20:19:20 +09003780 }
3781 }
junyulai2a4f0062021-02-03 20:15:30 +08003782 nai.clearInactivityState();
James Mattis8af2d602020-12-20 11:09:58 -08003783 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003784 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattis8af2d602020-12-20 11:09:58 -08003785 // Find out why, fix the rematch code, and delete this.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003786 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jean60902092019-11-07 18:54:49 +09003787 rematchAllNetworksAndRequests();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003788 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003789
3790 // Immediate teardown.
3791 if (nai.teardownDelayMs == 0) {
3792 destroyNetwork(nai);
3793 return;
3794 }
3795
3796 // Delayed teardown.
3797 try {
3798 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3799 } catch (RemoteException e) {
3800 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3801 }
3802 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3803 }
3804
3805 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeanefaf6532018-05-11 20:19:20 +09003806 if (nai.created) {
3807 // Tell netd to clean up the configuration for this network
3808 // (routing rules, DNS, etc).
3809 // This may be slow as it requires a lot of netd shelling out to ip and
3810 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean1bc77a92021-02-04 13:12:59 +09003811 // after we've rematched networks with requests (which might change the default
3812 // network or service a new request from an app), so network traffic isn't interrupted
3813 // for an unnecessarily long time.
Luke Huang135c5262019-04-09 18:41:49 +08003814 destroyNativeNetwork(nai);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003815 mDnsManager.removeNetwork(nai.network);
3816 }
Serik Beketayev284cb872020-12-07 22:43:07 -08003817 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003818 nai.onNetworkDestroyed();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003819 }
3820
Ken Chende5e7aa2021-04-09 15:08:42 +08003821 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huang135c5262019-04-09 18:41:49 +08003822 try {
3823 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chende5e7aa2021-04-09 15:08:42 +08003824 final NativeNetworkConfig config;
3825 if (nai.isVPN()) {
3826 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen4e6ae312021-05-12 13:38:13 +08003827 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chende5e7aa2021-04-09 15:08:42 +08003828 return false;
3829 }
3830 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3831 INetd.PERMISSION_NONE,
3832 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3833 getVpnType(nai));
Luke Huang135c5262019-04-09 18:41:49 +08003834 } else {
Ken Chende5e7aa2021-04-09 15:08:42 +08003835 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3836 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3837 VpnManager.TYPE_VPN_NONE);
Luke Huang135c5262019-04-09 18:41:49 +08003838 }
Ken Chende5e7aa2021-04-09 15:08:42 +08003839 mNetd.networkCreate(config);
3840 mDnsResolver.createNetworkCache(nai.network.getNetId());
3841 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3842 nai.networkCapabilities.getTransportTypes());
Luke Huang135c5262019-04-09 18:41:49 +08003843 return true;
3844 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen4e6ae312021-05-12 13:38:13 +08003845 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huang135c5262019-04-09 18:41:49 +08003846 return false;
3847 }
3848 }
3849
Ken Chende5e7aa2021-04-09 15:08:42 +08003850 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huang135c5262019-04-09 18:41:49 +08003851 try {
Ken Chende5e7aa2021-04-09 15:08:42 +08003852 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Oh1abe20f2021-01-20 11:04:46 +09003853 } catch (RemoteException | ServiceSpecificException e) {
3854 loge("Exception destroying network(networkDestroy): " + e);
3855 }
3856 try {
Ken Chende5e7aa2021-04-09 15:08:42 +08003857 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huang135c5262019-04-09 18:41:49 +08003858 } catch (RemoteException | ServiceSpecificException e) {
3859 loge("Exception destroying network: " + e);
3860 }
3861 }
3862
Jeremy Joslin94c30992014-11-05 10:32:09 -08003863 // If this method proves to be too slow then we can maintain a separate
3864 // pendingIntent => NetworkRequestInfo map.
3865 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3866 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003867 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3868 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3869 if (existingPendingIntent != null &&
paulhu94c60a92021-03-04 11:36:55 +08003870 existingPendingIntent.intentFilterEquals(pendingIntent)) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003871 return entry.getValue();
3872 }
3873 }
3874 return null;
3875 }
3876
James Mattis08131f32020-12-13 16:28:14 -08003877 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003878 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattis08131f32020-12-13 16:28:14 -08003879 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3880 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3881 final NetworkRequestInfo existingRequest =
3882 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003883 if (existingRequest != null) { // remove the existing request.
James Mattis08131f32020-12-13 16:28:14 -08003884 if (DBG) {
3885 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3886 + nri.mRequests.get(0) + " because their intents matched.");
3887 }
Lorenzo Colittie0857092021-03-12 22:39:08 +09003888 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohen06633de2019-01-08 12:09:18 -08003889 /* callOnUnavailable */ false);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003890 }
Erik Kline74d68ef2015-04-30 12:58:40 +09003891 handleRegisterNetworkRequest(nri);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003892 }
3893
James Mattis08131f32020-12-13 16:28:14 -08003894 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattise494cbb2021-02-09 18:18:28 -08003895 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis6e6fabf2021-01-10 14:24:24 -08003896 }
3897
James Mattise494cbb2021-02-09 18:18:28 -08003898 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean4deee632019-11-05 14:40:23 +09003899 ensureRunningOnConnectivityServiceThread();
James Mattis6e6fabf2021-01-10 14:24:24 -08003900 for (final NetworkRequestInfo nri : nris) {
3901 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3902 for (final NetworkRequest req : nri.mRequests) {
3903 mNetworkRequests.put(req, nri);
junyulai8cae3c72021-03-12 20:05:08 +08003904 // TODO: Consider update signal strength for other types.
James Mattis6e6fabf2021-01-10 14:24:24 -08003905 if (req.isListen()) {
3906 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3907 if (req.networkCapabilities.hasSignalStrength()
3908 && network.satisfiesImmutableCapabilitiesOf(req)) {
3909 updateSignalStrengthThresholds(network, "REGISTER", req);
3910 }
James Mattis08131f32020-12-13 16:28:14 -08003911 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09003912 }
3913 }
Chalard Jeand67ab4d2021-03-05 19:18:14 +09003914 // If this NRI has a satisfier already, it is replacing an older request that
3915 // has been removed. Track it.
3916 final NetworkRequest activeRequest = nri.getActiveRequest();
3917 if (null != activeRequest) {
3918 // If there is an active request, then for sure there is a satisfier.
3919 nri.getSatisfier().addRequest(activeRequest);
3920 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09003921 }
James Mattis08131f32020-12-13 16:28:14 -08003922
James Mattis6e6fabf2021-01-10 14:24:24 -08003923 rematchAllNetworksAndRequests();
James Mattis6e6fabf2021-01-10 14:24:24 -08003924
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003925 // Requests that have not been matched to a network will not have been sent to the
3926 // providers, because the old satisfier and the new satisfier are the same (null in this
3927 // case). Send these requests to the providers.
3928 for (final NetworkRequestInfo nri : nris) {
3929 for (final NetworkOfferInfo noi : mNetworkOffers) {
3930 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis6e6fabf2021-01-10 14:24:24 -08003931 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003932 }
3933 }
3934
James Mattis08131f32020-12-13 16:28:14 -08003935 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3936 final int callingUid) {
3937 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003938 if (nri != null) {
James Mattis08131f32020-12-13 16:28:14 -08003939 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3940 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3941 handleReleaseNetworkRequest(
3942 nri.mRequests.get(0),
3943 callingUid,
3944 /* callOnUnavailable */ false);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003945 }
3946 }
3947
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003948 // Determines whether the network is the best (or could become the best, if it validated), for
3949 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3950 // on the value of reason:
3951 //
3952 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3953 // then it should be torn down.
3954 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3955 // then it should be lingered.
3956 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean4deee632019-11-05 14:40:23 +09003957 ensureRunningOnConnectivityServiceThread();
Chalard Jeanf278aba2021-03-08 22:29:27 +09003958
3959 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
3960 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
3961 return false;
3962 }
3963
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003964 final int numRequests;
3965 switch (reason) {
3966 case TEARDOWN:
3967 numRequests = nai.numRequestNetworkRequests();
3968 break;
3969 case LINGER:
3970 numRequests = nai.numForegroundNetworkRequests();
3971 break;
3972 default:
Aaron Huang11e9a312020-10-30 22:04:25 +08003973 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003974 return true;
3975 }
3976
Chalard Jeanf278aba2021-03-08 22:29:27 +09003977 if (numRequests > 0) return false;
3978
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003979 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattise4e72bb2020-11-16 16:46:28 -08003980 if (reason == UnneededFor.LINGER
3981 && !nri.isMultilayerRequest()
3982 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003983 // Background requests don't affect lingering.
3984 continue;
3985 }
3986
James Mattise4e72bb2020-11-16 16:46:28 -08003987 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003988 return false;
Paul Jensen203a7442014-12-09 11:43:45 -05003989 }
3990 }
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003991 return true;
Paul Jensen203a7442014-12-09 11:43:45 -05003992 }
3993
James Mattise4e72bb2020-11-16 16:46:28 -08003994 private boolean isNetworkPotentialSatisfier(
3995 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
3996 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis65d0d1c2020-11-24 17:40:49 -08003997 // request, return immediately. For multilayer requests, check to see if any of the
3998 // multilayer requests may have a potential satisfier.
junyulai8cae3c72021-03-12 20:05:08 +08003999 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4000 || nri.mRequests.get(0).isListenForBest())) {
James Mattise4e72bb2020-11-16 16:46:28 -08004001 return false;
4002 }
4003 for (final NetworkRequest req : nri.mRequests) {
James Mattis622428c2020-12-02 14:12:41 -08004004 // This multilayer listen request is satisfied therefore no further requests need to be
4005 // evaluated deeming this network not a potential satisfier.
junyulai8cae3c72021-03-12 20:05:08 +08004006 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattis622428c2020-12-02 14:12:41 -08004007 return false;
4008 }
James Mattise4e72bb2020-11-16 16:46:28 -08004009 // As non-multilayer listen requests have already returned, the below would only happen
4010 // for a multilayer request therefore continue to the next request if available.
junyulai8cae3c72021-03-12 20:05:08 +08004011 if (req.isListen() || req.isListenForBest()) {
James Mattise4e72bb2020-11-16 16:46:28 -08004012 continue;
4013 }
4014 // If this Network is already the highest scoring Network for a request, or if
4015 // there is hope for it to become one if it validated, then it is needed.
4016 if (candidate.satisfies(req)) {
4017 // As soon as a network is found that satisfies a request, return. Specifically for
4018 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4019 // is important so as to not evaluate lower priority requests further in
4020 // nri.mRequests.
Chalard Jean3d71e302021-04-07 17:06:19 +09004021 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4022 ? nri.getSatisfier() : null;
4023 // Note that this catches two important cases:
4024 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4025 // is currently satisfying the request. This is desirable when
4026 // cellular ends up validating but WiFi does not.
4027 // 2. Unvalidated WiFi will not be reaped when validated cellular
4028 // is currently satisfying the request. This is desirable when
4029 // WiFi ends up validating and out scoring cellular.
4030 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattise4e72bb2020-11-16 16:46:28 -08004031 }
4032 }
4033
4034 return false;
4035 }
4036
Erik Klineaec3f5e2016-07-07 16:50:58 +09004037 private NetworkRequestInfo getNriForAppRequest(
4038 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattise494cbb2021-02-09 18:18:28 -08004039 // Looking up the app passed param request in mRequests isn't possible since it may return
4040 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4041 // do the lookup since that will also find per-app default managed requests.
James Mattis27aeff02021-02-17 16:13:05 -08004042 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4043 // to avoid potential race conditions when validating a package->uid mapping when sending
4044 // the callback on the very low-chance that an application shuts down prior to the callback
4045 // being sent.
4046 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4047 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004048
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004049 if (nri != null) {
lucaslin2d72a132021-03-15 15:35:38 +08004050 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004051 log(String.format("UID %d attempted to %s for unowned request %s",
4052 callingUid, requestedOperation, nri));
4053 return null;
Paul Jensenabaa0ed2014-05-16 14:31:12 -04004054 }
Erik Klineaec3f5e2016-07-07 16:50:58 +09004055 }
4056
4057 return nri;
4058 }
4059
James Mattis08131f32020-12-13 16:28:14 -08004060 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4061 final String callingMethod) {
4062 if (nri.isMultilayerRequest()) {
4063 throw new IllegalStateException(
4064 callingMethod + " does not support multilayer requests.");
Erik Kline66721822015-11-25 12:49:38 +09004065 }
4066 }
4067
James Mattis08131f32020-12-13 16:28:14 -08004068 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004069 ensureRunningOnConnectivityServiceThread();
James Mattis08131f32020-12-13 16:28:14 -08004070 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4071 // single NetworkRequest and thus does not apply to multilayer requests.
4072 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4073 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004074 return;
4075 }
James Mattisf61f7be2021-01-31 17:06:19 -08004076 if (nri.isBeingSatisfied()) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004077 return;
4078 }
James Mattis08131f32020-12-13 16:28:14 -08004079 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4080 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Klineaec3f5e2016-07-07 16:50:58 +09004081 }
4082 handleRemoveNetworkRequest(nri);
James Mattis08131f32020-12-13 16:28:14 -08004083 callCallbackForRequest(
4084 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004085 }
4086
James Mattis08131f32020-12-13 16:28:14 -08004087 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4088 final int callingUid,
4089 final boolean callOnUnavailable) {
Hugo Benichi4802c802017-03-23 22:40:44 +09004090 final NetworkRequestInfo nri =
4091 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4092 if (nri == null) {
4093 return;
Erik Kline66721822015-11-25 12:49:38 +09004094 }
James Mattis08131f32020-12-13 16:28:14 -08004095 if (VDBG || (DBG && request.isRequest())) {
4096 log("releasing " + request + " (release request)");
Hugo Benichi4802c802017-03-23 22:40:44 +09004097 }
4098 handleRemoveNetworkRequest(nri);
Etan Cohen06633de2019-01-08 12:09:18 -08004099 if (callOnUnavailable) {
4100 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4101 }
Erik Kline66721822015-11-25 12:49:38 +09004102 }
Erik Klineaec3f5e2016-07-07 16:50:58 +09004103
James Mattis622428c2020-12-02 14:12:41 -08004104 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean4deee632019-11-05 14:40:23 +09004105 ensureRunningOnConnectivityServiceThread();
Erik Klineaec3f5e2016-07-07 16:50:58 +09004106 nri.unlinkDeathRecipient();
James Mattis622428c2020-12-02 14:12:41 -08004107 for (final NetworkRequest req : nri.mRequests) {
4108 mNetworkRequests.remove(req);
4109 if (req.isListen()) {
4110 removeListenRequestFromNetworks(req);
4111 }
4112 }
Chalard Jean07dc1862021-03-01 22:08:57 +09004113 if (mDefaultNetworkRequests.remove(nri)) {
4114 // If this request was one of the defaults, then the UID rules need to be updated
4115 // WARNING : if the app(s) for which this network request is the default are doing
4116 // traffic, this will kill their connected sockets, even if an equivalent request
4117 // is going to be reinstated right away ; unconnected traffic will go on the default
4118 // until the new default is set, which will happen very soon.
4119 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4120 // remove ranges for those requests that won't have a replacement
4121 final NetworkAgentInfo satisfier = nri.getSatisfier();
4122 if (null != satisfier) {
4123 try {
4124 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4125 toUidRangeStableParcels(nri.getUids()));
4126 } catch (RemoteException e) {
4127 loge("Exception setting network preference default network", e);
4128 }
4129 }
4130 }
Chalard Jean70b2d9a2021-04-01 16:41:04 +09004131 nri.decrementRequestCount();
Erik Klineaec3f5e2016-07-07 16:50:58 +09004132 mNetworkRequestInfoLogs.log("RELEASE " + nri);
James Mattis622428c2020-12-02 14:12:41 -08004133
4134 if (null != nri.getActiveRequest()) {
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09004135 if (!nri.getActiveRequest().isListen()) {
James Mattis622428c2020-12-02 14:12:41 -08004136 removeSatisfiedNetworkRequestFromNetwork(nri);
4137 } else {
4138 nri.setSatisfier(null, null);
4139 }
4140 }
4141
Chalard Jean7b6a33b2021-01-12 10:58:56 +09004142 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4143 // needed for this offer.
4144 for (final NetworkOfferInfo noi : mNetworkOffers) {
4145 for (final NetworkRequest req : nri.mRequests) {
4146 if (req.isRequest() && noi.offer.neededFor(req)) {
4147 noi.offer.onNetworkUnneeded(req);
4148 }
4149 }
4150 }
James Mattis622428c2020-12-02 14:12:41 -08004151 }
4152
James Mattise494cbb2021-02-09 18:18:28 -08004153 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4154 for (final NetworkRequestInfo nri : nris) {
4155 if (mDefaultRequest == nri) {
4156 // Make sure we never remove the default request.
4157 continue;
4158 }
4159 handleRemoveNetworkRequest(nri);
4160 }
4161 }
4162
James Mattis622428c2020-12-02 14:12:41 -08004163 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4164 // listens don't have a singular affected Network. Check all networks to see
4165 // if this listen request applies and remove it.
4166 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4167 nai.removeRequest(req.requestId);
4168 if (req.networkCapabilities.hasSignalStrength()
4169 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4170 updateSignalStrengthThresholds(nai, "RELEASE", req);
4171 }
4172 }
4173 }
4174
4175 /**
4176 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4177 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4178 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4179 */
4180 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4181 boolean wasKept = false;
4182 final NetworkAgentInfo nai = nri.getSatisfier();
4183 if (nai != null) {
4184 final int requestLegacyType = nri.getActiveRequest().legacyType;
4185 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4186 nai.removeRequest(nri.getActiveRequest().requestId);
4187 if (VDBG || DDBG) {
4188 log(" Removing from current network " + nai.toShortString()
4189 + ", leaving " + nai.numNetworkRequests() + " requests.");
4190 }
4191 // If there are still lingered requests on this network, don't tear it down,
4192 // but resume lingering instead.
4193 final long now = SystemClock.elapsedRealtime();
junyulai2a4f0062021-02-03 20:15:30 +08004194 if (updateInactivityState(nai, now)) {
James Mattis622428c2020-12-02 14:12:41 -08004195 notifyNetworkLosing(nai, now);
4196 }
4197 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4198 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4199 teardownUnneededNetwork(nai);
4200 } else {
4201 wasKept = true;
4202 }
4203 nri.setSatisfier(null, null);
4204 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4205 // Went from foreground to background.
4206 updateCapabilitiesForNetwork(nai);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004207 }
4208
Erik Klineaec3f5e2016-07-07 16:50:58 +09004209 // Maintain the illusion. When this request arrived, we might have pretended
4210 // that a network connected to serve it, even though the network was already
4211 // connected. Now that this request has gone away, we might have to pretend
4212 // that the network disconnected. LegacyTypeTracker will generate that
4213 // phantom disconnect for this type.
James Mattis622428c2020-12-02 14:12:41 -08004214 if (requestLegacyType != TYPE_NONE) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004215 boolean doRemove = true;
4216 if (wasKept) {
4217 // check if any of the remaining requests for this network are for the
4218 // same legacy type - if so, don't remove the nai
4219 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4220 NetworkRequest otherRequest = nai.requestAt(i);
James Mattis622428c2020-12-02 14:12:41 -08004221 if (otherRequest.legacyType == requestLegacyType
4222 && otherRequest.isRequest()) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004223 if (DBG) log(" still have other legacy request - leaving");
4224 doRemove = false;
Robert Greenwaltb0491bb2015-01-08 14:43:31 -08004225 }
4226 }
Robert Greenwaltbc5794d2014-08-24 22:52:10 -07004227 }
4228
Erik Klineaec3f5e2016-07-07 16:50:58 +09004229 if (doRemove) {
James Mattis622428c2020-12-02 14:12:41 -08004230 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004231 }
4232 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004233 }
4234 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004235
Lorenzo Colittib4f8d8e2021-03-30 19:29:00 +09004236 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4237 return checkAnyPermissionOf(
4238 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4239 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4240 }
4241
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004242 @Override
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004243 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004244 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004245 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004246 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004247 }
4248
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004249 @Override
lucaslin25a50472019-03-12 13:08:03 +08004250 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4251 enforceNetworkStackSettingsOrSetup();
4252 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4253 encodeBool(accept), encodeBool(always), network));
4254 }
4255
4256 @Override
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004257 public void setAvoidUnvalidated(Network network) {
lucaslin25a50472019-03-12 13:08:03 +08004258 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004259 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4260 }
4261
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004262 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4263 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4264 " accept=" + accept + " always=" + always);
4265
4266 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4267 if (nai == null) {
4268 // Nothing to do.
4269 return;
4270 }
4271
4272 if (nai.everValidated) {
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004273 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004274 return;
4275 }
4276
Lorenzo Colitticf595362020-01-12 22:28:37 +09004277 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang11e9a312020-10-30 22:04:25 +08004278 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004279 }
4280
Lorenzo Colitticf595362020-01-12 22:28:37 +09004281 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4282 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin25a50472019-03-12 13:08:03 +08004283 // If network becomes partial connectivity and user already accepted to use this
4284 // network, we should respect the user's option and don't need to popup the
4285 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004286 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean1fc55292021-03-31 23:19:05 +09004287 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean60902092019-11-07 18:54:49 +09004288 rematchAllNetworksAndRequests();
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004289 }
4290
4291 if (always) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004292 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004293 }
4294
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004295 if (!accept) {
Paul Jensen4afac232015-07-13 15:19:51 -04004296 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004297 nai.onPreventAutomaticReconnect();
Chalard Jean73d9db72018-06-04 16:52:49 +09004298 // Teardown the network.
Paul Jensen4afac232015-07-13 15:19:51 -04004299 teardownUnneededNetwork(nai);
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004300 }
4301
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004302 }
4303
lucaslin25a50472019-03-12 13:08:03 +08004304 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4305 boolean always) {
4306 if (DBG) {
4307 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4308 + " always=" + always);
4309 }
4310
4311 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4312 if (nai == null) {
4313 // Nothing to do.
4314 return;
4315 }
4316
4317 if (nai.lastValidated) {
4318 // The network validated while the dialog box was up. Take no action.
4319 return;
4320 }
4321
Lorenzo Colitticf595362020-01-12 22:28:37 +09004322 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4323 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin25a50472019-03-12 13:08:03 +08004324 }
4325
4326 // TODO: Use the current design or save the user choice into IpMemoryStore.
4327 if (always) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004328 nai.onSaveAcceptUnvalidated(accept);
lucaslin25a50472019-03-12 13:08:03 +08004329 }
4330
4331 if (!accept) {
4332 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004333 nai.onPreventAutomaticReconnect();
lucaslin25a50472019-03-12 13:08:03 +08004334 // Tear down the network.
4335 teardownUnneededNetwork(nai);
4336 } else {
lucaslin2afb4bc2019-03-20 18:21:59 +08004337 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4338 // result in a partial connectivity result which will be processed by
4339 // maybeHandleNetworkMonitorMessage.
Chiachang Wang9cfa6fe2019-05-23 16:29:30 +08004340 //
4341 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4342 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004343 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin25a50472019-03-12 13:08:03 +08004344 }
4345 }
4346
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004347 private void handleSetAvoidUnvalidated(Network network) {
4348 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4349 if (nai == null || nai.lastValidated) {
4350 // Nothing to do. The network either disconnected or revalidated.
4351 return;
4352 }
4353 if (!nai.avoidUnvalidated) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004354 nai.avoidUnvalidated = true;
Chalard Jean1fc55292021-03-31 23:19:05 +09004355 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean60902092019-11-07 18:54:49 +09004356 rematchAllNetworksAndRequests();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004357 }
4358 }
4359
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004360 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09004361 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004362 mHandler.sendMessageDelayed(
4363 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4364 PROMPT_UNVALIDATED_DELAY_MS);
4365 }
4366
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004367 @Override
4368 public void startCaptivePortalApp(Network network) {
paulhud70b7dd2019-08-12 16:25:11 +08004369 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004370 mHandler.post(() -> {
4371 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4372 if (nai == null) return;
4373 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004374 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004375 });
4376 }
4377
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004378 /**
4379 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4380 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004381 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004382 * @param appExtras Bundle to use as intent extras for the captive portal application.
4383 * Must be treated as opaque to avoid preventing the captive portal app to
4384 * update its arguments.
4385 */
4386 @Override
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004387 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhud203f7a2019-05-14 14:17:44 +08004388 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4389 "ConnectivityService");
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004390
4391 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4392 appIntent.putExtras(appExtras);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004393 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4394 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004395 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4396
lucaslin86086772020-12-17 04:14:35 +08004397 final long token = Binder.clearCallingIdentity();
4398 try {
4399 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4400 } finally {
4401 Binder.restoreCallingIdentity(token);
4402 }
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004403 }
4404
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004405 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4406 private final Network mNetwork;
4407
4408 private CaptivePortalImpl(Network network) {
4409 mNetwork = network;
4410 }
4411
4412 @Override
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004413 public void appResponse(final int response) {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004414 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4415 enforceSettingsPermission();
4416 }
4417
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004418 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004419 if (nm == null) return;
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004420 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004421 }
4422
4423 @Override
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004424 public void appRequest(final int request) {
4425 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4426 if (nm == null) return;
4427
4428 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wang1fa770d2020-02-12 13:44:50 +08004429 checkNetworkStackPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09004430 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004431 }
4432 }
4433
4434 @Nullable
4435 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4436 // getNetworkAgentInfoForNetwork is thread-safe
4437 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4438 if (nai == null) return null;
4439
4440 // nai.networkMonitor() is thread-safe
4441 return nai.networkMonitor();
4442 }
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004443 }
4444
Hugo Benichi4fc79c42016-09-14 23:23:08 +00004445 public boolean avoidBadWifi() {
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004446 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti49d32fe2016-09-16 23:43:38 +09004447 }
4448
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004449 /**
4450 * Return whether the device should maintain continuous, working connectivity by switching away
4451 * from WiFi networks having no connectivity.
4452 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4453 */
4454 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004455 if (!checkNetworkStackPermission()) {
4456 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4457 }
4458 return avoidBadWifi();
4459 }
4460
Chalard Jean78515442021-03-19 13:49:56 +09004461 private void updateAvoidBadWifi() {
4462 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean1fc55292021-03-31 23:19:05 +09004463 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean78515442021-03-19 13:49:56 +09004464 }
Chalard Jean60902092019-11-07 18:54:49 +09004465 rematchAllNetworksAndRequests();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004466 }
4467
Erik Klinefc52be92016-10-02 18:02:14 +09004468 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004469 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004470 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004471 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004472 if (!configRestrict) {
4473 pw.println("Bad Wi-Fi avoidance: unrestricted");
4474 return;
4475 }
4476
4477 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4478 pw.increaseIndent();
4479 pw.println("Config restrict: " + configRestrict);
4480
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004481 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004482 String description;
4483 // Can't use a switch statement because strings are legal case labels, but null is not.
4484 if ("0".equals(value)) {
4485 description = "get stuck";
4486 } else if (value == null) {
4487 description = "prompt";
4488 } else if ("1".equals(value)) {
4489 description = "avoid";
4490 } else {
4491 description = value + " (?)";
4492 }
4493 pw.println("User setting: " + description);
4494 pw.println("Network overrides:");
4495 pw.increaseIndent();
Hugo Benichi821785c2018-09-03 08:19:02 +09004496 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004497 if (nai.avoidUnvalidated) {
Chalard Jean373391b2019-12-10 21:07:02 +09004498 pw.println(nai.toShortString());
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004499 }
4500 }
4501 pw.decreaseIndent();
4502 pw.decreaseIndent();
4503 }
4504
paulhu68426192020-06-09 19:07:03 +08004505 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4506 // unify the method.
4507 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4508 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4509 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4510 return settingsComponent != null
4511 ? settingsComponent.getPackageName() : "com.android.settings";
4512 }
4513
lucaslin1ac72392019-01-24 15:55:30 +08004514 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004515 final String action;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004516 final boolean highPriority;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004517 switch (type) {
4518 case NO_INTERNET:
4519 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004520 // High priority because it is only displayed for explicitly selected networks.
4521 highPriority = true;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004522 break;
lucaslin8cf57f52019-10-22 18:27:33 +08004523 case PRIVATE_DNS_BROKEN:
4524 action = Settings.ACTION_WIRELESS_SETTINGS;
4525 // High priority because we should let user know why there is no internet.
4526 highPriority = true;
4527 break;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004528 case LOST_INTERNET:
4529 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004530 // High priority because it could help the user avoid unexpected data usage.
4531 highPriority = true;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004532 break;
lucaslin25a50472019-03-12 13:08:03 +08004533 case PARTIAL_CONNECTIVITY:
4534 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004535 // Don't bother the user with a high-priority notification if the network was not
4536 // explicitly selected by the user.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004537 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin25a50472019-03-12 13:08:03 +08004538 break;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004539 default:
Aaron Huang11e9a312020-10-30 22:04:25 +08004540 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004541 return;
4542 }
4543
4544 Intent intent = new Intent(action);
lucaslin5cba3142020-02-20 16:56:59 +08004545 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wangef52aad2021-03-18 16:20:27 +08004546 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslin1ac72392019-01-24 15:55:30 +08004547 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu68426192020-06-09 19:07:03 +08004548 // Some OEMs have their own Settings package. Thus, need to get the current using
4549 // Settings package name instead of just use default name "com.android.settings".
4550 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4551 intent.setClassName(settingsPkgName,
4552 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslin1ac72392019-01-24 15:55:30 +08004553 }
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004554
paulhufea8f292020-10-11 22:52:27 +08004555 PendingIntent pendingIntent = PendingIntent.getActivity(
4556 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu68426192020-06-09 19:07:03 +08004557 0 /* requestCode */,
4558 intent,
paulhufea8f292020-10-11 22:52:27 +08004559 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004560
Serik Beketayev284cb872020-12-07 22:43:07 -08004561 mNotifier.showNotification(
4562 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004563 }
4564
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004565 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4566 // Don't prompt if the network is validated, and don't prompt on captive portals
4567 // because we're already prompting the user to sign in.
4568 if (nai.everValidated || nai.everCaptivePortalDetected) {
4569 return false;
4570 }
4571
4572 // If a network has partial connectivity, always prompt unless the user has already accepted
4573 // partial connectivity and selected don't ask again. This ensures that if the device
4574 // automatically connects to a network that has partial Internet access, the user will
4575 // always be able to use it, either because they've already chosen "don't ask again" or
4576 // because we have prompt them.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004577 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004578 return true;
4579 }
4580
4581 // If a network has no Internet access, only prompt if the network was explicitly selected
4582 // and if the user has not already told us to use the network regardless of whether it
4583 // validated or not.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004584 if (nai.networkAgentConfig.explicitlySelected
4585 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004586 return true;
4587 }
4588
4589 return false;
4590 }
4591
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004592 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09004593 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004594 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4595
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004596 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004597 return;
4598 }
Lorenzo Colitti50501802019-05-30 16:24:31 +09004599
4600 // Stop automatically reconnecting to this network in the future. Automatically connecting
4601 // to a network that provides no or limited connectivity is not useful, because the user
4602 // cannot use that network except through the notification shown by this method, and the
4603 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004604 nai.onPreventAutomaticReconnect();
Lorenzo Colitti50501802019-05-30 16:24:31 +09004605
lucaslin25a50472019-03-12 13:08:03 +08004606 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4607 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4608 // popup the notification immediately when the network is partial connectivity.
4609 if (nai.partialConnectivity) {
lucaslin32ecfc42019-03-21 11:59:22 +08004610 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin25a50472019-03-12 13:08:03 +08004611 } else {
4612 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4613 }
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004614 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004615
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004616 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4617 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean373391b2019-12-10 21:07:02 +09004618 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5447c492016-05-23 16:33:16 -07004619
lucaslin25a50472019-03-12 13:08:03 +08004620 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4621 return;
4622 }
4623
4624 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslin1ac72392019-01-24 15:55:30 +08004625 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004626 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004627 }
4628
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004629 @Override
4630 public int getMultipathPreference(Network network) {
4631 enforceAccessPermission();
4632
4633 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey41a72692017-07-12 10:50:42 -06004634 if (nai != null && nai.networkCapabilities
4635 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004636 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4637 }
4638
Aaron Huang5301b6f2020-12-08 10:03:29 +08004639 final NetworkPolicyManager netPolicyManager =
4640 mContext.getSystemService(NetworkPolicyManager.class);
4641
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09004642 final long token = Binder.clearCallingIdentity();
4643 final int networkPreference;
4644 try {
4645 networkPreference = netPolicyManager.getMultipathPreference(network);
4646 } finally {
4647 Binder.restoreCallingIdentity(token);
4648 }
Aaron Huang5301b6f2020-12-08 10:03:29 +08004649 if (networkPreference != 0) {
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09004650 return networkPreference;
4651 }
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004652 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4653 }
4654
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004655 @Override
4656 public NetworkRequest getDefaultRequest() {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004657 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004658 }
4659
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004660 private class InternalHandler extends Handler {
4661 public InternalHandler(Looper looper) {
4662 super(looper);
4663 }
4664
4665 @Override
4666 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004667 switch (msg.what) {
Robert Greenwalt61837eb2014-06-25 16:45:57 -07004668 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004669 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi58aab552017-03-30 23:18:10 +09004670 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004671 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004672 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004673 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean9fbd93c2018-06-08 14:24:49 +09004674 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004675 break;
4676 }
Jason Monk445cea82013-10-10 14:02:51 -04004677 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangb2ad4a92021-01-18 15:28:01 +08004678 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4679 handleApplyDefaultProxy(arg.second);
Jason Monk445cea82013-10-10 14:02:51 -04004680 break;
4681 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09004682 case EVENT_REGISTER_NETWORK_PROVIDER: {
4683 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07004684 break;
4685 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09004686 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4687 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt948aea52014-04-11 15:53:27 -07004688 break;
4689 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09004690 case EVENT_REGISTER_NETWORK_OFFER: {
4691 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4692 break;
4693 }
4694 case EVENT_UNREGISTER_NETWORK_OFFER: {
4695 final NetworkOfferInfo offer =
4696 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4697 if (null != offer) {
4698 handleUnregisterNetworkOffer(offer);
4699 }
4700 break;
4701 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004702 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004703 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4704 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4705 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004706 break;
4707 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004708 case EVENT_REGISTER_NETWORK_REQUEST:
4709 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline74d68ef2015-04-30 12:58:40 +09004710 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004711 break;
4712 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004713 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4714 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin94c30992014-11-05 10:32:09 -08004715 handleRegisterNetworkRequestWithIntent(msg);
4716 break;
4717 }
Erik Kline66721822015-11-25 12:49:38 +09004718 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4719 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4720 handleTimedOutNetworkRequest(nri);
4721 break;
4722 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004723 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4724 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4725 break;
4726 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004727 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohen06633de2019-01-08 12:09:18 -08004728 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4729 /* callOnUnavailable */ false);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004730 break;
4731 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004732 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004733 Network network = (Network) msg.obj;
4734 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004735 break;
4736 }
lucaslin25a50472019-03-12 13:08:03 +08004737 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4738 Network network = (Network) msg.obj;
4739 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4740 toBool(msg.arg2));
4741 break;
4742 }
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004743 case EVENT_SET_AVOID_UNVALIDATED: {
4744 handleSetAvoidUnvalidated((Network) msg.obj);
4745 break;
4746 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004747 case EVENT_PROMPT_UNVALIDATED: {
4748 handlePromptUnvalidated((Network) msg.obj);
4749 break;
4750 }
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07004751 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4752 handleConfigureAlwaysOnNetworks();
Erik Kline74d68ef2015-04-30 12:58:40 +09004753 break;
4754 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004755 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai21c06d02019-01-03 18:50:15 +08004756 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004757 mKeepaliveTracker.handleStartKeepalive(msg);
4758 break;
4759 }
4760 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai21c06d02019-01-03 18:50:15 +08004761 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004762 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4763 int slot = msg.arg1;
4764 int reason = msg.arg2;
4765 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4766 break;
4767 }
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004768 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004769 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004770 break;
4771 }
Erik Klinec06d4f92018-01-11 21:07:29 +09004772 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4773 handlePrivateDnsSettingsChanged();
4774 break;
dalykf4977492018-03-05 12:42:22 -05004775 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4776 handlePrivateDnsValidationUpdate(
4777 (PrivateDnsValidationUpdate) msg.obj);
4778 break;
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00004779 case EVENT_UID_BLOCKED_REASON_CHANGED:
4780 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulai5ab727b2018-08-07 19:50:45 +08004781 break;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09004782 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4783 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4784 break;
Chalard Jeandc974072021-03-01 22:00:20 +09004785 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jeancc9ad152021-03-03 16:37:13 +09004786 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4787 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jeandc974072021-03-01 22:00:20 +09004788 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis6e6fabf2021-01-10 14:24:24 -08004789 break;
Chalard Jeandc974072021-03-01 22:00:20 +09004790 }
Chalard Jean9d968182021-02-25 21:46:34 +09004791 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4792 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4793 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4794 msg.obj;
4795 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhu339d9be2021-05-05 11:04:59 +08004796 break;
Chalard Jean9d968182021-02-25 21:46:34 +09004797 }
lucaslina5e9bdb2021-01-21 02:04:15 +08004798 case EVENT_REPORT_NETWORK_ACTIVITY:
4799 mNetworkActivityTracker.handleReportNetworkActivity();
4800 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004801 }
4802 }
4803 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004804
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004805 @Override
markchien4f949812019-12-16 20:15:20 +08004806 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004807 public int getLastTetherError(String iface) {
markchien4f949812019-12-16 20:15:20 +08004808 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4809 Context.TETHERING_SERVICE);
4810 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004811 }
4812
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004813 @Override
markchien4f949812019-12-16 20:15:20 +08004814 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004815 public String[] getTetherableIfaces() {
markchien4f949812019-12-16 20:15:20 +08004816 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4817 Context.TETHERING_SERVICE);
4818 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004819 }
4820
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004821 @Override
markchien4f949812019-12-16 20:15:20 +08004822 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004823 public String[] getTetheredIfaces() {
markchien4f949812019-12-16 20:15:20 +08004824 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4825 Context.TETHERING_SERVICE);
4826 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004827 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004828
markchien4f949812019-12-16 20:15:20 +08004829
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004830 @Override
markchien4f949812019-12-16 20:15:20 +08004831 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004832 public String[] getTetheringErroredIfaces() {
markchien4f949812019-12-16 20:15:20 +08004833 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4834 Context.TETHERING_SERVICE);
4835
4836 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004837 }
4838
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004839 @Override
markchien4f949812019-12-16 20:15:20 +08004840 @Deprecated
4841 public String[] getTetherableUsbRegexs() {
4842 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4843 Context.TETHERING_SERVICE);
4844
4845 return tm.getTetherableUsbRegexs();
Robert Greenwalta75c4652014-06-23 14:53:42 -07004846 }
4847
Udam Saini15072332017-06-07 12:06:28 -07004848 @Override
markchien4f949812019-12-16 20:15:20 +08004849 @Deprecated
4850 public String[] getTetherableWifiRegexs() {
4851 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4852 Context.TETHERING_SERVICE);
4853 return tm.getTetherableWifiRegexs();
markchiena005c992019-02-27 14:56:11 +08004854 }
4855
Robert Greenwalt205fd8e2014-07-02 09:59:16 -07004856 // Called when we lose the default network and have no replacement yet.
4857 // This will automatically be cleared after X seconds or a new default network
4858 // becomes CONNECTED, whichever happens first. The timer is started by the
4859 // first caller and not restarted by subsequent callers.
Hugo Benichi58aab552017-03-30 23:18:10 +09004860 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004861 synchronized (this) {
Hugo Benichi58aab552017-03-30 23:18:10 +09004862 if (mNetTransitionWakeLock.isHeld()) {
4863 return;
4864 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004865 mNetTransitionWakeLock.acquire();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09004866 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4867 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004868 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004869 mWakelockLogs.log("ACQUIRE for " + forWhom);
4870 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09004871 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09004872 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09004873 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004874 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07004875
Hugo Benichi58aab552017-03-30 23:18:10 +09004876 // Called when we gain a new default network to release the network transition wakelock in a
4877 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4878 // message is cancelled.
4879 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004880 synchronized (this) {
Hugo Benichi58aab552017-03-30 23:18:10 +09004881 if (!mNetTransitionWakeLock.isHeld()) {
4882 return; // expiry message released the lock first.
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004883 }
4884 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004885 // Cancel self timeout on wakelock hold.
4886 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4887 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4888 mHandler.sendMessageDelayed(msg, 1000);
4889 }
4890
4891 // Called when either message of ensureNetworkTransitionWakelock or
4892 // scheduleReleaseNetworkTransitionWakelock is processed.
4893 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4894 String event = eventName(eventId);
4895 synchronized (this) {
4896 if (!mNetTransitionWakeLock.isHeld()) {
4897 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang11e9a312020-10-30 22:04:25 +08004898 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi58aab552017-03-30 23:18:10 +09004899 return;
4900 }
4901 mNetTransitionWakeLock.release();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09004902 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4903 mTotalWakelockDurationMs += lockDuration;
4904 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4905 mTotalWakelockReleases++;
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004906 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004907 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004908 }
4909
Robert Greenwalt986c7412010-09-08 15:24:47 -07004910 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004911 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07004912 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltb264cd82014-08-06 21:32:18 -07004913 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittibdda6bf2015-02-11 07:39:20 +09004914 if (nai == null) return;
Paul Jensen7aac1b32015-04-07 12:43:13 -04004915 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07004916 }
4917
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004918 @Override
Paul Jensen7aac1b32015-04-07 12:43:13 -04004919 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen57d231c2014-08-29 09:54:01 -04004920 enforceAccessPermission();
4921 enforceInternetPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09004922 final int uid = mDeps.getCallingUid();
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004923 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kestinga58c07c2020-01-07 11:18:54 -08004924
Cody Kestingb0174782020-06-25 11:13:39 -07004925 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4926 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4927 // does not match the known connectivity of the network - this causes NetworkMonitor to
4928 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
Cody Kestinga58c07c2020-01-07 11:18:54 -08004929 final NetworkAgentInfo nai;
4930 if (network == null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004931 nai = getDefaultNetwork();
Cody Kestinga58c07c2020-01-07 11:18:54 -08004932 } else {
4933 nai = getNetworkAgentInfoForNetwork(network);
4934 }
4935 if (nai != null) {
4936 mConnectivityDiagnosticsHandler.sendMessage(
4937 mConnectivityDiagnosticsHandler.obtainMessage(
4938 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4939 connectivityInfo, 0, nai));
4940 }
Cody Kestingb0174782020-06-25 11:13:39 -07004941
4942 mHandler.sendMessage(
4943 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004944 }
Paul Jensen57d231c2014-08-29 09:54:01 -04004945
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004946 private void handleReportNetworkConnectivity(
4947 Network network, int uid, boolean hasConnectivity) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09004948 final NetworkAgentInfo nai;
Paul Jensen7aac1b32015-04-07 12:43:13 -04004949 if (network == null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004950 nai = getDefaultNetwork();
Paul Jensen7aac1b32015-04-07 12:43:13 -04004951 } else {
4952 nai = getNetworkAgentInfoForNetwork(network);
4953 }
Paul Jensen773f4f32015-06-25 10:28:34 -04004954 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4955 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4956 return;
4957 }
Paul Jensen7aac1b32015-04-07 12:43:13 -04004958 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9a35d82017-04-06 16:01:44 +09004959 if (hasConnectivity == nai.lastValidated) {
4960 return;
4961 }
Paul Jensen7aac1b32015-04-07 12:43:13 -04004962 if (DBG) {
Serik Beketayev284cb872020-12-07 22:43:07 -08004963 int netid = nai.network.getNetId();
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004964 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensen7aac1b32015-04-07 12:43:13 -04004965 }
Hugo Benichie9a35d82017-04-06 16:01:44 +09004966 // Validating a network that has not yet connected could result in a call to
4967 // rematchNetworkAndRequests() which is not meant to work on such networks.
4968 if (!nai.everConnected) {
4969 return;
Paul Jensen57d231c2014-08-29 09:54:01 -04004970 }
paulhu3b063e32020-12-30 00:42:19 +08004971 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
4972 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09004973 return;
4974 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004975 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004976 }
4977
Lorenzo Colittid81932b2021-03-23 21:01:07 +09004978 // TODO: call into netd.
4979 private boolean queryUserAccess(int uid, Network network) {
4980 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4981 if (nai == null) return false;
4982
4983 // Any UID can use its default network.
4984 if (nai == getDefaultNetworkForUid(uid)) return true;
4985
4986 // Privileged apps can use any network.
4987 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
4988 return true;
4989 }
4990
4991 // An unprivileged UID can use a VPN iff the VPN applies to it.
4992 if (nai.isVPN()) {
4993 return nai.networkCapabilities.appliesToUid(uid);
4994 }
4995
4996 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
4997 // sockets, i.e., if it is the owner.
4998 final NetworkAgentInfo vpn = getVpnForUid(uid);
4999 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5000 && uid != vpn.networkCapabilities.getOwnerUid()) {
5001 return false;
5002 }
5003
5004 // The UID's permission must be at least sufficient for the network. Since the restricted
5005 // permission was already checked above, that just leaves background networks.
5006 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5007 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5008 }
5009
5010 // Unrestricted network. Anyone gets to use it.
5011 return true;
5012 }
5013
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005014 /**
5015 * Returns information about the proxy a certain network is using. If given a null network, it
5016 * it will return the proxy for the bound network for the caller app or the default proxy if
5017 * none.
5018 *
5019 * @param network the network we want to get the proxy information for.
5020 * @return Proxy information if a network has a proxy configured, or otherwise null.
5021 */
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09005022 @Override
Paul Jensenfdec88b2015-05-06 07:32:40 -04005023 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean626c0122018-06-07 18:02:37 +09005024 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensenfdec88b2015-05-06 07:32:40 -04005025 if (globalProxy != null) return globalProxy;
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005026 if (network == null) {
5027 // Get the network associated with the calling UID.
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005028 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005029 true);
5030 if (activeNetwork == null) {
5031 return null;
5032 }
5033 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colittid81932b2021-03-23 21:01:07 +09005034 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005035 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5036 // caller may not have.
5037 return getLinkPropertiesProxyInfo(network);
5038 }
5039 // No proxy info available if the calling UID does not have network access.
5040 return null;
5041 }
5042
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005043
5044 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensenfdec88b2015-05-06 07:32:40 -04005045 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5046 if (nai == null) return null;
5047 synchronized (nai) {
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005048 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5049 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensenfdec88b2015-05-06 07:32:40 -04005050 }
5051 }
5052
Chalard Jean850c29e2018-06-07 18:37:59 +09005053 @Override
Chalard Jeanaac3b872021-03-17 17:03:34 +09005054 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu5e094422021-01-25 18:53:17 +08005055 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean850c29e2018-06-07 18:37:59 +09005056 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005057 }
5058
Chalard Jean626c0122018-06-07 18:02:37 +09005059 @Override
5060 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04005061 public ProxyInfo getGlobalProxy() {
Chalard Jean626c0122018-06-07 18:02:37 +09005062 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005063 }
5064
Jason Monk1e3df5d2014-04-25 15:00:09 -04005065 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04005066 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard21523a42014-11-20 14:35:32 -05005067 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005068 proxy = null;
5069 }
Chalard Jeanbbd62a02018-06-08 12:20:15 +09005070 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005071 }
5072
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005073 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5074 // when any network changes proxy.
5075 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5076 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005077 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensen12131352014-12-10 15:12:18 -05005078 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5079 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5080
Chalard Jean80b334a2018-06-07 17:41:29 +09005081 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean07c5bab2018-06-08 19:46:44 +09005082 mProxyTracker.sendProxyBroadcast();
Paul Jensen12131352014-12-10 15:12:18 -05005083 }
5084 }
5085
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005086 private static class SettingsObserver extends ContentObserver {
Erik Kline74d68ef2015-04-30 12:58:40 +09005087 final private HashMap<Uri, Integer> mUriEventMap;
5088 final private Context mContext;
5089 final private Handler mHandler;
5090
5091 SettingsObserver(Context context, Handler handler) {
5092 super(null);
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005093 mUriEventMap = new HashMap<>();
Erik Kline74d68ef2015-04-30 12:58:40 +09005094 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005095 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005096 }
5097
Erik Kline74d68ef2015-04-30 12:58:40 +09005098 void observe(Uri uri, int what) {
5099 mUriEventMap.put(uri, what);
5100 final ContentResolver resolver = mContext.getContentResolver();
5101 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005102 }
5103
5104 @Override
5105 public void onChange(boolean selfChange) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005106 Log.wtf(TAG, "Should never be reached.");
Erik Kline74d68ef2015-04-30 12:58:40 +09005107 }
5108
5109 @Override
5110 public void onChange(boolean selfChange, Uri uri) {
5111 final Integer what = mUriEventMap.get(uri);
5112 if (what != null) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09005113 mHandler.obtainMessage(what).sendToTarget();
Erik Kline74d68ef2015-04-30 12:58:40 +09005114 } else {
5115 loge("No matching event to send for URI=" + uri);
5116 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005117 }
5118 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005119
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005120 private static void log(String s) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005121 Log.d(TAG, s);
5122 }
5123
5124 private static void logw(String s) {
5125 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005126 }
5127
Daniel Bright60f02ed2020-06-15 16:10:01 -07005128 private static void logwtf(String s) {
5129 Log.wtf(TAG, s);
5130 }
5131
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09005132 private static void logwtf(String s, Throwable t) {
5133 Log.wtf(TAG, s, t);
5134 }
5135
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005136 private static void loge(String s) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005137 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005138 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005139
Hugo Benichi0a28d302017-02-11 17:04:43 +09005140 private static void loge(String s, Throwable t) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005141 Log.e(TAG, s, t);
Hugo Benichi0a28d302017-02-11 17:04:43 +09005142 }
5143
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005144 /**
Varun Anand5e980f42019-02-07 14:13:13 -08005145 * Return the information of all ongoing VPNs.
5146 *
5147 * <p>This method is used to update NetworkStatsService.
5148 *
5149 * <p>Must be called on the handler thread.
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005150 */
junyulai62d35f72021-01-23 09:46:34 +08005151 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anand5e980f42019-02-07 14:13:13 -08005152 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005153 if (mLockdownEnabled) {
5154 return new UnderlyingNetworkInfo[0];
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005155 }
junyulai62d35f72021-01-23 09:46:34 +08005156 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colittia68139a2020-12-15 15:47:24 +09005157 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai62d35f72021-01-23 09:46:34 +08005158 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colittia68139a2020-12-15 15:47:24 +09005159 if (info != null) {
5160 infoList.add(info);
5161 }
5162 }
junyulai62d35f72021-01-23 09:46:34 +08005163 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005164 }
5165
5166 /**
5167 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wongb393d282019-06-12 17:46:15 +00005168 * information, e.g underlying ifaces.
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005169 */
junyulai62d35f72021-01-23 09:46:34 +08005170 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005171 if (!nai.isVPN()) return null;
5172
5173 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005174 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5175 // the underlyingNetworks list.
5176 if (underlyingNetworks == null) {
James Mattisf61f7be2021-01-31 17:06:19 -08005177 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5178 nai.networkCapabilities.getOwnerUid());
Benedict Wongb98e0692019-06-12 17:46:31 +00005179 if (defaultNai != null) {
Benedict Wongb393d282019-06-12 17:46:15 +00005180 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005181 }
5182 }
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005183
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005184 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005185
5186 List<String> interfaces = new ArrayList<>();
5187 for (Network network : underlyingNetworks) {
5188 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5189 if (underlyingNai == null) continue;
5190 LinkProperties lp = underlyingNai.linkProperties;
5191 for (String iface : lp.getAllInterfaceNames()) {
5192 if (!TextUtils.isEmpty(iface)) {
5193 interfaces.add(iface);
Benedict Wongb393d282019-06-12 17:46:15 +00005194 }
5195 }
Benedict Wongb393d282019-06-12 17:46:15 +00005196 }
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005197
5198 if (interfaces.isEmpty()) return null;
5199
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005200 // Must be non-null or NetworkStatsService will crash.
5201 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5202 // tun or ipsec interface is created.
junyulai62d35f72021-01-23 09:46:34 +08005203 // TODO: Remove this check.
junyulaibd7f3cd2021-01-23 01:09:11 +08005204 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005205
junyulai62d35f72021-01-23 09:46:34 +08005206 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5207 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005208 }
5209
James Mattis1238af22020-12-23 16:37:26 -08005210 // TODO This needs to be the default network that applies to the NAI.
James Mattisf61f7be2021-01-31 17:06:19 -08005211 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5212 Network[] underlyingNetworks) {
5213 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005214 if (underlyingNetworks == null && defaultNetwork != null) {
5215 // null underlying networks means to track the default.
5216 underlyingNetworks = new Network[] { defaultNetwork };
5217 }
5218 return underlyingNetworks;
5219 }
5220
5221 // Returns true iff |network| is an underlying network of |nai|.
5222 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5223 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5224 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5225 if (!nai.supportsUnderlyingNetworks()) return false;
James Mattisf61f7be2021-01-31 17:06:19 -08005226 final Network[] underlying = underlyingNetworksOrDefault(
5227 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005228 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005229 }
5230
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005231 /**
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005232 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005233 *
Lorenzo Colitti220987b2020-11-09 10:32:56 +09005234 * When underlying networks change, such networks may have to update capabilities to reflect
5235 * things like the metered bit, their transports, and so on. The capabilities are calculated
5236 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005237 */
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005238 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti220987b2020-11-09 10:32:56 +09005239 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005240 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005241 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09005242 updateCapabilitiesForNetwork(nai);
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005243 }
5244 }
5245 }
5246
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005247 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5248 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5249 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5250 // a VPN is not up.
5251 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5252 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5253 for (UidRange range : blockedUidRanges) {
5254 if (range.contains(uid)) return true;
5255 }
5256 return false;
5257 }
5258
5259 @Override
5260 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucaslin5140e482021-03-22 11:51:27 +08005261 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005262 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5263 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5264 }
5265
5266 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5267 if (DBG) {
5268 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5269 + Arrays.toString(ranges));
5270 }
5271 // Cannot use a Set since the list of UID ranges might contain duplicates.
5272 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5273 for (int i = 0; i < ranges.length; i++) {
5274 if (requireVpn) {
5275 newVpnBlockedUidRanges.add(ranges[i]);
5276 } else {
5277 newVpnBlockedUidRanges.remove(ranges[i]);
5278 }
5279 }
5280
5281 try {
5282 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5283 } catch (RemoteException | ServiceSpecificException e) {
5284 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5285 + Arrays.toString(ranges) + "): netd command failed: " + e);
5286 }
5287
5288 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5289 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00005290 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5291 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005292 }
5293
5294 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5295 }
5296
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07005297 @Override
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005298 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucaslin5140e482021-03-22 11:51:27 +08005299 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005300 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He729f0b42017-05-15 17:07:18 +01005301 }
5302
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005303 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5304 return mLockdownEnabled
5305 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5306 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Lee33c73e22016-01-05 18:03:46 +00005307 }
5308
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005309 private NetworkAgentInfo getLegacyLockdownNai() {
5310 if (!mLockdownEnabled) {
5311 return null;
Robin Lee33c73e22016-01-05 18:03:46 +00005312 }
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005313 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005314 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5315 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Lee33c73e22016-01-05 18:03:46 +00005316
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005317 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005318 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5319 // a local variable. There is no need to make a copy because its contents cannot change.
5320 final Network[] underlying = nai.declaredUnderlyingNetworks;
5321 if (underlying == null || underlying.length != 1) {
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005322 return null;
Pavel Grafov4753f402019-01-25 08:50:06 +00005323 }
Pavel Grafov4753f402019-01-25 08:50:06 +00005324
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005325 // The legacy lockdown VPN always uses the default network.
5326 // If the VPN's underlying network is no longer the current default network, it means that
5327 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005328 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5329 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005330 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005331 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005332 return null;
Pavel Grafov4753f402019-01-25 08:50:06 +00005333 }
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005334
5335 return nai;
5336 };
5337
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005338 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5339 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5340 // just a DetailedState object.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005341 private DetailedState getLegacyLockdownState(DetailedState origState) {
5342 if (origState != DetailedState.CONNECTED) {
5343 return origState;
5344 }
5345 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5346 ? DetailedState.CONNECTING
5347 : DetailedState.CONNECTED;
Pavel Grafov4753f402019-01-25 08:50:06 +00005348 }
5349
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005350 private void filterForLegacyLockdown(NetworkInfo ni) {
5351 if (!mLockdownEnabled || !ni.isConnected()) return;
5352 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5353 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5354 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5355 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5356 // network, this time with a state of CONNECTED.
5357 //
5358 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5359 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5360 // is not too far off the truth, since an always-on VPN, when not connected, is always
5361 // trying to reconnect.
5362 if (getLegacyLockdownNai() == null) {
5363 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5364 }
5365 }
5366
Pavel Grafov4753f402019-01-25 08:50:06 +00005367 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07005368 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04005369 String action) {
paulhud70b7dd2019-08-12 16:25:11 +08005370 enforceSettingsPermission();
Hugo Benichi37d5c3c2017-06-20 14:07:59 +09005371 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5372 return;
5373 }
Paul Jensen82c7e422014-09-15 15:59:36 -04005374 final long ident = Binder.clearCallingIdentity();
5375 try {
Lorenzo Colittieb166f42016-08-22 22:36:19 +09005376 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09005377 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittieb166f42016-08-22 22:36:19 +09005378 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen82c7e422014-09-15 15:59:36 -04005379 } finally {
5380 Binder.restoreCallingIdentity(ident);
5381 }
Wink Saville89c87b92013-08-29 08:55:16 -07005382 }
Wink Saville3ade4872013-08-29 14:57:08 -07005383
Yuhao Zheng15019892013-09-09 17:00:04 -07005384 @Override
5385 public void setAirplaneMode(boolean enable) {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01005386 enforceAirplaneModePermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07005387 final long ident = Binder.clearCallingIdentity();
5388 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07005389 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichi7f919fe2017-04-21 15:07:12 +09005390 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng82579362013-09-11 09:36:41 -07005391 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5392 intent.putExtra("state", enable);
xinhe51e77032014-11-17 11:35:01 -08005393 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng15019892013-09-09 17:00:04 -07005394 } finally {
5395 Binder.restoreCallingIdentity(ident);
5396 }
5397 }
5398
James Mattisbd275dc2021-03-13 19:27:21 -08005399 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005400 mPermissionMonitor.onUserAdded(user);
James Mattis3bf8b7a2021-03-01 17:09:11 -08005401 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5402 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5403 }
Fyodor Kupolov188d3bd2015-09-02 13:27:21 -07005404 }
5405
James Mattisbd275dc2021-03-13 19:27:21 -08005406 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005407 mPermissionMonitor.onUserRemoved(user);
Chalard Jean6bb468c2021-03-09 21:09:20 +09005408 // If there was a network preference for this user, remove it.
5409 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5410 null /* listener */);
James Mattis3bf8b7a2021-03-01 17:09:11 -08005411 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5412 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5413 }
junyulaib56dc512020-08-28 13:44:33 +08005414 }
5415
James Mattisbd275dc2021-03-13 19:27:21 -08005416 private void onPackageChanged(@NonNull final String packageName) {
5417 // This is necessary in case a package is added or removed, but also when it's replaced to
5418 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5419 // as one in the preferences, then it should follow the same routing as that other package,
5420 // which means updating the rules is never to be needed in this case (whether it joins or
5421 // leaves a UID with a preference).
5422 if (isMappedInOemNetworkPreference(packageName)) {
5423 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5424 }
5425 }
5426
5427 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerccae0d32013-06-14 11:16:51 -07005428 @Override
5429 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti37d17e62021-02-15 09:36:55 +09005430 ensureRunningOnConnectivityServiceThread();
Chad Brubakerccae0d32013-06-14 11:16:51 -07005431 final String action = intent.getAction();
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005432 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaib56dc512020-08-28 13:44:33 +08005433
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005434 // User should be filled for below intents, check the existence.
5435 if (user == null) {
5436 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5437 return;
5438 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07005439
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005440 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005441 onUserAdded(user);
Fyodor Kupolov188d3bd2015-09-02 13:27:21 -07005442 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005443 onUserRemoved(user);
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005444 } else {
junyulaib56dc512020-08-28 13:44:33 +08005445 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerccae0d32013-06-14 11:16:51 -07005446 }
5447 }
5448 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07005449
James Mattisbd275dc2021-03-13 19:27:21 -08005450 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5451 @Override
5452 public void onReceive(Context context, Intent intent) {
5453 ensureRunningOnConnectivityServiceThread();
5454 switch (intent.getAction()) {
5455 case Intent.ACTION_PACKAGE_ADDED:
5456 case Intent.ACTION_PACKAGE_REMOVED:
5457 case Intent.ACTION_PACKAGE_REPLACED:
5458 onPackageChanged(intent.getData().getSchemeSpecificPart());
5459 break;
5460 default:
5461 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5462 }
5463 }
5464 };
5465
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005466 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005467 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt948aea52014-04-11 15:53:27 -07005468
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005469 private static class NetworkProviderInfo {
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005470 public final String name;
5471 public final Messenger messenger;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005472 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005473 public final int providerId;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005474
lifr1c0d9b22021-03-10 13:58:14 +08005475 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5476 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005477 this.name = name;
5478 this.messenger = messenger;
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005479 this.providerId = providerId;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005480 mDeathRecipient = deathRecipient;
5481
Remi NGUYEN VAN773d9182021-02-04 18:04:43 +09005482 if (mDeathRecipient == null) {
5483 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005484 }
5485 }
5486
Lorenzo Colittia54a1aa2020-01-07 19:36:24 +09005487 void connect(Context context, Handler handler) {
Remi NGUYEN VAN773d9182021-02-04 18:04:43 +09005488 try {
5489 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5490 } catch (RemoteException e) {
5491 mDeathRecipient.binderDied();
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005492 }
Lorenzo Colittia54a1aa2020-01-07 19:36:24 +09005493 }
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005494 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005495
James Mattis3f93a312020-11-12 15:53:42 -08005496 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5497 for (int i = 0; i < requests.size(); i++) {
5498 ensureNetworkRequestHasType(requests.get(i));
5499 }
5500 }
5501
Lorenzo Colitticef9c492016-07-05 01:22:13 +09005502 private void ensureNetworkRequestHasType(NetworkRequest request) {
5503 if (request.type == NetworkRequest.Type.NONE) {
5504 throw new IllegalArgumentException(
5505 "All NetworkRequests in ConnectivityService must have a type");
5506 }
5507 }
5508
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005509 /**
5510 * Tracks info about the requester.
James Mattis08131f32020-12-13 16:28:14 -08005511 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005512 */
James Mattisf8eb49a2020-11-15 15:04:40 -08005513 @VisibleForTesting
5514 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattis8af2d602020-12-20 11:09:58 -08005515 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5516 // single NetworkRequest in mRequests.
James Mattis7835f742020-11-03 15:54:33 -08005517 final List<NetworkRequest> mRequests;
James Mattis7835f742020-11-03 15:54:33 -08005518
James Mattis622428c2020-12-02 14:12:41 -08005519 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5520 void setSatisfier(
5521 @Nullable final NetworkAgentInfo satisfier,
5522 @Nullable final NetworkRequest activeRequest) {
5523 mSatisfier = satisfier;
5524 mActiveRequest = activeRequest;
5525 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005526
James Mattis1238af22020-12-23 16:37:26 -08005527 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09005528 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeane8cf3bf2019-11-05 15:07:09 +09005529 @Nullable
James Mattis622428c2020-12-02 14:12:41 -08005530 private NetworkAgentInfo mSatisfier;
5531 NetworkAgentInfo getSatisfier() {
5532 return mSatisfier;
5533 }
5534
5535 // The request in mRequests assigned to a network agent. This is null if none of the
5536 // requests in mRequests can be satisfied. This member has the constraint of only being
5537 // accessible on the handler thread.
5538 @Nullable
5539 private NetworkRequest mActiveRequest;
5540 NetworkRequest getActiveRequest() {
5541 return mActiveRequest;
5542 }
5543
Jeremy Joslin94c30992014-11-05 10:32:09 -08005544 final PendingIntent mPendingIntent;
Jeremy Joslinb9846d02014-12-03 17:15:28 -08005545 boolean mPendingIntentSent;
James Mattis6e6fabf2021-01-10 14:24:24 -08005546 @Nullable
5547 final Messenger mMessenger;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005548
5549 // Information about the caller that caused this object to be created.
James Mattis6e6fabf2021-01-10 14:24:24 -08005550 @Nullable
Jeremy Joslin94c30992014-11-05 10:32:09 -08005551 private final IBinder mBinder;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005552 final int mPid;
5553 final int mUid;
Roshan Pius7992afd2020-12-22 15:10:42 -08005554 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusc97d8062020-12-17 14:53:09 -08005555 @Nullable
5556 final String mCallingAttributionTag;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005557
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005558 // Counter keeping track of this NRI.
5559 final PerUidCounter mPerUidCounter;
5560
Lorenzo Colittif2514122021-03-12 22:50:57 +09005561 // Effective UID of this request. This is different from mUid when a privileged process
5562 // files a request on behalf of another UID. This UID is used to determine blocked status,
5563 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5564 // maximum limit of registered callbacks per UID.
5565 final int mAsUid;
5566
James Mattise494cbb2021-02-09 18:18:28 -08005567 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5568 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5569 // maintained for keying off of. This is only a concern when the original nri
5570 // mNetworkRequests changes which happens currently for apps that register callbacks to
5571 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5572 // that match the per-app default nri that currently tracks the calling app's uid so that
5573 // callbacks are fired at the appropriate time. When the callbacks fire,
5574 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5575 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5576 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5577 @NonNull
5578 private final NetworkRequest mNetworkRequestForCallback;
5579 NetworkRequest getNetworkRequestForCallback() {
5580 return mNetworkRequestForCallback;
5581 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005582
James Mattis1238af22020-12-23 16:37:26 -08005583 /**
5584 * Get the list of UIDs this nri applies to.
5585 */
5586 @NonNull
5587 private Set<UidRange> getUids() {
5588 // networkCapabilities.getUids() returns a defensive copy.
5589 // multilayer requests will all have the same uids so return the first one.
Chiachang Wangd5034c72021-02-22 18:36:38 +08005590 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5591 return (null == uids) ? new ArraySet<>() : uids;
James Mattis1238af22020-12-23 16:37:26 -08005592 }
5593
Lorenzo Colittif2514122021-03-12 22:50:57 +09005594 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5595 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5596 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
James Mattis6e6fabf2021-01-10 14:24:24 -08005597 }
5598
Lorenzo Colittif2514122021-03-12 22:50:57 +09005599 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattise494cbb2021-02-09 18:18:28 -08005600 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5601 @Nullable String callingAttributionTag) {
5602 ensureAllNetworkRequestsHaveType(r);
James Mattis7835f742020-11-03 15:54:33 -08005603 mRequests = initializeRequests(r);
James Mattise494cbb2021-02-09 18:18:28 -08005604 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005605 mPendingIntent = pi;
James Mattis6e6fabf2021-01-10 14:24:24 -08005606 mMessenger = null;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005607 mBinder = null;
5608 mPid = getCallingPid();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005609 mUid = mDeps.getCallingUid();
Lorenzo Colittif2514122021-03-12 22:50:57 +09005610 mAsUid = asUid;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005611 mPerUidCounter = getRequestCounter(this);
5612 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005613 /**
5614 * Location sensitive data not included in pending intent. Only included in
5615 * {@link NetworkCallback}.
5616 */
5617 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusc97d8062020-12-17 14:53:09 -08005618 mCallingAttributionTag = callingAttributionTag;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005619 }
5620
Lorenzo Colittif2514122021-03-12 22:50:57 +09005621 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius7992afd2020-12-22 15:10:42 -08005622 @Nullable final IBinder binder,
5623 @NetworkCallback.Flag int callbackFlags,
5624 @Nullable String callingAttributionTag) {
Lorenzo Colittif2514122021-03-12 22:50:57 +09005625 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5626 callingAttributionTag);
James Mattis6e6fabf2021-01-10 14:24:24 -08005627 }
5628
Lorenzo Colittif2514122021-03-12 22:50:57 +09005629 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattise494cbb2021-02-09 18:18:28 -08005630 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius7992afd2020-12-22 15:10:42 -08005631 @Nullable final IBinder binder,
5632 @NetworkCallback.Flag int callbackFlags,
5633 @Nullable String callingAttributionTag) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005634 super();
James Mattise494cbb2021-02-09 18:18:28 -08005635 ensureAllNetworkRequestsHaveType(r);
James Mattis7835f742020-11-03 15:54:33 -08005636 mRequests = initializeRequests(r);
James Mattise494cbb2021-02-09 18:18:28 -08005637 mNetworkRequestForCallback = requestForCallback;
James Mattis6e6fabf2021-01-10 14:24:24 -08005638 mMessenger = m;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005639 mBinder = binder;
5640 mPid = getCallingPid();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005641 mUid = mDeps.getCallingUid();
Lorenzo Colittif2514122021-03-12 22:50:57 +09005642 mAsUid = asUid;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005643 mPendingIntent = null;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005644 mPerUidCounter = getRequestCounter(this);
5645 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005646 mCallbackFlags = callbackFlags;
Roshan Piusc97d8062020-12-17 14:53:09 -08005647 mCallingAttributionTag = callingAttributionTag;
James Mattisfdd2d3b2021-03-31 13:57:52 -07005648 linkDeathRecipient();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005649 }
5650
James Mattise494cbb2021-02-09 18:18:28 -08005651 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5652 @NonNull final List<NetworkRequest> r) {
5653 super();
5654 ensureAllNetworkRequestsHaveType(r);
5655 mRequests = initializeRequests(r);
5656 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeand67ab4d2021-03-05 19:18:14 +09005657 final NetworkAgentInfo satisfier = nri.getSatisfier();
5658 if (null != satisfier) {
5659 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5660 // The active request is necessary to figure out what callbacks to send, in
5661 // particular then a network updates its capabilities.
5662 // As this code creates a new NRI with a new set of requests, figure out which of
5663 // the list of requests should be the active request. It is always the first
5664 // request of the list that can be satisfied by the satisfier since the order of
5665 // requests is a priority order.
5666 // Note even in the presence of a satisfier there may not be an active request,
5667 // when the satisfier is the no-service network.
5668 NetworkRequest activeRequest = null;
5669 for (final NetworkRequest candidate : r) {
5670 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5671 activeRequest = candidate;
5672 break;
5673 }
5674 }
5675 setSatisfier(satisfier, activeRequest);
5676 }
James Mattise494cbb2021-02-09 18:18:28 -08005677 mMessenger = nri.mMessenger;
5678 mBinder = nri.mBinder;
5679 mPid = nri.mPid;
5680 mUid = nri.mUid;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005681 mAsUid = nri.mAsUid;
James Mattise494cbb2021-02-09 18:18:28 -08005682 mPendingIntent = nri.mPendingIntent;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005683 mPerUidCounter = getRequestCounter(this);
5684 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005685 mCallbackFlags = nri.mCallbackFlags;
James Mattise494cbb2021-02-09 18:18:28 -08005686 mCallingAttributionTag = nri.mCallingAttributionTag;
James Mattisfdd2d3b2021-03-31 13:57:52 -07005687 linkDeathRecipient();
James Mattise494cbb2021-02-09 18:18:28 -08005688 }
5689
Lorenzo Colittif2514122021-03-12 22:50:57 +09005690 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5691 this(asUid, Collections.singletonList(r));
James Mattis6e6fabf2021-01-10 14:24:24 -08005692 }
5693
Lorenzo Colittif2514122021-03-12 22:50:57 +09005694 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5695 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
Cody Kesting0ffbf922019-12-18 10:57:50 -08005696 }
5697
James Mattisf61f7be2021-01-31 17:06:19 -08005698 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5699 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5700 // false.
5701 boolean isBeingSatisfied() {
5702 return (null != mSatisfier && null != mActiveRequest);
5703 }
5704
James Mattise4e72bb2020-11-16 16:46:28 -08005705 boolean isMultilayerRequest() {
5706 return mRequests.size() > 1;
5707 }
5708
James Mattis6e6fabf2021-01-10 14:24:24 -08005709 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5710 // Creating a defensive copy to prevent the sender from modifying the list being
5711 // reflected in the return value of this method.
5712 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis7835f742020-11-03 15:54:33 -08005713 return Collections.unmodifiableList(tempRequests);
5714 }
5715
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005716 void decrementRequestCount() {
5717 mPerUidCounter.decrementCount(mUid);
5718 }
5719
James Mattisfdd2d3b2021-03-31 13:57:52 -07005720 void linkDeathRecipient() {
5721 if (null != mBinder) {
5722 try {
5723 mBinder.linkToDeath(this, 0);
5724 } catch (RemoteException e) {
5725 binderDied();
5726 }
5727 }
5728 }
5729
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005730 void unlinkDeathRecipient() {
James Mattisfdd2d3b2021-03-31 13:57:52 -07005731 if (null != mBinder) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08005732 mBinder.unlinkToDeath(this, 0);
5733 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005734 }
5735
James Mattis3f93a312020-11-12 15:53:42 -08005736 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005737 public void binderDied() {
5738 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis3f93a312020-11-12 15:53:42 -08005739 mRequests + ", " + mBinder + ")");
James Mattisc449dde2020-11-20 16:08:10 -08005740 releaseNetworkRequests(mRequests);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005741 }
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005742
James Mattis3f93a312020-11-12 15:53:42 -08005743 @Override
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005744 public String toString() {
Lorenzo Colittif2514122021-03-12 22:50:57 +09005745 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5746 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattis1238af22020-12-23 16:37:26 -08005747 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colittif2514122021-03-12 22:50:57 +09005748 + " callbackRequest: "
Chalard Jeandc974072021-03-01 22:00:20 +09005749 + mNetworkRequestForCallback.requestId
James Mattis1238af22020-12-23 16:37:26 -08005750 + " " + mRequests
Roshan Pius7992afd2020-12-22 15:10:42 -08005751 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
Roshan Piusf75ffaa2021-03-11 21:16:44 -08005752 + " callback flags: " + mCallbackFlags;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005753 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005754 }
5755
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09005756 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5757 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5758 if (badCapability != null) {
5759 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04005760 }
5761 }
5762
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09005763 // This checks that the passed capabilities either do not request a
5764 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean058cd312018-04-11 21:09:10 +09005765 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005766 int callerPid, int callerUid, String callerPackageName) {
Chalard Jeanbd958b32020-03-18 15:58:50 +09005767 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean058cd312018-04-11 21:09:10 +09005768 throw new SecurityException("Insufficient permissions to request a specific SSID");
5769 }
paulhua9a6e2a2019-03-22 16:35:06 +08005770
5771 if (nc.hasSignalStrength()
5772 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5773 throw new SecurityException(
5774 "Insufficient permissions to request a specific signal strength");
5775 }
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005776 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong4310e452021-03-24 14:01:51 -07005777
junyulai58153cc2021-04-14 23:33:31 +08005778 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong4310e452021-03-24 14:01:51 -07005779 enforceNetworkFactoryPermission();
5780 }
Chalard Jean058cd312018-04-11 21:09:10 +09005781 }
5782
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005783 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005784 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005785 synchronized (nai) {
James Mattis622428c2020-12-02 14:12:41 -08005786 // mNetworkRequests may contain the same value multiple times in case of
5787 // multilayer requests. It won't matter in this case because the thresholds
5788 // will then be the same and be deduplicated as they enter the `thresholds` set.
5789 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattis9301a9a2020-11-18 16:23:25 -08005790 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5791 for (final NetworkRequest req : nri.mRequests) {
5792 if (req.networkCapabilities.hasSignalStrength()
5793 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5794 thresholds.add(req.networkCapabilities.getSignalStrength());
5795 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005796 }
5797 }
5798 }
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005799 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005800 }
5801
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005802 private void updateSignalStrengthThresholds(
5803 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005804 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005805
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09005806 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005807 String detail;
5808 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5809 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5810 } else {
5811 detail = reason;
5812 }
5813 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005814 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005815 }
5816
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005817 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005818 }
5819
Etan Cohenb184cba2017-04-03 17:42:34 -07005820 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5821 if (nc == null) {
5822 return;
5823 }
5824 NetworkSpecifier ns = nc.getNetworkSpecifier();
5825 if (ns == null) {
5826 return;
5827 }
lucaslin61ad5f32021-01-22 15:15:23 +08005828 if (ns instanceof MatchAllNetworkSpecifier) {
5829 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5830 }
Etan Cohenb184cba2017-04-03 17:42:34 -07005831 }
5832
lucaslin8cf57f52019-10-22 18:27:33 +08005833 private void ensureValid(NetworkCapabilities nc) {
5834 ensureValidNetworkSpecifier(nc);
5835 if (nc.isPrivateDnsBroken()) {
5836 throw new IllegalArgumentException("Can't request broken private DNS");
5837 }
5838 }
5839
Roshan Pius7992afd2020-12-22 15:10:42 -08005840 private boolean isTargetSdkAtleast(int version, int callingUid,
5841 @NonNull String callingPackageName) {
5842 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu66797212020-12-10 23:32:32 +08005843 final PackageManager pm =
5844 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien7fae6ea2020-03-27 18:12:39 +08005845 try {
Roshan Pius7992afd2020-12-22 15:10:42 -08005846 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien7fae6ea2020-03-27 18:12:39 +08005847 if (callingVersion < version) return false;
5848 } catch (PackageManager.NameNotFoundException e) { }
5849 return true;
5850 }
5851
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005852 @Override
Lorenzo Colittib199b962021-03-12 22:48:07 +09005853 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
junyulaid1a78162021-01-11 16:53:38 +08005854 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
Roshan Pius7992afd2020-12-22 15:10:42 -08005855 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaid1a78162021-01-11 16:53:38 +08005856 @Nullable String callingAttributionTag) {
markchieneddbe2b2020-03-18 21:16:15 +08005857 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius7992afd2020-12-22 15:10:42 -08005858 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5859 callingPackageName)) {
markchien7fae6ea2020-03-27 18:12:39 +08005860 throw new SecurityException("Insufficient permissions to specify legacy type");
5861 }
markchieneddbe2b2020-03-18 21:16:15 +08005862 }
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005863 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005864 final int callingUid = mDeps.getCallingUid();
Lorenzo Colittib199b962021-03-12 22:48:07 +09005865 // Privileged callers can track the default network of another UID by passing in a UID.
5866 if (asUid != Process.INVALID_UID) {
5867 enforceSettingsPermission();
5868 } else {
5869 asUid = callingUid;
5870 }
junyulaid1a78162021-01-11 16:53:38 +08005871 final NetworkRequest.Type reqType;
5872 try {
5873 reqType = NetworkRequest.Type.values()[reqTypeInt];
5874 } catch (ArrayIndexOutOfBoundsException e) {
5875 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5876 }
5877 switch (reqType) {
5878 case TRACK_DEFAULT:
5879 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colittib199b962021-03-12 22:48:07 +09005880 // is unused and will be replaced by ones appropriate for the UID (usually, the
5881 // calling app). This allows callers to keep track of the default network.
James Mattise494cbb2021-02-09 18:18:28 -08005882 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittib199b962021-03-12 22:48:07 +09005883 defaultNc, asUid, callingUid, callingPackageName);
junyulaid1a78162021-01-11 16:53:38 +08005884 enforceAccessPermission();
5885 break;
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005886 case TRACK_SYSTEM_DEFAULT:
5887 enforceSettingsPermission();
5888 networkCapabilities = new NetworkCapabilities(defaultNc);
5889 break;
Junyu Lai23568a42021-01-19 11:10:56 +00005890 case BACKGROUND_REQUEST:
5891 enforceNetworkStackOrSettingsPermission();
5892 // Fall-through since other checks are the same with normal requests.
junyulaid1a78162021-01-11 16:53:38 +08005893 case REQUEST:
5894 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5895 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5896 callingAttributionTag);
5897 // TODO: this is incorrect. We mark the request as metered or not depending on
5898 // the state of the app when the request is filed, but we never change the
5899 // request if the app changes network state. http://b/29964605
5900 enforceMeteredApnPolicy(networkCapabilities);
5901 break;
junyulai8cae3c72021-03-12 20:05:08 +08005902 case LISTEN_FOR_BEST:
5903 enforceAccessPermission();
5904 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5905 break;
junyulaid1a78162021-01-11 16:53:38 +08005906 default:
5907 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Klinee0aed632016-03-16 15:31:39 +09005908 }
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09005909 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09005910 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005911 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005912
junyulai8cae3c72021-03-12 20:05:08 +08005913 // Enforce FOREGROUND if the caller does not have permission to use background network.
5914 if (reqType == LISTEN_FOR_BEST) {
5915 restrictBackgroundRequestForCaller(networkCapabilities);
5916 }
5917
5918 // Set the UID range for this request to the single UID of the requester, unless the
5919 // requester has the permission to specify other UIDs.
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09005920 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5921 // are no visible methods to set the UIDs, an app could use reflection to try and get
5922 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai8cae3c72021-03-12 20:05:08 +08005923 // Also set the requester UID and package name in the request.
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005924 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5925 callingUid, callingPackageName);
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005926
Etan Cohen3985c172017-02-05 10:42:27 -08005927 if (timeoutMs < 0) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005928 throw new IllegalArgumentException("Bad timeout specified");
5929 }
lucaslin8cf57f52019-10-22 18:27:33 +08005930 ensureValid(networkCapabilities);
Etan Cohend988de62015-11-18 10:56:15 -08005931
James Mattise494cbb2021-02-09 18:18:28 -08005932 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaid1a78162021-01-11 16:53:38 +08005933 nextNetworkRequestId(), reqType);
James Mattise494cbb2021-02-09 18:18:28 -08005934 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colittib199b962021-03-12 22:48:07 +09005935 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colittif2514122021-03-12 22:50:57 +09005936 callingAttributionTag);
Erik Kline47401fa2015-07-09 18:24:03 +09005937 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005938
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005939 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5940 // copied from the default request above. (This is necessary to ensure, for example, that
5941 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5942 // changes don't alter request matching.
5943 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5944 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colittid5e9f982021-02-10 11:59:07 +09005945 throw new IllegalStateException(
5946 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005947 + networkCapabilities + " vs. " + defaultNc);
5948 }
5949
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005950 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07005951 if (timeoutMs > 0) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005952 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07005953 nri), timeoutMs);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005954 }
5955 return networkRequest;
5956 }
5957
James Mattise494cbb2021-02-09 18:18:28 -08005958 /**
5959 * Return the nri to be used when registering a network request. Specifically, this is used with
5960 * requests registered to track the default request. If there is currently a per-app default
5961 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5962 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colittif2514122021-03-12 22:50:57 +09005963 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5964 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08005965 * @param nr the network request for the nri.
5966 * @param msgr the messenger for the nri.
5967 * @param binder the binder for the nri.
5968 * @param callingAttributionTag the calling attribution tag for the nri.
5969 * @return the nri to register.
5970 */
Lorenzo Colittif2514122021-03-12 22:50:57 +09005971 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattise494cbb2021-02-09 18:18:28 -08005972 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius7992afd2020-12-22 15:10:42 -08005973 @NetworkCallback.Flag int callbackFlags,
James Mattise494cbb2021-02-09 18:18:28 -08005974 @Nullable String callingAttributionTag) {
5975 final List<NetworkRequest> requests;
5976 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
5977 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09005978 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattise494cbb2021-02-09 18:18:28 -08005979 } else {
5980 requests = Collections.singletonList(nr);
5981 }
Roshan Pius7992afd2020-12-22 15:10:42 -08005982 return new NetworkRequestInfo(
Lorenzo Colittif2514122021-03-12 22:50:57 +09005983 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattise494cbb2021-02-09 18:18:28 -08005984 }
5985
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07005986 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
5987 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti98097292015-05-14 17:28:27 +09005988 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichic4899352016-07-19 15:59:27 +09005989 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin94c30992014-11-05 10:32:09 -08005990 } else {
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07005991 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin94c30992014-11-05 10:32:09 -08005992 }
5993 }
5994
fenglu76564332015-03-20 11:29:56 -07005995 @Override
fenglu73169332015-04-21 17:12:05 -07005996 public boolean requestBandwidthUpdate(Network network) {
fenglu76564332015-03-20 11:29:56 -07005997 enforceAccessPermission();
5998 NetworkAgentInfo nai = null;
5999 if (network == null) {
6000 return false;
6001 }
6002 synchronized (mNetworkForNetId) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006003 nai = mNetworkForNetId.get(network.getNetId());
fenglu76564332015-03-20 11:29:56 -07006004 }
6005 if (nai != null) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006006 nai.onBandwidthUpdateRequested();
Nathan Harold6179b142018-07-30 13:38:01 -07006007 synchronized (mBandwidthRequests) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006008 final int uid = mDeps.getCallingUid();
Nathan Harold6179b142018-07-30 13:38:01 -07006009 Integer uidReqs = mBandwidthRequests.get(uid);
6010 if (uidReqs == null) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006011 uidReqs = 0;
Nathan Harold6179b142018-07-30 13:38:01 -07006012 }
6013 mBandwidthRequests.put(uid, ++uidReqs);
6014 }
fenglu76564332015-03-20 11:29:56 -07006015 return true;
6016 }
6017 return false;
6018 }
6019
Felipe Lemeff760142016-06-20 16:36:29 -07006020 private boolean isSystem(int uid) {
6021 return uid < Process.FIRST_APPLICATION_UID;
6022 }
fenglu76564332015-03-20 11:29:56 -07006023
Jeremy Joslin94c30992014-11-05 10:32:09 -08006024 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006025 final int uid = mDeps.getCallingUid();
Felipe Lemeff760142016-06-20 16:36:29 -07006026 if (isSystem(uid)) {
Hugo Benichi0a28d302017-02-11 17:04:43 +09006027 // Exemption for system uid.
Felipe Lemeff760142016-06-20 16:36:29 -07006028 return;
6029 }
Hugo Benichi0a28d302017-02-11 17:04:43 +09006030 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6031 // Policy already enforced.
6032 return;
6033 }
paulhu76cf0c52020-12-24 19:47:34 +08006034 final long ident = Binder.clearCallingIdentity();
6035 try {
6036 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6037 // If UID is restricted, don't allow them to bring up metered APNs.
6038 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6039 }
6040 } finally {
6041 Binder.restoreCallingIdentity(ident);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006042 }
6043 }
6044
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006045 @Override
6046 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07006047 PendingIntent operation, @NonNull String callingPackageName,
6048 @Nullable String callingAttributionTag) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006049 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006050 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin94c30992014-11-05 10:32:09 -08006051 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07006052 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6053 callingAttributionTag);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006054 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09006055 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006056 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006057 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohenb184cba2017-04-03 17:42:34 -07006058 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006059 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6060 callingUid, callingPackageName);
Etan Cohendb38d9d2017-04-03 12:17:51 -07006061
Jeremy Joslin94c30992014-11-05 10:32:09 -08006062 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006063 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006064 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6065 callingAttributionTag);
Erik Kline47401fa2015-07-09 18:24:03 +09006066 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006067 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6068 nri));
6069 return networkRequest;
6070 }
6071
Jeremy Joslinb9846d02014-12-03 17:15:28 -08006072 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6073 mHandler.sendMessageDelayed(
6074 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colittie0857092021-03-12 22:39:08 +09006075 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslinb9846d02014-12-03 17:15:28 -08006076 }
6077
Jeremy Joslin94c30992014-11-05 10:32:09 -08006078 @Override
6079 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006080 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin94c30992014-11-05 10:32:09 -08006081 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colittie0857092021-03-12 22:39:08 +09006082 mDeps.getCallingUid(), 0, operation));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006083 }
6084
Lorenzo Colitti15ff2fc2015-04-22 10:44:49 +09006085 // In order to implement the compatibility measure for pre-M apps that call
6086 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6087 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6088 // This ensures it has permission to do so.
6089 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6090 if (nc == null) {
6091 return false;
6092 }
6093 int[] transportTypes = nc.getTransportTypes();
6094 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6095 return false;
6096 }
6097 try {
6098 mContext.enforceCallingOrSelfPermission(
6099 android.Manifest.permission.ACCESS_WIFI_STATE,
6100 "ConnectivityService");
6101 } catch (SecurityException e) {
6102 return false;
6103 }
6104 return true;
6105 }
6106
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006107 @Override
6108 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius7992afd2020-12-22 15:10:42 -08006109 Messenger messenger, IBinder binder,
6110 @NetworkCallback.Flag int callbackFlags,
6111 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006112 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti15ff2fc2015-04-22 10:44:49 +09006113 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6114 enforceAccessPermission();
6115 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006116
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09006117 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006118 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006119 Binder.getCallingPid(), callingUid, callingPackageName);
6120 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeana43eede2018-03-20 19:13:57 +09006121 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6122 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6123 // onLost and onAvailable callbacks when networks move in and out of the background.
6124 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6125 // can't request networks.
6126 restrictBackgroundRequestForCaller(nc);
lucaslin8cf57f52019-10-22 18:27:33 +08006127 ensureValid(nc);
Etan Cohendb38d9d2017-04-03 12:17:51 -07006128
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09006129 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006130 NetworkRequest.Type.LISTEN);
Roshan Piusc97d8062020-12-17 14:53:09 -08006131 NetworkRequestInfo nri =
Lorenzo Colittif2514122021-03-12 22:50:57 +09006132 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius7992afd2020-12-22 15:10:42 -08006133 callingAttributionTag);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09006134 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006135
6136 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6137 return networkRequest;
6138 }
6139
6140 @Override
6141 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusc97d8062020-12-17 14:53:09 -08006142 PendingIntent operation, @NonNull String callingPackageName,
6143 @Nullable String callingAttributionTag) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006144 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006145 final int callingUid = mDeps.getCallingUid();
Paul Jensen9ceed862015-06-17 14:15:39 -04006146 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6147 enforceAccessPermission();
6148 }
lucaslin8cf57f52019-10-22 18:27:33 +08006149 ensureValid(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006150 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006151 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09006152 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006153 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09006154
6155 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006156 NetworkRequest.Type.LISTEN);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006157 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6158 callingAttributionTag);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09006159 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen9ceed862015-06-17 14:15:39 -04006160
6161 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006162 }
6163
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006164 /** Returns the next Network provider ID. */
6165 public final int nextNetworkProviderId() {
6166 return mNextNetworkProviderId.getAndIncrement();
6167 }
6168
James Mattisc449dde2020-11-20 16:08:10 -08006169 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
James Mattis3f93a312020-11-12 15:53:42 -08006170 for (int i = 0; i < networkRequests.size(); i++) {
6171 releaseNetworkRequest(networkRequests.get(i));
6172 }
6173 }
6174
Erik Klineaec3f5e2016-07-07 16:50:58 +09006175 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006176 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitticef9c492016-07-05 01:22:13 +09006177 ensureNetworkRequestHasType(networkRequest);
Erik Klineaec3f5e2016-07-07 16:50:58 +09006178 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colittie0857092021-03-12 22:39:08 +09006179 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006180 }
6181
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006182 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6183 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006184 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6185 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6186 // as that will throw if a duplicate provider is registered.
Aaron Huang11e9a312020-10-30 22:04:25 +08006187 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006188 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006189 return;
6190 }
6191
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006192 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6193 mNetworkProviderInfos.put(npi.messenger, npi);
6194 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006195 }
6196
6197 @Override
6198 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006199 enforceNetworkFactoryOrSettingsPermission();
Aaron Huang6a16a412021-04-09 12:06:42 +08006200 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006201 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifr1c0d9b22021-03-10 13:58:14 +08006202 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006203 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6204 return npi.providerId;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006205 }
6206
6207 @Override
6208 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006209 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006210 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07006211 }
6212
Chalard Jean1ef1d902021-01-05 08:40:09 +09006213 @Override
Chalard Jeanb004da52021-03-22 22:44:02 +09006214 public void offerNetwork(final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09006215 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6216 @NonNull final INetworkOfferCallback callback) {
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006217 Objects.requireNonNull(score);
6218 Objects.requireNonNull(caps);
6219 Objects.requireNonNull(callback);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006220 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanb004da52021-03-22 22:44:02 +09006221 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006222 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6223 }
6224
6225 @Override
6226 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6228 }
6229
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006230 private void handleUnregisterNetworkProvider(Messenger messenger) {
6231 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6232 if (npi == null) {
6233 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07006234 return;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006235 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09006236 // Unregister all the offers from this provider
6237 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6238 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jeanb004da52021-03-22 22:44:02 +09006239 if (noi.offer.providerId == npi.providerId) {
Chalard Jean1ef1d902021-01-05 08:40:09 +09006240 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6241 toRemove.add(noi);
6242 }
6243 }
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006244 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jean1ef1d902021-01-05 08:40:09 +09006245 handleUnregisterNetworkOffer(noi);
6246 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006247 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt948aea52014-04-11 15:53:27 -07006248 }
6249
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006250 @Override
James Mattis08131f32020-12-13 16:28:14 -08006251 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006252 if (request.hasTransport(TRANSPORT_TEST)) {
6253 enforceNetworkFactoryOrTestNetworksPermission();
6254 } else {
6255 enforceNetworkFactoryPermission();
6256 }
James Mattis08131f32020-12-13 16:28:14 -08006257 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6258 if (nri != null) {
6259 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6260 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6261 mHandler.post(() -> handleReleaseNetworkRequest(
6262 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6263 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006264 }
6265
Paul Jensenc2569432015-02-13 14:18:39 -05006266 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6267 @GuardedBy("mNetworkForNetId")
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006268 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensenc2569432015-02-13 14:18:39 -05006269 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006270 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensenc2569432015-02-13 14:18:39 -05006271 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006272 private final NetIdManager mNetIdManager;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006273
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006274 // NetworkAgentInfo keyed off its connecting messenger
6275 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensenc2569432015-02-13 14:18:39 -05006276 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006277 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006278
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09006279 // UID ranges for users that are currently blocked by VPNs.
6280 // This array is accessed and iterated on multiple threads without holding locks, so its
6281 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6282 // (on the handler thread).
6283 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6284
Chalard Jean1ef1d902021-01-05 08:40:09 +09006285 // Must only be accessed on the handler thread
6286 @NonNull
6287 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6288
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09006289 @GuardedBy("mBlockedAppUids")
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006290 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09006291
Chalard Jean9d968182021-02-25 21:46:34 +09006292 // Current OEM network preferences. This object must only be written to on the handler thread.
6293 // Since it is immutable and always non-null, other threads may read it if they only care
6294 // about seeing a consistent object but not that it is current.
James Mattis6e6fabf2021-01-10 14:24:24 -08006295 @NonNull
6296 private OemNetworkPreferences mOemNetworkPreferences =
6297 new OemNetworkPreferences.Builder().build();
Chalard Jean9d968182021-02-25 21:46:34 +09006298 // Current per-profile network preferences. This object follows the same threading rules as
6299 // the OEM network preferences above.
6300 @NonNull
6301 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
James Mattis6e6fabf2021-01-10 14:24:24 -08006302
James Mattis6e4405f2021-04-06 17:07:42 -07006303 // OemNetworkPreferences activity String log entries.
6304 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6305 @NonNull
6306 private final LocalLog mOemNetworkPreferencesLogs =
6307 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6308
James Mattisbd275dc2021-03-13 19:27:21 -08006309 /**
6310 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6311 * @param packageName the package name to check existence of a mapping for.
6312 * @return true if a mapping exists, false otherwise
6313 */
6314 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6315 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6316 }
6317
James Mattis8af2d602020-12-20 11:09:58 -08006318 // The always-on request for an Internet-capable network that apps without a specific default
6319 // fall back to.
James Mattis6e6fabf2021-01-10 14:24:24 -08006320 @VisibleForTesting
Chalard Jean4deee632019-11-05 14:40:23 +09006321 @NonNull
James Mattis6e6fabf2021-01-10 14:24:24 -08006322 final NetworkRequestInfo mDefaultRequest;
James Mattis8af2d602020-12-20 11:09:58 -08006323 // Collection of NetworkRequestInfo's used for default networks.
James Mattis6e6fabf2021-01-10 14:24:24 -08006324 @VisibleForTesting
James Mattis8af2d602020-12-20 11:09:58 -08006325 @NonNull
James Mattis6e6fabf2021-01-10 14:24:24 -08006326 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09006327
James Mattis1238af22020-12-23 16:37:26 -08006328 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6329 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6330 }
6331
6332 /**
James Mattise494cbb2021-02-09 18:18:28 -08006333 * Return the default network request currently tracking the given uid.
6334 * @param uid the uid to check.
6335 * @return the NetworkRequestInfo tracking the given uid.
6336 */
6337 @NonNull
James Mattisbd275dc2021-03-13 19:27:21 -08006338 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
James Mattise494cbb2021-02-09 18:18:28 -08006339 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6340 if (nri == mDefaultRequest) {
6341 continue;
6342 }
6343 // Checking the first request is sufficient as only multilayer requests will have more
6344 // than one request and for multilayer, all requests will track the same uids.
6345 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6346 return nri;
6347 }
6348 }
6349 return mDefaultRequest;
6350 }
6351
6352 /**
6353 * Get a copy of the network requests of the default request that is currently tracking the
6354 * given uid.
Lorenzo Colittif2514122021-03-12 22:50:57 +09006355 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6356 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08006357 * @param requestorUid the uid to check the default for.
6358 * @param requestorPackageName the requestor's package name.
6359 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6360 */
6361 @NonNull
6362 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006363 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattise494cbb2021-02-09 18:18:28 -08006364 return copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006365 getDefaultRequestTrackingUid(asUid).mRequests,
6366 asUid, requestorUid, requestorPackageName);
James Mattise494cbb2021-02-09 18:18:28 -08006367 }
6368
6369 /**
6370 * Copy the given nri's NetworkRequest collection.
6371 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colittif2514122021-03-12 22:50:57 +09006372 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6373 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08006374 * @param requestorUid the uid to set on the copied collection.
6375 * @param requestorPackageName the package name to set on the copied collection.
6376 * @return the copied NetworkRequest collection.
6377 */
6378 @NonNull
6379 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006380 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6381 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattise494cbb2021-02-09 18:18:28 -08006382 final List<NetworkRequest> requests = new ArrayList<>();
6383 for (final NetworkRequest nr : requestsToCopy) {
6384 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006385 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattise494cbb2021-02-09 18:18:28 -08006386 nr.legacyType, nextNetworkRequestId(), nr.type));
6387 }
6388 return requests;
6389 }
6390
6391 @NonNull
6392 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006393 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6394 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colittic62368f2021-03-22 02:12:04 +09006395 // These capabilities are for a TRACK_DEFAULT callback, so:
6396 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6397 // mDefaultRequest and a per-UID default request.
6398 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colittif2514122021-03-12 22:50:57 +09006399 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colittic62368f2021-03-22 02:12:04 +09006400 // not do this in the case of a privileged application.
James Mattise494cbb2021-02-09 18:18:28 -08006401 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6402 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006403 netCap.setSingleUid(asUid);
James Mattise494cbb2021-02-09 18:18:28 -08006404 restrictRequestUidsForCallerAndSetRequestorInfo(
6405 netCap, requestorUid, requestorPackageName);
6406 return netCap;
6407 }
6408
6409 /**
6410 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6411 * @param nr the network request to check for equality against.
6412 * @return the nri if one exists, null otherwise.
6413 */
6414 @Nullable
6415 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6416 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6417 if (nri.getNetworkRequestForCallback().equals(nr)) {
6418 return nri;
6419 }
6420 }
6421 return null;
6422 }
6423
6424 /**
6425 * Check if an nri is currently being managed by per-app default networking.
6426 * @param nri the nri to check.
6427 * @return true if this nri is currently being managed by per-app default networking.
6428 */
6429 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6430 // nri.mRequests.get(0) is only different from the original request filed in
6431 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6432 // functionality therefore if these two don't match, it means this particular nri is
6433 // currently being managed by a per-app default.
6434 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6435 }
6436
6437 /**
James Mattis1238af22020-12-23 16:37:26 -08006438 * Determine if an nri is a managed default request that disallows default networking.
6439 * @param nri the request to evaluate
6440 * @return true if device-default networking is disallowed
6441 */
6442 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6443 // Check if this nri is a managed default that supports the default network at its
6444 // lowest priority request.
6445 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6446 final NetworkCapabilities lowestPriorityNetCap =
6447 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6448 return isPerAppDefaultRequest(nri)
6449 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6450 lowestPriorityNetCap));
6451 }
6452
Erik Kline74d68ef2015-04-30 12:58:40 +09006453 // Request used to optionally keep mobile data active even when higher
6454 // priority networks like Wi-Fi are active.
6455 private final NetworkRequest mDefaultMobileDataRequest;
6456
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07006457 // Request used to optionally keep wifi data active even when higher
6458 // priority networks like ethernet are active.
6459 private final NetworkRequest mDefaultWifiRequest;
6460
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08006461 // Request used to optionally keep vehicle internal network always active
6462 private final NetworkRequest mDefaultVehicleRequest;
6463
James Mattis1238af22020-12-23 16:37:26 -08006464 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6465 // network with no service. This NAI should never be matched against, nor should any public API
6466 // ever return the associated network. For this reason, this NAI is not in the list of available
6467 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6468 // default requests that don't support using the device default network which will ultimately
6469 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6470 @VisibleForTesting
6471 final NetworkAgentInfo mNoServiceNetwork;
6472
Chalard Jean1bc77a92021-02-04 13:12:59 +09006473 // The NetworkAgentInfo currently satisfying the default request, if any.
6474 private NetworkAgentInfo getDefaultNetwork() {
6475 return mDefaultRequest.mSatisfier;
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09006476 }
6477
James Mattisf61f7be2021-01-31 17:06:19 -08006478 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6479 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6480 // Currently, all network requests will have the same uids therefore checking the first
6481 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wangd5034c72021-02-22 18:36:38 +08006482 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattisf61f7be2021-01-31 17:06:19 -08006483 if (null == uids) {
6484 continue;
6485 }
6486 for (final UidRange range : uids) {
6487 if (range.contains(uid)) {
6488 return nri.getSatisfier();
6489 }
6490 }
6491 }
6492 return getDefaultNetwork();
6493 }
6494
Varun Anand273f9002019-02-06 10:13:38 -08006495 @Nullable
6496 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6497 return nai != null ? nai.network : null;
6498 }
6499
6500 private void ensureRunningOnConnectivityServiceThread() {
6501 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6502 throw new IllegalStateException(
6503 "Not running on ConnectivityService thread: "
6504 + Thread.currentThread().getName());
6505 }
6506 }
6507
Chalard Jean8cc4e872019-04-10 23:07:55 +09006508 @VisibleForTesting
Chalard Jean1bc77a92021-02-04 13:12:59 +09006509 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6510 return nai == getDefaultNetwork();
Robert Greenwaltb264cd82014-08-06 21:32:18 -07006511 }
6512
Chalard Jean44689aa2018-05-02 21:14:54 +09006513 /**
6514 * Register a new agent with ConnectivityService to handle a network.
6515 *
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006516 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean44689aa2018-05-02 21:14:54 +09006517 * @param networkInfo the initial info associated with this network. It can be updated later :
6518 * see {@link #updateNetworkInfo}.
6519 * @param linkProperties the initial link properties of this network. They can be updated
6520 * later : see {@link #updateLinkProperties}.
6521 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean945f2482019-12-12 13:56:13 +09006522 * later : see {@link #updateCapabilities}.
Chalard Jeandd753522020-12-21 18:36:52 +09006523 * @param initialScore the initial score of the network. See
Chalard Jean44689aa2018-05-02 21:14:54 +09006524 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colitticf595362020-01-12 22:28:37 +09006525 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006526 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeana973c7a2019-12-13 19:47:12 +09006527 * @return the network created for this agent.
Chalard Jean44689aa2018-05-02 21:14:54 +09006528 */
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006529 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean44689aa2018-05-02 21:14:54 +09006530 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeandd753522020-12-21 18:36:52 +09006531 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6532 int providerId) {
Lorenzo Colitti83d06562021-01-18 14:15:17 +09006533 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6534 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6535 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jeandd753522020-12-21 18:36:52 +09006536 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colitti83d06562021-01-18 14:15:17 +09006537 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006538 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6539 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006540 } else {
6541 enforceNetworkFactoryPermission();
6542 }
6543
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006544 final int uid = mDeps.getCallingUid();
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006545 final long token = Binder.clearCallingIdentity();
6546 try {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006547 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeandd753522020-12-21 18:36:52 +09006548 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006549 } finally {
6550 Binder.restoreCallingIdentity(token);
6551 }
6552 }
6553
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006554 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006555 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeandd753522020-12-21 18:36:52 +09006556 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6557 int uid) {
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006558 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006559 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6560 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6561 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6562 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006563 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006564 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006565
Rubin Xu57b437a2017-09-05 18:40:49 +01006566 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006567
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09006568 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006569 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006570 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jeande419812020-03-04 17:45:08 +09006571 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jeane634b282021-03-05 23:07:53 +09006572 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6573 mQosCallbackTracker, mDeps);
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006574
6575 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006576 processCapabilitiesFromAgent(nai, nc);
Chalard Jean8ffefba2019-11-22 22:39:56 +09006577 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006578 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6579
Chalard Jeandf2478a2018-04-26 16:16:10 +09006580 final String extraInfo = networkInfo.getExtraInfo();
6581 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jeanbd958b32020-03-18 15:58:50 +09006582 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt721f2372014-08-27 14:34:02 -07006583 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006584 mDeps.getNetworkStack().makeNetworkMonitor(
6585 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006586 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6587 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006588 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006589 // registration.
Chalard Jeana973c7a2019-12-13 19:47:12 +09006590 return nai.network;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006591 }
6592
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006593 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6594 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006595 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006596 mNetworkAgentInfos.add(nai);
Paul Jensenc2569432015-02-13 14:18:39 -05006597 synchronized (mNetworkForNetId) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006598 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensenc2569432015-02-13 14:18:39 -05006599 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006600
6601 try {
6602 networkMonitor.start();
6603 } catch (RemoteException e) {
Chiachang Wang619a8a22019-04-24 21:44:05 +08006604 e.rethrowAsRuntimeException();
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006605 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006606 nai.notifyRegistered();
Erik Kline79371012018-03-04 21:01:01 +09006607 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline79371012018-03-04 21:01:01 +09006608 updateNetworkInfo(nai, networkInfo);
6609 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006610 }
6611
Chalard Jean1ef1d902021-01-05 08:40:09 +09006612 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6613 @NonNull public final NetworkOffer offer;
6614
6615 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6616 this.offer = offer;
6617 }
6618
6619 @Override
6620 public void binderDied() {
6621 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6622 }
6623 }
6624
Chalard Jean7618f1a2021-03-24 14:31:38 +09006625 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6626 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6627 if (npi.providerId == providerId) return true;
6628 }
6629 return false;
6630 }
6631
Chalard Jean1ef1d902021-01-05 08:40:09 +09006632 /**
6633 * Register or update a network offer.
6634 * @param newOffer The new offer. If the callback member is the same as an existing
6635 * offer, it is an update of that offer.
6636 */
6637 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6638 ensureRunningOnConnectivityServiceThread();
Chalard Jean7618f1a2021-03-24 14:31:38 +09006639 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6640 // This may actually happen if a provider updates its score or registers and then
6641 // immediately unregisters. The offer would still be in the handler queue, but the
6642 // provider would have been removed.
6643 if (DBG) log("Received offer from an unregistered provider");
6644 return;
6645 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09006646 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6647 if (null != existingOffer) {
6648 handleUnregisterNetworkOffer(existingOffer);
6649 newOffer.migrateFrom(existingOffer.offer);
6650 }
6651 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6652 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09006653 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006654 } catch (RemoteException e) {
6655 noi.binderDied();
6656 return;
6657 }
6658 mNetworkOffers.add(noi);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006659 issueNetworkNeeds(noi);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006660 }
6661
6662 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6663 ensureRunningOnConnectivityServiceThread();
6664 mNetworkOffers.remove(noi);
Chalard Jeanb004da52021-03-22 22:44:02 +09006665 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006666 }
6667
6668 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6669 @NonNull final INetworkOfferCallback callback) {
6670 ensureRunningOnConnectivityServiceThread();
6671 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jeanf1364432021-04-08 17:37:36 +09006672 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jean1ef1d902021-01-05 08:40:09 +09006673 }
6674 return null;
6675 }
6676
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006677 /**
6678 * Called when receiving LinkProperties directly from a NetworkAgent.
6679 * Stores into |nai| any data coming from the agent that might also be written to the network's
6680 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6681 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti3c75ca82020-12-02 13:58:47 +09006682 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006683 */
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006684 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6685 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colitti54fb93f2020-04-01 22:25:16 +09006686 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalom492febb2021-01-11 18:45:34 -08006687 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006688 }
6689
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006690 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006691 @NonNull LinkProperties oldLp) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006692 int netId = networkAgent.network.getNetId();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006693
Lorenzo Colittifff75392020-04-01 20:16:30 +09006694 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6695 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6696 // the LinkProperties for the network are accurate.
Lorenzo Colitti07f10202019-01-08 14:43:37 +09006697 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti667da282014-09-20 13:47:47 +09006698
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006699 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006700
6701 // update filtering rules, need to happen after the interface update so netd knows about the
6702 // new interface (the interface name -> index map becomes initialized)
6703 updateVpnFiltering(newLp, oldLp, networkAgent);
6704
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006705 updateMtu(newLp, oldLp);
6706 // TODO - figure out what to do for clat
6707// for (LinkProperties lp : newLp.getStackedLinks()) {
6708// updateMtu(lp, null);
6709// }
Chalard Jean1bc77a92021-02-04 13:12:59 +09006710 if (isDefaultNetwork(networkAgent)) {
lucaslin589964b2018-11-28 19:27:52 +08006711 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6712 }
Lorenzo Colittiaa4f1f62014-11-28 20:07:46 +09006713
Erik Kline3d4ed152016-04-05 13:30:49 +09006714 updateRoutes(newLp, oldLp, netId);
6715 updateDnses(newLp, oldLp, netId);
dalykf4977492018-03-05 12:42:22 -05006716 // Make sure LinkProperties represents the latest private DNS status.
6717 // This does not need to be done before updateDnses because the
6718 // LinkProperties are not the source of the private DNS configuration.
6719 // updateDnses will fetch the private DNS configuration from DnsManager.
6720 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colittiaa4f1f62014-11-28 20:07:46 +09006721
Chalard Jean1bc77a92021-02-04 13:12:59 +09006722 if (isDefaultNetwork(networkAgent)) {
Paul Jensen12131352014-12-10 15:12:18 -05006723 handleApplyDefaultProxy(newLp.getHttpProxy());
6724 } else {
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006725 updateProxy(newLp, oldLp);
Paul Jensen12131352014-12-10 15:12:18 -05006726 }
Valentin Iftimea039e572019-09-24 13:32:13 +02006727
6728 updateWakeOnLan(newLp);
6729
Hai Shalom492febb2021-01-11 18:45:34 -08006730 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6731 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6732 // does, it needs to be merged here.
6733 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6734 networkAgent.capportApiData));
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09006735
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07006736 // TODO - move this check to cover the whole function
6737 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanf2f75592018-05-23 09:07:51 +09006738 synchronized (networkAgent) {
6739 networkAgent.linkProperties = newLp;
6740 }
Lorenzo Colitti714b7862019-02-19 13:21:56 +09006741 // Start or stop DNS64 detection and 464xlat according to network state.
6742 networkAgent.clatd.update();
Jeff Davidson9804c892016-01-20 11:35:38 -08006743 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VAN3b1d8b42020-05-10 16:11:11 +09006744 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6745 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin34cd3942018-11-28 12:51:55 +08006746 if (networkAgent.everConnected) {
6747 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6748 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07006749 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09006750
6751 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen7d854042014-05-13 11:44:01 -04006752 }
6753
Hai Shalom492febb2021-01-11 18:45:34 -08006754 /**
6755 * @param naData captive portal data from NetworkAgent
6756 * @param apiData captive portal data from capport API
6757 */
6758 @Nullable
6759 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6760 CaptivePortalData apiData) {
6761 if (naData == null || apiData == null) {
6762 return naData == null ? apiData : naData;
6763 }
6764 final CaptivePortalData.Builder captivePortalBuilder =
6765 new CaptivePortalData.Builder(naData);
6766
6767 if (apiData.isCaptive()) {
6768 captivePortalBuilder.setCaptive(true);
6769 }
6770 if (apiData.isSessionExtendable()) {
6771 captivePortalBuilder.setSessionExtendable(true);
6772 }
6773 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6774 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6775 // otherwise data would be inconsistent. Prefer the capport API info if present,
6776 // as it can generally be refreshed more often.
6777 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6778 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6779 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6780 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6781 // No source has time / bytes remaining information: surface the newest refresh time
6782 // for other fields
6783 captivePortalBuilder.setRefreshTime(
6784 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6785 }
6786
Hai Shalom7fcd18a2021-02-04 19:34:06 -08006787 // Prioritize the user portal URL from the network agent if the source is authenticated.
6788 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6789 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6790 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6791 apiData.getUserPortalUrlSource());
Hai Shalom492febb2021-01-11 18:45:34 -08006792 }
Hai Shalom7fcd18a2021-02-04 19:34:06 -08006793 // Prioritize the venue information URL from the network agent if the source is
6794 // authenticated.
6795 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6796 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6797 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6798 apiData.getVenueInfoUrlSource());
Hai Shalom492febb2021-01-11 18:45:34 -08006799 }
6800 return captivePortalBuilder.build();
6801 }
6802
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006803 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean73d9db72018-06-04 16:52:49 +09006804 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006805 // marks on unsupported interfaces is harmless.
6806 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6807 return;
6808 }
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006809
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09006810 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6811 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6812
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006813 // Mask/mark of zero will not detect anything interesting.
6814 // Don't install rules unless both values are nonzero.
6815 if (mark == 0 || mask == 0) {
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006816 return;
6817 }
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006818
6819 final String prefix = "iface:" + iface;
6820 try {
6821 if (add) {
Luke Huang358aa262018-09-27 19:33:11 +08006822 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006823 } else {
Luke Huang358aa262018-09-27 19:33:11 +08006824 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006825 }
6826 } catch (Exception e) {
6827 loge("Exception modifying wakeup packet monitoring: " + e);
6828 }
6829
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006830 }
6831
Chalard Jeane5550312019-11-19 19:03:53 +09006832 private void updateInterfaces(final @Nullable LinkProperties newLp,
6833 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006834 final @NonNull NetworkCapabilities caps) {
Chalard Jeane5550312019-11-19 19:03:53 +09006835 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu8cb82d22017-08-22 16:35:52 +01006836 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6837 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jeane5550312019-11-19 19:03:53 +09006838 if (!interfaceDiff.added.isEmpty()) {
Chalard Jeane5550312019-11-19 19:03:53 +09006839 for (final String iface : interfaceDiff.added) {
6840 try {
6841 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wanga93ddb22020-10-26 14:23:52 +08006842 mNetd.networkAddInterface(netId, iface);
Chalard Jeane5550312019-11-19 19:03:53 +09006843 wakeupModifyInterface(iface, caps, true);
Aaron Huange044c462020-10-27 03:36:19 +08006844 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6845 caps.getTransportTypes());
Chalard Jeane5550312019-11-19 19:03:53 +09006846 } catch (Exception e) {
lucaslin3967e5f2021-04-01 19:17:08 +08006847 logw("Exception adding interface: " + e);
Chalard Jeane5550312019-11-19 19:03:53 +09006848 }
Paul Jensen6b197532014-04-28 10:33:11 -04006849 }
6850 }
Chalard Jeane5550312019-11-19 19:03:53 +09006851 for (final String iface : interfaceDiff.removed) {
Paul Jensen6b197532014-04-28 10:33:11 -04006852 try {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006853 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006854 wakeupModifyInterface(iface, caps, false);
Chiachang Wanga93ddb22020-10-26 14:23:52 +08006855 mNetd.networkRemoveInterface(netId, iface);
Paul Jensen6b197532014-04-28 10:33:11 -04006856 } catch (Exception e) {
6857 loge("Exception removing interface: " + e);
6858 }
6859 }
6860 }
6861
Tyler Weara8978d42019-12-05 14:55:30 -08006862 // TODO: move to frameworks/libs/net.
6863 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6864 final String nextHop;
6865
6866 switch (route.getType()) {
6867 case RouteInfo.RTN_UNICAST:
6868 if (route.hasGateway()) {
6869 nextHop = route.getGateway().getHostAddress();
6870 } else {
6871 nextHop = INetd.NEXTHOP_NONE;
6872 }
6873 break;
6874 case RouteInfo.RTN_UNREACHABLE:
6875 nextHop = INetd.NEXTHOP_UNREACHABLE;
6876 break;
6877 case RouteInfo.RTN_THROW:
6878 nextHop = INetd.NEXTHOP_THROW;
6879 break;
6880 default:
6881 nextHop = INetd.NEXTHOP_NONE;
6882 break;
6883 }
6884
6885 final RouteInfoParcel rip = new RouteInfoParcel();
6886 rip.ifName = route.getInterface();
6887 rip.destination = route.getDestination().toString();
6888 rip.nextHop = nextHop;
6889 rip.mtu = route.getMtu();
6890
6891 return rip;
6892 }
6893
Paul Jensen1b79a592014-08-06 15:51:33 -04006894 /**
6895 * Have netd update routes from oldLp to newLp.
6896 * @return true if routes changed between oldLp and newLp
6897 */
6898 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weara8978d42019-12-05 14:55:30 -08006899 // compare the route diff to determine which routes have been updated
junyulai21c26da2020-03-23 20:49:43 +08006900 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
6901 new CompareOrUpdateResult<>(
6902 oldLp != null ? oldLp.getAllRoutes() : null,
6903 newLp != null ? newLp.getAllRoutes() : null,
6904 (r) -> r.getRouteKey());
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006905
6906 // add routes before removing old in case it helps with continuous connectivity
6907
Chalard Jean73d9db72018-06-04 16:52:49 +09006908 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006909 for (RouteInfo route : routeDiff.added) {
6910 if (route.hasGateway()) continue;
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006911 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006912 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006913 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006914 } catch (Exception e) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006915 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weara8978d42019-12-05 14:55:30 -08006916 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt721f2372014-08-27 14:34:02 -07006917 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006918 }
6919 }
6920 for (RouteInfo route : routeDiff.added) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006921 if (!route.hasGateway()) continue;
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006922 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006923 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006924 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006925 } catch (Exception e) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006926 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weara8978d42019-12-05 14:55:30 -08006927 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt721f2372014-08-27 14:34:02 -07006928 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006929 }
6930 }
6931
6932 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006933 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006934 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006935 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006936 } catch (Exception e) {
Tyler Weara8978d42019-12-05 14:55:30 -08006937 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006938 }
6939 }
Tyler Weara8978d42019-12-05 14:55:30 -08006940
6941 for (RouteInfo route : routeDiff.updated) {
6942 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
6943 try {
6944 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
6945 } catch (Exception e) {
6946 loge("Exception in networkUpdateRouteParcel: " + e);
6947 }
6948 }
6949 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
6950 || !routeDiff.updated.isEmpty();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006951 }
Erik Kline04270062015-06-17 13:19:54 +09006952
Erik Kline3d4ed152016-04-05 13:30:49 +09006953 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
6954 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
6955 return; // no updating necessary
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006956 }
Erik Kline3d4ed152016-04-05 13:30:49 +09006957
Erik Klinec06d4f92018-01-11 21:07:29 +09006958 if (DBG) {
6959 final Collection<InetAddress> dnses = newLp.getDnsServers();
6960 log("Setting DNS servers for network " + netId + " to " + dnses);
6961 }
Erik Kline3d4ed152016-04-05 13:30:49 +09006962 try {
chenbruce2e6b79f2020-02-20 14:28:31 +08006963 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce2e6b79f2020-02-20 14:28:31 +08006964 mDnsManager.flushVmDnsCache();
Erik Kline3d4ed152016-04-05 13:30:49 +09006965 } catch (Exception e) {
Pierre Imai5b5fe392016-04-28 17:00:04 +09006966 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline3d4ed152016-04-05 13:30:49 +09006967 }
Erik Klinebd18f302017-04-07 15:29:29 +09006968 }
6969
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006970 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
6971 NetworkAgentInfo nai) {
6972 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
6973 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
6974 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
6975 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
6976
6977 if (!wasFiltering && !needsFiltering) {
6978 // Nothing to do.
6979 return;
6980 }
6981
6982 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
6983 // Nothing changed.
6984 return;
6985 }
6986
Chiachang Wangd5034c72021-02-22 18:36:38 +08006987 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb3347b2020-01-17 17:54:27 -08006988 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006989 // TODO: this create a window of opportunity for apps to receive traffic between the time
6990 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey0d585432020-09-11 15:10:20 -06006991 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006992 // old rules are being removed.
6993 if (wasFiltering) {
6994 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
6995 }
6996 if (needsFiltering) {
6997 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
6998 }
6999 }
7000
Valentin Iftimea039e572019-09-24 13:32:13 +02007001 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09007002 if (mWolSupportedInterfaces == null) {
7003 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09007004 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09007005 }
Valentin Iftimea039e572019-09-24 13:32:13 +02007006 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7007 }
7008
Luke Huang089ebf12018-08-24 20:33:16 +08007009 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007010 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang089ebf12018-08-24 20:33:16 +08007011 return INetd.PERMISSION_SYSTEM;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007012 }
7013 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang089ebf12018-08-24 20:33:16 +08007014 return INetd.PERMISSION_NETWORK;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007015 }
Luke Huang089ebf12018-08-24 20:33:16 +08007016 return INetd.PERMISSION_NONE;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007017 }
7018
Chalard Jeana00029d2019-12-02 18:39:29 +09007019 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7020 @NonNull final NetworkCapabilities newNc) {
7021 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7022 final int newPermission = getNetworkPermission(newNc);
7023 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7024 try {
Serik Beketayev284cb872020-12-07 22:43:07 -08007025 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wang9695da32020-10-26 19:59:31 +08007026 } catch (RemoteException | ServiceSpecificException e) {
7027 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jeana00029d2019-12-02 18:39:29 +09007028 }
7029 }
7030 }
7031
Paul Jensen783c0e02015-06-16 14:27:36 -04007032 /**
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007033 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7034 * Stores into |nai| any data coming from the agent that might also be written to the network's
7035 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7036 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti3c75ca82020-12-02 13:58:47 +09007037 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007038 */
7039 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007040 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7041 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7042 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7043 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti39b4c5b2020-12-09 18:30:52 +09007044 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7045 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7046 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7047 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7048 }
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007049 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007050 }
7051
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007052 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007053 @VisibleForTesting
Lorenzo Colitti8750be02020-12-01 01:08:37 +09007054 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007055 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattisf61f7be2021-01-31 17:06:19 -08007056 underlyingNetworks = underlyingNetworksOrDefault(
7057 agentCaps.getOwnerUid(), underlyingNetworks);
lifrc33ea4d2021-03-04 14:08:08 +08007058 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007059 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7060 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007061 // metered if any underlying is metered, or originally declared metered by the agent.
7062 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007063 boolean roaming = false; // roaming if any underlying is roaming
7064 boolean congested = false; // congested if any underlying is congested
7065 boolean suspended = true; // suspended if all underlying are suspended
7066
7067 boolean hadUnderlyingNetworks = false;
7068 if (null != underlyingNetworks) {
7069 for (Network underlyingNetwork : underlyingNetworks) {
7070 final NetworkAgentInfo underlying =
7071 getNetworkAgentInfoForNetwork(underlyingNetwork);
7072 if (underlying == null) continue;
7073
7074 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7075 hadUnderlyingNetworks = true;
7076 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09007077 transportTypes |= 1L << underlyingType;
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007078 }
7079
7080 // Merge capabilities of this underlying network. For bandwidth, assume the
7081 // worst case.
7082 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7083 underlyingCaps.getLinkDownstreamBandwidthKbps());
7084 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7085 underlyingCaps.getLinkUpstreamBandwidthKbps());
7086 // If this underlying network is metered, the VPN is metered (it may cost money
7087 // to send packets on this network).
7088 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7089 // If this underlying network is roaming, the VPN is roaming (the billing structure
7090 // is different than the usual, local one).
7091 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7092 // If this underlying network is congested, the VPN is congested (the current
7093 // condition of the network affects the performance of this network).
7094 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7095 // If this network is not suspended, the VPN is not suspended (the VPN
7096 // is able to transfer some data).
7097 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7098 }
7099 }
7100 if (!hadUnderlyingNetworks) {
7101 // No idea what the underlying networks are; assume reasonable defaults
7102 metered = true;
7103 roaming = false;
7104 congested = false;
7105 suspended = false;
7106 }
7107
lifrc33ea4d2021-03-04 14:08:08 +08007108 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007109 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7110 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7111 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7112 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7113 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7114 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007115 }
7116
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007117 /**
Lorenzo Colitti72664112018-01-16 00:52:07 +09007118 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7119 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7120 * and foreground status).
Paul Jensen783c0e02015-06-16 14:27:36 -04007121 */
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09007122 @NonNull
Lorenzo Colitti72664112018-01-16 00:52:07 +09007123 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi2f90b2d2017-08-16 13:19:04 +09007124 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007125 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7126 // causing a connect/teardown loop.
Lorenzo Colitti94c93142020-01-10 00:40:28 +09007127 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007128 // avoid connect/teardown loops.
Lorenzo Colitti72664112018-01-16 00:52:07 +09007129 if (nai.everConnected &&
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007130 !nai.isVPN() &&
Lorenzo Colitti72664112018-01-16 00:52:07 +09007131 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7132 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi2f90b2d2017-08-16 13:19:04 +09007133 // does not cause any request (that is not a listen) currently matching that agent to
7134 // stop being matched by the updated agent.
Lorenzo Colitti72664112018-01-16 00:52:07 +09007135 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi8c928882017-07-25 11:40:56 +09007136 if (!TextUtils.isEmpty(diff)) {
Aaron Huang11e9a312020-10-30 22:04:25 +08007137 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi8c928882017-07-25 11:40:56 +09007138 }
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007139 }
7140
Paul Jensen783c0e02015-06-16 14:27:36 -04007141 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007142 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007143 if (nai.lastValidated) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007144 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen783c0e02015-06-16 14:27:36 -04007145 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007146 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen783c0e02015-06-16 14:27:36 -04007147 }
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007148 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007149 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen783c0e02015-06-16 14:27:36 -04007150 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007151 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen783c0e02015-06-16 14:27:36 -04007152 }
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007153 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007154 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007155 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007156 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007157 }
lucaslin25a50472019-03-12 13:08:03 +08007158 if (nai.partialConnectivity) {
7159 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7160 } else {
7161 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7162 }
lucaslin8cf57f52019-10-22 18:27:33 +08007163 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007164
Chalard Jeanc212ed12020-01-15 00:49:43 +09007165 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeanfa33a752020-01-14 22:46:36 +09007166 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7167 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanc212ed12020-01-15 00:49:43 +09007168 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeanfa33a752020-01-14 22:46:36 +09007169 }
7170
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007171 if (nai.supportsUnderlyingNetworks()) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007172 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7173 newNc);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007174 }
7175
Lorenzo Colitti72664112018-01-16 00:52:07 +09007176 return newNc;
7177 }
7178
Lorenzo Colitti246d1762021-01-11 22:27:57 +09007179 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7180 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7181 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7182 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7183 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7184 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7185 if (prevSuspended != suspended) {
7186 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7187 // onResumed have been removed.
7188 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7189 : ConnectivityManager.CALLBACK_RESUMED);
7190 }
7191 if (prevSuspended != suspended || prevRoaming != roaming) {
7192 // updateNetworkInfo will mix in the suspended info from the capabilities and
7193 // take appropriate action for the network having possibly changed state.
7194 updateNetworkInfo(nai, nai.networkInfo);
7195 }
7196 }
7197
Lorenzo Colitti72664112018-01-16 00:52:07 +09007198 /**
7199 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7200 *
7201 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7202 * capabilities we manage and store in {@code nai}, such as validated status and captive
7203 * portal status)
7204 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7205 * potentially triggers rematches.
7206 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7207 * change.)
7208 *
7209 * @param oldScore score of the network before any of the changes that prompted us
7210 * to call this function.
7211 * @param nai the network having its capabilities updated.
7212 * @param nc the new network capabilities.
7213 */
Chalard Jeana00029d2019-12-02 18:39:29 +09007214 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7215 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007216 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti72664112018-01-16 00:52:07 +09007217 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jeana00029d2019-12-02 18:39:29 +09007218 updateNetworkPermissions(nai, newNc);
Chalard Jean8ffefba2019-11-22 22:39:56 +09007219 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007220
Chalard Jeana39c91c2018-01-16 18:43:05 +09007221 updateUids(nai, prevNc, newNc);
Chalard Jean1fc55292021-03-31 23:19:05 +09007222 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeana39c91c2018-01-16 18:43:05 +09007223
Lorenzo Colitti72664112018-01-16 00:52:07 +09007224 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007225 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7226 // the change we're processing can't affect any requests, it can only affect the listens
7227 // on this network. We might have been called by rematchNetworkAndRequests when a
7228 // network changed foreground state.
Chalard Jeanb9c02722019-12-09 11:50:38 +09007229 processListenRequests(nai);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007230 } else {
7231 // If the requestable capabilities have changed or the score changed, we can't have been
7232 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jean60902092019-11-07 18:54:49 +09007233 rematchAllNetworksAndRequests();
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007234 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07007235 }
Lorenzo Colitti246d1762021-01-11 22:27:57 +09007236 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007237
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007238 final boolean oldMetered = prevNc.isMetered();
7239 final boolean newMetered = newNc.isMetered();
7240 final boolean meteredChanged = oldMetered != newMetered;
junyulai5ab727b2018-08-07 19:50:45 +08007241
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007242 if (meteredChanged) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00007243 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7244 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007245 }
junyulai5ab727b2018-08-07 19:50:45 +08007246
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007247 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7248 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai5ab727b2018-08-07 19:50:45 +08007249
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007250 // Report changes that are interesting for network statistics tracking.
7251 if (meteredChanged || roamingChanged) {
7252 notifyIfacesChangedForNetworkStats();
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007253 }
7254
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007255 // This network might have been underlying another network. Propagate its capabilities.
7256 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce2e6b79f2020-02-20 14:28:31 +08007257
7258 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayev284cb872020-12-07 22:43:07 -08007259 mDnsManager.updateTransportsForNetwork(
7260 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce2e6b79f2020-02-20 14:28:31 +08007261 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007262 }
7263
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09007264 /** Convenience method to update the capabilities for a given network. */
7265 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7266 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7267 }
7268
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007269 /**
7270 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7271 * network.
7272 *
7273 * Ingress interface filtering enforces that all apps under the given network can only receive
7274 * packets from the network's interface (and loopback). This is important for VPNs because
7275 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7276 * non-VPN interfaces.
7277 *
7278 * As a result, this method should return true iff
7279 * 1. the network is an app VPN (not legacy VPN)
7280 * 2. the VPN does not allow bypass
7281 * 3. the VPN is fully-routed
7282 * 4. the VPN interface is non-null
7283 *
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09007284 * @see INetd#firewallAddUidInterfaceRules
7285 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007286 */
7287 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7288 LinkProperties lp) {
7289 if (nc == null || lp == null) return false;
7290 return nai.isVPN()
Lorenzo Colitticf595362020-01-12 22:28:37 +09007291 && !nai.networkAgentConfig.allowBypass
Qingxi Libb3347b2020-01-17 17:54:27 -08007292 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007293 && lp.getInterfaceName() != null
lucaslin62bc2b02020-11-02 16:05:02 +08007294 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7295 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007296 }
7297
Chiachang Wang1f50ae52020-12-10 22:24:47 +08007298 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7299 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7300 int index = 0;
7301 for (UidRange range : ranges) {
7302 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7303 index++;
7304 }
7305 return stableRanges;
7306 }
7307
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09007308 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7309 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7310 for (int i = 0; i < ranges.length; i++) {
7311 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7312 }
7313 return stableRanges;
7314 }
7315
Ken Chenb8e4bc92020-12-24 12:59:10 +08007316 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7317 int[] exemptUids) {
7318 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7319 try {
7320 mNetd.socketDestroy(ranges, exemptUids);
7321 } catch (Exception e) {
7322 loge("Exception in socket destroy: ", e);
7323 }
7324 }
7325 }
7326
7327 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7328 int[] exemptUids = new int[2];
7329 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7330 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7331 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7332 exemptUids[0] = VPN_UID;
7333 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7334 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7335
7336 maybeCloseSockets(nai, ranges, exemptUids);
7337 try {
7338 if (add) {
7339 mNetd.networkAddUidRanges(nai.network.netId, ranges);
7340 } else {
7341 mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
7342 }
7343 } catch (Exception e) {
7344 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7345 " on netId " + nai.network.netId + ". " + e);
7346 }
7347 maybeCloseSockets(nai, ranges, exemptUids);
7348 }
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09007349
Chalard Jeana39c91c2018-01-16 18:43:05 +09007350 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7351 NetworkCapabilities newNc) {
Chiachang Wangd5034c72021-02-22 18:36:38 +08007352 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7353 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeana39c91c2018-01-16 18:43:05 +09007354 if (null == prevRanges) prevRanges = new ArraySet<>();
7355 if (null == newRanges) newRanges = new ArraySet<>();
7356 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7357
7358 prevRanges.removeAll(newRanges);
7359 newRanges.removeAll(prevRangesCopy);
7360
7361 try {
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007362 // When updating the VPN uid routing rules, add the new range first then remove the old
7363 // range. If old range were removed first, there would be a window between the old
7364 // range being removed and the new range being added, during which UIDs contained
7365 // in both ranges are not subject to any VPN routing rules. Adding new range before
7366 // removing old range works because, unlike the filtering rules below, it's possible to
7367 // add duplicate UID routing rules.
Ken Chenb8e4bc92020-12-24 12:59:10 +08007368 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7369 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7370 // [1-5] & [1-2],[4-5] == [3]
7371 // Then we can do:
7372 // maybeCloseSockets([3])
7373 // mNetd.networkAddUidRanges([1-2],[4-5])
7374 // mNetd.networkRemoveUidRanges([1-5])
7375 // maybeCloseSockets([3])
7376 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7377 // number of binder calls from 6 to 4.
Chalard Jeana39c91c2018-01-16 18:43:05 +09007378 if (!newRanges.isEmpty()) {
Ken Chenb8e4bc92020-12-24 12:59:10 +08007379 updateUidRanges(true, nai, newRanges);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007380 }
7381 if (!prevRanges.isEmpty()) {
Ken Chenb8e4bc92020-12-24 12:59:10 +08007382 updateUidRanges(false, nai, prevRanges);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007383 }
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007384 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7385 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7386 final String iface = nai.linkProperties.getInterfaceName();
7387 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jean7f06b342020-05-20 16:11:50 +09007388 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007389 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7390 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7391 // were added first and then newRanges got removed later, there would be only one uid
7392 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7393 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7394 // Note that this is in contrast with the (more robust) update of VPN routing rules
7395 // above, where the addition of new ranges happens before the removal of old ranges.
7396 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7397 // to be removed will never overlap with the new range to be added.
7398 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb3347b2020-01-17 17:54:27 -08007399 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007400 }
7401 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb3347b2020-01-17 17:54:27 -08007402 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007403 }
Chalard Jeana39c91c2018-01-16 18:43:05 +09007404 } catch (Exception e) {
7405 // Never crash!
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007406 loge("Exception in updateUids: ", e);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007407 }
7408 }
7409
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007410 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti7ec341a2019-02-20 21:34:01 +09007411 ensureRunningOnConnectivityServiceThread();
7412
Serik Beketayev284cb872020-12-07 22:43:07 -08007413 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007414 // Ignore updates for disconnected networks
7415 return;
7416 }
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09007417 if (VDBG || DDBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007418 log("Update of LinkProperties for " + nai.toShortString()
7419 + "; created=" + nai.created
7420 + "; everConnected=" + nai.everConnected);
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007421 }
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09007422 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7423 // modify its oldLp parameter.
lucaslin34cd3942018-11-28 12:51:55 +08007424 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007425 }
7426
Jeremy Joslin94c30992014-11-05 10:32:09 -08007427 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7428 int notificationType) {
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007429 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08007430 Intent intent = new Intent();
Jeremy Joslin362093e2014-11-26 14:24:15 -08007431 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattis622428c2020-12-02 14:12:41 -08007432 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7433 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7434 // such an API is ever implemented, there is no doubt the right request to send in
7435 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7436 // be sent as a separate extra.
7437 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007438 nri.mPendingIntentSent = true;
Jeremy Joslin94c30992014-11-05 10:32:09 -08007439 sendIntent(nri.mPendingIntent, intent);
7440 }
7441 // else not handled
7442 }
7443
7444 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7445 mPendingIntentWakeLock.acquire();
7446 try {
7447 if (DBG) log("Sending " + pendingIntent);
7448 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7449 } catch (PendingIntent.CanceledException e) {
7450 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7451 mPendingIntentWakeLock.release();
7452 releasePendingNetworkRequest(pendingIntent);
7453 }
7454 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7455 }
7456
7457 @Override
7458 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7459 String resultData, Bundle resultExtras) {
7460 if (DBG) log("Finished sending " + pendingIntent);
7461 mPendingIntentWakeLock.release();
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007462 // Release with a delay so the receiving client has an opportunity to put in its
7463 // own request.
7464 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08007465 }
7466
James Mattis757e0e82020-12-03 19:57:41 -08007467 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7468 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7469 final int arg1) {
James Mattis6e6fabf2021-01-10 14:24:24 -08007470 if (nri.mMessenger == null) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08007471 // Default request has no msgr. Also prevents callbacks from being invoked for
7472 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7473 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7474 return;
Hugo Benichi4802c802017-03-23 22:40:44 +09007475 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007476 Bundle bundle = new Bundle();
James Mattis757e0e82020-12-03 19:57:41 -08007477 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichi4802c802017-03-23 22:40:44 +09007478 // TODO: check if defensive copies of data is needed.
James Mattise494cbb2021-02-09 18:18:28 -08007479 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis757e0e82020-12-03 19:57:41 -08007480 putParcelable(bundle, nrForCallback);
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007481 Message msg = Message.obtain();
Hugo Benichi4802c802017-03-23 22:40:44 +09007482 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7483 putParcelable(bundle, networkAgent.network);
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007484 }
Roshan Pius7992afd2020-12-22 15:10:42 -08007485 final boolean includeLocationSensitiveInfo =
7486 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007487 switch (notificationType) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09007488 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Libf6bf082020-01-08 12:51:49 -08007489 final NetworkCapabilities nc =
7490 networkCapabilitiesRestrictedForCallerPermissions(
7491 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7492 putParcelable(
7493 bundle,
Roshan Pius423fff62020-12-28 09:01:49 -08007494 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius332e7a22021-03-21 17:55:29 +00007495 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius7992afd2020-12-22 15:10:42 -08007496 nrForCallback.getRequestorPackageName(),
Roshan Piusc97d8062020-12-17 14:53:09 -08007497 nri.mCallingAttributionTag));
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09007498 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7499 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulai5ab727b2018-08-07 19:50:45 +08007500 // For this notification, arg1 contains the blocked status.
7501 msg.arg1 = arg1;
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09007502 break;
7503 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007504 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007505 msg.arg1 = arg1;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007506 break;
7507 }
7508 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanb70f7cc2018-01-26 19:24:40 +09007509 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Libf6bf082020-01-08 12:51:49 -08007510 final NetworkCapabilities netCap =
7511 networkCapabilitiesRestrictedForCallerPermissions(
7512 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7513 putParcelable(
7514 bundle,
Roshan Pius423fff62020-12-28 09:01:49 -08007515 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius332e7a22021-03-21 17:55:29 +00007516 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius7992afd2020-12-22 15:10:42 -08007517 nrForCallback.getRequestorPackageName(),
Roshan Piusc97d8062020-12-17 14:53:09 -08007518 nri.mCallingAttributionTag));
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007519 break;
7520 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007521 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09007522 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7523 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007524 break;
7525 }
junyulai5ab727b2018-08-07 19:50:45 +08007526 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09007527 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulai5ab727b2018-08-07 19:50:45 +08007528 msg.arg1 = arg1;
7529 break;
7530 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007531 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007532 msg.what = notificationType;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007533 msg.setData(bundle);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007534 try {
Robert Greenwalt721f2372014-08-27 14:34:02 -07007535 if (VDBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09007536 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis757e0e82020-12-03 19:57:41 -08007537 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt721f2372014-08-27 14:34:02 -07007538 }
James Mattis6e6fabf2021-01-10 14:24:24 -08007539 nri.mMessenger.send(msg);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007540 } catch (RemoteException e) {
7541 // may occur naturally in the race of binder death.
James Mattis757e0e82020-12-03 19:57:41 -08007542 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007543 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007544 }
7545
Hugo Benichi4802c802017-03-23 22:40:44 +09007546 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7547 bundle.putParcelable(t.getClass().getSimpleName(), t);
7548 }
7549
Paul Jensenab9bdd52014-09-30 15:37:41 -04007550 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09007551 if (nai.numRequestNetworkRequests() != 0) {
7552 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7553 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09007554 // Ignore listening and track default requests.
7555 if (!nr.isRequest()) continue;
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09007556 loge("Dead network still had at least " + nr);
7557 break;
7558 }
Paul Jensenab9bdd52014-09-30 15:37:41 -04007559 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007560 nai.disconnect();
Paul Jensenab9bdd52014-09-30 15:37:41 -04007561 }
7562
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007563 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7564 if (oldNetwork == null) {
7565 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7566 return;
7567 }
Chalard Jean373391b2019-12-10 21:07:02 +09007568 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007569
7570 // If we get here it means that the last linger timeout for this network expired. So there
7571 // must be no other active linger timers, and we must stop lingering.
junyulai2a4f0062021-02-03 20:15:30 +08007572 oldNetwork.clearInactivityState();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007573
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09007574 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007575 // Tear the network down.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007576 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007577 } else {
junyulaif6d98ec2020-12-14 18:41:52 +08007578 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09007579 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007580 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007581 }
7582
James Mattis8af2d602020-12-20 11:09:58 -08007583 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7584 boolean isDefaultChanged = false;
7585 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7586 final NetworkReassignment.RequestReassignment reassignment =
7587 changes.getReassignment(defaultRequestInfo);
7588 if (null == reassignment) {
7589 continue;
7590 }
7591 // reassignment only contains those instances where the satisfying network changed.
7592 isDefaultChanged = true;
7593 // Notify system services of the new default.
7594 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7595 }
Chiachang Wang228b1c32018-09-28 22:42:48 +08007596
James Mattis8af2d602020-12-20 11:09:58 -08007597 if (isDefaultChanged) {
7598 // Hold a wakelock for a short time to help apps in migrating to a new default.
7599 scheduleReleaseNetworkTransitionWakelock();
7600 }
7601 }
7602
7603 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7604 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7605 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7606 if (DBG) {
7607 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7608 }
Chalard Jean337a8032019-12-03 20:45:30 +09007609
James Mattis1238af22020-12-23 16:37:26 -08007610 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7611 if (newDefaultNetwork != null) {
7612 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensen207feb72014-07-14 12:03:33 -04007613 }
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09007614
James Mattis1238af22020-12-23 16:37:26 -08007615 // Set an app level managed default and return since further processing only applies to the
7616 // default network.
7617 if (mDefaultRequest != nri) {
7618 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7619 return;
7620 }
7621
7622 makeDefaultNetwork(newDefaultNetwork);
7623
James Mattis8af2d602020-12-20 11:09:58 -08007624 if (oldDefaultNetwork != null) {
7625 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7626 }
7627 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattis8af2d602020-12-20 11:09:58 -08007628 handleApplyDefaultProxy(null != newDefaultNetwork
7629 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7630 updateTcpBufferSizes(null != newDefaultNetwork
7631 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09007632 notifyIfacesChangedForNetworkStats();
Paul Jensen207feb72014-07-14 12:03:33 -04007633 }
7634
James Mattis1238af22020-12-23 16:37:26 -08007635 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7636 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7637 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7638 try {
7639 if (VDBG) {
7640 log("Setting default network for " + nri
7641 + " using UIDs " + nri.getUids()
7642 + " with old network " + (oldDefaultNetwork != null
7643 ? oldDefaultNetwork.network().getNetId() : "null")
7644 + " and new network " + (newDefaultNetwork != null
7645 ? newDefaultNetwork.network().getNetId() : "null"));
7646 }
7647 if (nri.getUids().isEmpty()) {
7648 throw new IllegalStateException("makeDefaultForApps called without specifying"
7649 + " any applications to set as the default." + nri);
7650 }
7651 if (null != newDefaultNetwork) {
7652 mNetd.networkAddUidRanges(
7653 newDefaultNetwork.network.getNetId(),
7654 toUidRangeStableParcels(nri.getUids()));
7655 }
7656 if (null != oldDefaultNetwork) {
7657 mNetd.networkRemoveUidRanges(
7658 oldDefaultNetwork.network.getNetId(),
7659 toUidRangeStableParcels(nri.getUids()));
7660 }
7661 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09007662 loge("Exception setting app default network", e);
James Mattis1238af22020-12-23 16:37:26 -08007663 }
7664 }
7665
7666 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7667 try {
7668 if (null != newDefaultNetwork) {
7669 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7670 } else {
7671 mNetd.networkClearDefault();
7672 }
7673 } catch (RemoteException | ServiceSpecificException e) {
7674 loge("Exception setting default network :" + e);
7675 }
7676 }
7677
Chalard Jeanb9c02722019-12-09 11:50:38 +09007678 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007679 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007680 processNewlyLostListenRequests(nai);
Chalard Jeanb9c02722019-12-09 11:50:38 +09007681 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007682 processNewlySatisfiedListenRequests(nai);
7683 }
7684
7685 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattis622428c2020-12-02 14:12:41 -08007686 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7687 if (nri.isMultilayerRequest()) {
7688 continue;
7689 }
7690 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007691 if (!nr.isListen()) continue;
7692 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattis622428c2020-12-02 14:12:41 -08007693 nai.removeRequest(nr.requestId);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007694 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7695 }
7696 }
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007697 }
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007698
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007699 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattis622428c2020-12-02 14:12:41 -08007700 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7701 if (nri.isMultilayerRequest()) {
7702 continue;
7703 }
7704 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007705 if (!nr.isListen()) continue;
7706 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7707 nai.addRequest(nr);
Erik Kline81fdc8a2017-02-15 19:59:17 +09007708 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007709 }
7710 }
7711 }
7712
Chalard Jean63cb44d2019-12-02 15:34:05 +09007713 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean63cb44d2019-12-02 15:34:05 +09007714 private static class NetworkReassignment {
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007715 static class RequestReassignment {
James Mattis622428c2020-12-02 14:12:41 -08007716 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jean018dbe42021-03-01 22:16:08 +09007717 @Nullable public final NetworkRequest mOldNetworkRequest;
7718 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007719 @Nullable public final NetworkAgentInfo mOldNetwork;
7720 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattis622428c2020-12-02 14:12:41 -08007721 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jean018dbe42021-03-01 22:16:08 +09007722 @Nullable final NetworkRequest oldNetworkRequest,
7723 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007724 @Nullable final NetworkAgentInfo oldNetwork,
7725 @Nullable final NetworkAgentInfo newNetwork) {
James Mattis622428c2020-12-02 14:12:41 -08007726 mNetworkRequestInfo = networkRequestInfo;
7727 mOldNetworkRequest = oldNetworkRequest;
7728 mNewNetworkRequest = newNetworkRequest;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007729 mOldNetwork = oldNetwork;
7730 mNewNetwork = newNetwork;
7731 }
Chalard Jean373391b2019-12-10 21:07:02 +09007732
7733 public String toString() {
Chalard Jeanad0a6e62021-03-01 22:06:04 +09007734 final NetworkRequest requestToShow = null != mNewNetworkRequest
7735 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7736 return requestToShow.requestId + " : "
Serik Beketayev284cb872020-12-07 22:43:07 -08007737 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7738 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean373391b2019-12-10 21:07:02 +09007739 }
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007740 }
7741
Chalard Jean8049afd2019-12-10 21:25:24 +09007742 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean63cb44d2019-12-02 15:34:05 +09007743
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007744 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean8049afd2019-12-10 21:25:24 +09007745 return mReassignments;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007746 }
7747
7748 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN53e02712021-04-07 19:40:31 +09007749 if (Build.isDebuggable()) {
Chalard Jean8049afd2019-12-10 21:25:24 +09007750 // The code is never supposed to add two reassignments of the same request. Make
7751 // sure this stays true, but without imposing this expensive check on all
7752 // reassignments on all user devices.
7753 for (final RequestReassignment existing : mReassignments) {
James Mattis622428c2020-12-02 14:12:41 -08007754 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean8049afd2019-12-10 21:25:24 +09007755 throw new IllegalStateException("Trying to reassign ["
7756 + reassignment + "] but already have ["
7757 + existing + "]");
7758 }
7759 }
Chalard Jean69369aa2019-12-03 22:16:26 +09007760 }
Chalard Jean8049afd2019-12-10 21:25:24 +09007761 mReassignments.add(reassignment);
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007762 }
7763
Chalard Jean3952fb12019-12-03 14:43:57 +09007764 // Will return null if this reassignment does not change the network assigned to
Chalard Jean337a8032019-12-03 20:45:30 +09007765 // the passed request.
7766 @Nullable
7767 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean3952fb12019-12-03 14:43:57 +09007768 for (final RequestReassignment event : getRequestReassignments()) {
James Mattis622428c2020-12-02 14:12:41 -08007769 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean3952fb12019-12-03 14:43:57 +09007770 }
7771 return null;
7772 }
Chalard Jean373391b2019-12-10 21:07:02 +09007773
7774 public String toString() {
7775 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7776 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jean88e5b872019-12-11 14:12:30 +09007777 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean373391b2019-12-10 21:07:02 +09007778 for (final RequestReassignment rr : getRequestReassignments()) {
7779 sj.add(rr.toString());
7780 }
7781 return sj.toString();
7782 }
7783
7784 public String debugString() {
7785 final StringBuilder sb = new StringBuilder();
7786 sb.append("NetworkReassignment :");
Chalard Jean88e5b872019-12-11 14:12:30 +09007787 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean373391b2019-12-10 21:07:02 +09007788 for (final RequestReassignment rr : getRequestReassignments()) {
7789 sb.append("\n ").append(rr);
7790 }
7791 return sb.append("\n").toString();
7792 }
Chalard Jean63cb44d2019-12-02 15:34:05 +09007793 }
7794
Chalard Jeanf57b9692019-12-04 13:32:31 +09007795 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean018dbe42021-03-01 22:16:08 +09007796 @Nullable final NetworkRequest previousRequest,
7797 @Nullable final NetworkRequest newRequest,
Chalard Jeanf57b9692019-12-04 13:32:31 +09007798 @Nullable final NetworkAgentInfo previousSatisfier,
7799 @Nullable final NetworkAgentInfo newSatisfier,
7800 final long now) {
James Mattis1238af22020-12-23 16:37:26 -08007801 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean373391b2019-12-10 21:07:02 +09007802 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jean018dbe42021-03-01 22:16:08 +09007803 if (null != previousRequest && null != previousSatisfier) {
Chalard Jeanf57b9692019-12-04 13:32:31 +09007804 if (VDBG || DDBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007805 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jeanf57b9692019-12-04 13:32:31 +09007806 }
James Mattis622428c2020-12-02 14:12:41 -08007807 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jeane634b282021-03-05 23:07:53 +09007808 previousSatisfier.lingerRequest(previousRequest.requestId, now);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007809 } else {
7810 if (VDBG || DDBG) log(" accepting network in place of null");
7811 }
junyulaif6d98ec2020-12-14 18:41:52 +08007812
7813 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7814 // and immediately satisfies a request then remove the timer. This will happen for
7815 // all networks except in the case of an underlying network for a VCN.
7816 if (newSatisfier.isNascent()) {
7817 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai2f4a5b32021-03-26 00:40:48 +08007818 newSatisfier.unsetInactive();
junyulaif6d98ec2020-12-14 18:41:52 +08007819 }
7820
Chalard Jeandc974072021-03-01 22:00:20 +09007821 // if newSatisfier is not null, then newRequest may not be null.
James Mattis622428c2020-12-02 14:12:41 -08007822 newSatisfier.unlingerRequest(newRequest.requestId);
7823 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang11e9a312020-10-30 22:04:25 +08007824 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattis622428c2020-12-02 14:12:41 -08007825 + newRequest);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007826 }
Chalard Jean018dbe42021-03-01 22:16:08 +09007827 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jeanf57b9692019-12-04 13:32:31 +09007828 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007829 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattis622428c2020-12-02 14:12:41 -08007830 + " request " + previousRequest.requestId);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007831 }
James Mattis622428c2020-12-02 14:12:41 -08007832 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007833 }
James Mattis622428c2020-12-02 14:12:41 -08007834 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007835 }
7836
James Mattis622428c2020-12-02 14:12:41 -08007837 /**
7838 * This function is triggered when something can affect what network should satisfy what
7839 * request, and it computes the network reassignment from the passed collection of requests to
7840 * network match to the one that the system should now have. That data is encoded in an
7841 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
7842 * satisfier.
7843 *
7844 * After the reassignment is computed, it is applied to the state objects.
7845 *
7846 * @param networkRequests the nri objects to evaluate for possible network reassignment
7847 * @return NetworkReassignment listing of proposed network assignment changes
7848 */
Chalard Jean42909302019-12-10 18:56:30 +09007849 @NonNull
James Mattis622428c2020-12-02 14:12:41 -08007850 private NetworkReassignment computeNetworkReassignment(
7851 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean013fb142019-12-10 21:08:07 +09007852 final NetworkReassignment changes = new NetworkReassignment();
7853
Chalard Jean3d71e302021-04-07 17:06:19 +09007854 // Gather the list of all relevant agents.
Chalard Jean013fb142019-12-10 21:08:07 +09007855 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007856 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis622428c2020-12-02 14:12:41 -08007857 if (!nai.everConnected) {
7858 continue;
7859 }
Chalard Jean013fb142019-12-10 21:08:07 +09007860 nais.add(nai);
Chalard Jean013fb142019-12-10 21:08:07 +09007861 }
Chalard Jean013fb142019-12-10 21:08:07 +09007862
James Mattis622428c2020-12-02 14:12:41 -08007863 for (final NetworkRequestInfo nri : networkRequests) {
7864 // Non-multilayer listen requests can be ignored.
7865 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
7866 continue;
7867 }
7868 NetworkAgentInfo bestNetwork = null;
7869 NetworkRequest bestRequest = null;
7870 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeanb887f602021-03-29 17:03:59 +09007871 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattis622428c2020-12-02 14:12:41 -08007872 // Stop evaluating as the highest possible priority request is satisfied.
7873 if (null != bestNetwork) {
7874 bestRequest = req;
7875 break;
7876 }
7877 }
James Mattis1238af22020-12-23 16:37:26 -08007878 if (null == bestNetwork && isDefaultBlocked(nri)) {
7879 // Remove default networking if disallowed for managed default requests.
7880 bestNetwork = mNoServiceNetwork;
7881 }
7882 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean58d486c2019-12-10 22:16:53 +09007883 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean013fb142019-12-10 21:08:07 +09007884 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattis622428c2020-12-02 14:12:41 -08007885 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean013fb142019-12-10 21:08:07 +09007886 }
Chalard Jean42909302019-12-10 18:56:30 +09007887 }
7888 return changes;
7889 }
7890
James Mattis622428c2020-12-02 14:12:41 -08007891 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
7892 return new HashSet<>(mNetworkRequests.values());
7893 }
7894
Paul Jensen50f38772015-06-16 14:27:36 -04007895 /**
James Mattis622428c2020-12-02 14:12:41 -08007896 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensen50f38772015-06-16 14:27:36 -04007897 * being disconnected.
Paul Jensen50f38772015-06-16 14:27:36 -04007898 */
Chalard Jean60902092019-11-07 18:54:49 +09007899 private void rematchAllNetworksAndRequests() {
James Mattis622428c2020-12-02 14:12:41 -08007900 rematchNetworksAndRequests(getNrisFromGlobalRequests());
7901 }
7902
7903 /**
7904 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
7905 * being disconnected.
7906 */
7907 private void rematchNetworksAndRequests(
7908 @NonNull final Set<NetworkRequestInfo> networkRequests) {
7909 ensureRunningOnConnectivityServiceThread();
Chalard Jean013fb142019-12-10 21:08:07 +09007910 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007911 final long now = SystemClock.elapsedRealtime();
James Mattis622428c2020-12-02 14:12:41 -08007912 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean373391b2019-12-10 21:07:02 +09007913 if (VDBG || DDBG) {
7914 log(changes.debugString());
7915 } else if (DBG) {
7916 log(changes.toString()); // Shorter form, only one line of log
7917 }
Chalard Jean32c20902019-12-10 22:01:31 +09007918 applyNetworkReassignment(changes, now);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09007919 issueNetworkNeeds();
Chalard Jeand4a4a302019-12-10 19:01:29 +09007920 }
Chalard Jean208f81b2019-12-04 19:55:32 +09007921
Chalard Jeand4a4a302019-12-10 19:01:29 +09007922 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jean32c20902019-12-10 22:01:31 +09007923 final long now) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007924 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jean88e5b872019-12-11 14:12:30 +09007925
7926 // Since most of the time there are only 0 or 1 background networks, it would probably
7927 // be more efficient to just use an ArrayList here. TODO : measure performance
7928 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
7929 for (final NetworkAgentInfo nai : nais) {
7930 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
7931 }
7932
Chalard Jeand4a4a302019-12-10 19:01:29 +09007933 // First, update the lists of satisfied requests in the network agents. This is necessary
7934 // because some code later depends on this state to be correct, most prominently computing
7935 // the linger status.
Chalard Jean208f81b2019-12-04 19:55:32 +09007936 for (final NetworkReassignment.RequestReassignment event :
7937 changes.getRequestReassignments()) {
James Mattis622428c2020-12-02 14:12:41 -08007938 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
7939 event.mOldNetworkRequest, event.mNewNetworkRequest,
7940 event.mOldNetwork, event.mNewNetwork,
7941 now);
Chalard Jeana03df692019-11-07 19:05:18 +09007942 }
Chalard Jeandc623312019-11-07 23:16:12 +09007943
James Mattis8af2d602020-12-20 11:09:58 -08007944 // Process default network changes if applicable.
7945 processDefaultNetworkChanges(changes);
Chalard Jean76b04162019-11-19 19:16:48 +09007946
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007947 // Notify requested networks are available after the default net is switched, but
7948 // before LegacyTypeTracker sends legacy broadcasts
7949 for (final NetworkReassignment.RequestReassignment event :
7950 changes.getRequestReassignments()) {
7951 if (null != event.mNewNetwork) {
James Mattis622428c2020-12-02 14:12:41 -08007952 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jeanc1da9302019-12-03 15:55:14 +09007953 } else {
James Mattis622428c2020-12-02 14:12:41 -08007954 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jeanc1da9302019-12-03 15:55:14 +09007955 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007956 }
7957 }
7958
junyulaif6d98ec2020-12-14 18:41:52 +08007959 // Update the inactivity state before processing listen callbacks, because the background
7960 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean1a1d2782019-12-04 20:01:46 +09007961 // just yet though, because they have to be sent after the listens are processed to keep
7962 // backward compatibility.
junyulaif6d98ec2020-12-14 18:41:52 +08007963 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean41bae5c2019-11-19 20:01:10 +09007964 for (final NetworkAgentInfo nai : nais) {
junyulaif6d98ec2020-12-14 18:41:52 +08007965 // Rematching may have altered the inactivity state of some networks, so update all
7966 // inactivity timers. updateInactivityState reads the state from the network agent
7967 // and does nothing if the state has not changed : the source of truth is controlled
7968 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
7969 // have been called while rematching the individual networks above.
junyulai2a4f0062021-02-03 20:15:30 +08007970 if (updateInactivityState(nai, now)) {
junyulaif6d98ec2020-12-14 18:41:52 +08007971 inactiveNetworks.add(nai);
Chalard Jeand915e362019-12-04 18:49:18 +09007972 }
7973 }
7974
Chalard Jean88e5b872019-12-11 14:12:30 +09007975 for (final NetworkAgentInfo nai : nais) {
7976 if (!nai.everConnected) continue;
7977 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007978 // Process listen requests and update capabilities if the background state has
7979 // changed for this network. For consistency with previous behavior, send onLost
7980 // callbacks before onAvailable.
Chalard Jean88e5b872019-12-11 14:12:30 +09007981 processNewlyLostListenRequests(nai);
7982 if (oldBackground != nai.isBackgroundNetwork()) {
7983 applyBackgroundChangeForRematch(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007984 }
Chalard Jean88e5b872019-12-11 14:12:30 +09007985 processNewlySatisfiedListenRequests(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007986 }
7987
junyulaif6d98ec2020-12-14 18:41:52 +08007988 for (final NetworkAgentInfo nai : inactiveNetworks) {
7989 // For nascent networks, if connecting with no foreground request, skip broadcasting
7990 // LOSING for backward compatibility. This is typical when mobile data connected while
7991 // wifi connected with mobile data always-on enabled.
7992 if (nai.isNascent()) continue;
Chalard Jeand915e362019-12-04 18:49:18 +09007993 notifyNetworkLosing(nai, now);
Chalard Jeandc623312019-11-07 23:16:12 +09007994 }
7995
James Mattis8af2d602020-12-20 11:09:58 -08007996 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jean4005aeb2019-11-19 19:23:38 +09007997
Chalard Jeandc623312019-11-07 23:16:12 +09007998 // Tear down all unneeded networks.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007999 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jeana03df692019-11-07 19:05:18 +09008000 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2a4f0062021-02-03 20:15:30 +08008001 if (nai.getInactivityExpiry() > 0) {
Chalard Jeana03df692019-11-07 19:05:18 +09008002 // This network has active linger timers and no requests, but is not
8003 // lingering. Linger it.
8004 //
8005 // One way (the only way?) this can happen if this network is unvalidated
8006 // and became unneeded due to another network improving its score to the
8007 // point where this network will no longer be able to satisfy any requests
8008 // even if it validates.
junyulai2a4f0062021-02-03 20:15:30 +08008009 if (updateInactivityState(nai, now)) {
Chalard Jeand915e362019-12-04 18:49:18 +09008010 notifyNetworkLosing(nai, now);
8011 }
Chalard Jeana03df692019-11-07 19:05:18 +09008012 } else {
Chalard Jean373391b2019-12-10 21:07:02 +09008013 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jeana03df692019-11-07 19:05:18 +09008014 teardownUnneededNetwork(nai);
8015 }
8016 }
Paul Jensen19d1d362014-09-11 11:00:39 -04008017 }
8018 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008019
Chalard Jeana00029d2019-12-02 18:39:29 +09008020 /**
8021 * Apply a change in background state resulting from rematching networks with requests.
8022 *
8023 * During rematch, a network may change background states by starting to satisfy or stopping
8024 * to satisfy a foreground request. Listens don't count for this. When a network changes
8025 * background states, its capabilities need to be updated and callbacks fired for the
8026 * capability change.
8027 *
8028 * @param nai The network that changed background states
8029 */
8030 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8031 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8032 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8033 updateNetworkPermissions(nai, newNc);
8034 nai.getAndSetNetworkCapabilities(newNc);
8035 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8036 }
8037
Chalard Jean4005aeb2019-11-19 19:23:38 +09008038 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattis8af2d602020-12-20 11:09:58 -08008039 @NonNull final NetworkReassignment changes,
Chalard Jean42909302019-12-10 18:56:30 +09008040 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09008041 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8042 changes.getReassignment(mDefaultRequest);
8043 final NetworkAgentInfo oldDefaultNetwork =
8044 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8045 final NetworkAgentInfo newDefaultNetwork =
8046 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattis8af2d602020-12-20 11:09:58 -08008047
Chalard Jean1bc77a92021-02-04 13:12:59 +09008048 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jean76b04162019-11-19 19:16:48 +09008049 // Maintain the illusion : since the legacy API only understands one network at a time,
8050 // if the default network changed, apps should see a disconnected broadcast for the
8051 // old default network before they see a connected broadcast for the new one.
Chalard Jean1bc77a92021-02-04 13:12:59 +09008052 if (oldDefaultNetwork != null) {
8053 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8054 oldDefaultNetwork, true);
Chalard Jean76b04162019-11-19 19:16:48 +09008055 }
Chalard Jean1bc77a92021-02-04 13:12:59 +09008056 if (newDefaultNetwork != null) {
Chalard Jean76b04162019-11-19 19:16:48 +09008057 // The new default network can be newly null if and only if the old default
8058 // network doesn't satisfy the default request any more because it lost a
8059 // capability.
Chalard Jean1bc77a92021-02-04 13:12:59 +09008060 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattis8af2d602020-12-20 11:09:58 -08008061 mLegacyTypeTracker.add(
Chalard Jean1bc77a92021-02-04 13:12:59 +09008062 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jean76b04162019-11-19 19:16:48 +09008063 }
8064 }
8065
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008066 // Now that all the callbacks have been sent, send the legacy network broadcasts
8067 // as needed. This is necessary so that legacy requests correctly bind dns
8068 // requests to this network. The legacy users are listening for this broadcast
8069 // and will generally do a dns request so they can ensureRouteToHost and if
8070 // they do that before the callbacks happen they'll use the default network.
8071 //
8072 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8073 // callbacks, but if apps can receive the broadcast before the callback, they still might
8074 // have an inconsistent view of networking.
8075 //
8076 // This *does* introduce a race where if the user uses the new api
8077 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8078 // they may get old info. Reverse this after the old startUsing api is removed.
8079 // This is on top of the multiple intent sequencing referenced in the todo above.
8080 for (NetworkAgentInfo nai : nais) {
Chalard Jean88e5b872019-12-11 14:12:30 +09008081 if (nai.everConnected) {
8082 addNetworkToLegacyTypeTracker(nai);
8083 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008084 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008085 }
8086
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008087 private void issueNetworkNeeds() {
8088 ensureRunningOnConnectivityServiceThread();
8089 for (final NetworkOfferInfo noi : mNetworkOffers) {
8090 issueNetworkNeeds(noi);
8091 }
8092 }
8093
8094 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8095 ensureRunningOnConnectivityServiceThread();
8096 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8097 informOffer(nri, noi.offer, mNetworkRanker);
8098 }
8099 }
8100
8101 /**
8102 * Inform a NetworkOffer about any new situation of a request.
8103 *
8104 * This function handles updates to offers. A number of events may happen that require
8105 * updating the registrant for this offer about the situation :
8106 * • The offer itself was updated. This may lead the offer to no longer being able
8107 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8108 * or conversely being strengthened enough to beat the satisfier (and therefore
8109 * start being needed)
8110 * • The network satisfying a request changed (including cases where the request
8111 * starts or stops being satisfied). The new network may be a stronger or weaker
8112 * match than the old one, possibly affecting whether the offer is needed.
8113 * • The network satisfying a request updated their score. This may lead the offer
8114 * to no longer be able to beat it if the current satisfier got better, or
8115 * conversely start being a good choice if the current satisfier got weaker.
8116 *
8117 * @param nri The request
8118 * @param offer The offer. This may be an updated offer.
8119 */
8120 private static void informOffer(@NonNull NetworkRequestInfo nri,
8121 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8122 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8123 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008124
8125 // Multi-layer requests have a currently active request, the one being satisfied.
8126 // Since the system will try to bring up a better network than is currently satisfying
8127 // the request, NetworkProviders need to be told the offers matching the requests *above*
8128 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8129 // not needed, and the offer is needed for the active request iff the offer can beat
8130 // the satisfier.
8131 // For non-multilayer requests, the logic above gracefully degenerates to only the
8132 // last case.
8133 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8134 // providers that the offer is needed for this request, until the active request is found.
8135 // In a second phase, deal with the currently active request. In a third phase, inform
8136 // the providers that offer is unneeded for the remaining requests.
8137
8138 // First phase : inform providers of all requests above the active request.
8139 int i;
8140 for (i = 0; nri.mRequests.size() > i; ++i) {
8141 final NetworkRequest request = nri.mRequests.get(i);
8142 if (activeRequest == request) break; // Found the active request : go to phase 2
8143 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8144 // Since this request is higher-priority than the one currently satisfied, if the
8145 // offer can satisfy it, the provider should try and bring up the network for sure ;
8146 // no need to even ask the ranker – an offer that can satisfy is always better than
8147 // no network. Hence tell the provider so unless it already knew.
8148 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8149 offer.onNetworkNeeded(request);
8150 }
8151 }
8152
8153 // Second phase : deal with the active request (if any)
8154 if (null != activeRequest && activeRequest.isRequest()) {
8155 final boolean oldNeeded = offer.neededFor(activeRequest);
8156 // An offer is needed if it is currently served by this provider or if this offer
8157 // can beat the current satisfier.
8158 final boolean currentlyServing = satisfier != null
8159 && satisfier.factorySerialNumber == offer.providerId;
8160 final boolean newNeeded = (currentlyServing
8161 || (activeRequest.canBeSatisfiedBy(offer.caps)
Chalard Jeanb887f602021-03-29 17:03:59 +09008162 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008163 if (newNeeded != oldNeeded) {
8164 if (newNeeded) {
8165 offer.onNetworkNeeded(activeRequest);
8166 } else {
8167 // The offer used to be able to beat the satisfier. Now it can't.
8168 offer.onNetworkUnneeded(activeRequest);
8169 }
8170 }
8171 }
8172
8173 // Third phase : inform the providers that the offer isn't needed for any request
8174 // below the active one.
8175 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8176 final NetworkRequest request = nri.mRequests.get(i);
8177 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8178 // Since this request is lower-priority than the one currently satisfied, if the
8179 // offer can satisfy it, the provider should not try and bring up the network.
8180 // Hence tell the provider so unless it already knew.
8181 if (offer.neededFor(request)) {
8182 offer.onNetworkUnneeded(request);
8183 }
8184 }
8185 }
8186
Chalard Jean9fdd38a2019-11-07 23:07:32 +09008187 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8188 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8189 NetworkRequest nr = nai.requestAt(i);
8190 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8191 // legacy type tracker filters out repeat adds
8192 mLegacyTypeTracker.add(nr.legacyType, nai);
8193 }
8194 }
8195
8196 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean1bc77a92021-02-04 13:12:59 +09008197 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean9fdd38a2019-11-07 23:07:32 +09008198 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8199 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8200 if (nai.isVPN()) {
8201 mLegacyTypeTracker.add(TYPE_VPN, nai);
8202 }
8203 }
8204
Lorenzo Colittiaf3f8552014-12-17 11:26:49 +09008205 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen5877e732014-09-05 12:06:44 -04008206 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colitti80a0b532014-12-17 11:14:42 +09008207 if (!nai.everValidated) return;
Chalard Jean1bc77a92021-02-04 13:12:59 +09008208 // For now only update icons for the default connection.
Paul Jensen5877e732014-09-05 12:06:44 -04008209 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean1bc77a92021-02-04 13:12:59 +09008210 if (!isDefaultNetwork(nai)) return;
Paul Jensen5877e732014-09-05 12:06:44 -04008211
Lorenzo Colittiaf3f8552014-12-17 11:26:49 +09008212 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen5877e732014-09-05 12:06:44 -04008213 // Don't repeat publish.
8214 if (newInetCondition == mDefaultInetConditionPublished) return;
8215
8216 mDefaultInetConditionPublished = newInetCondition;
8217 sendInetConditionBroadcast(nai.networkInfo);
8218 }
8219
Chalard Jeanfa33a752020-01-14 22:46:36 +09008220 @NonNull
8221 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8222 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanc212ed12020-01-15 00:49:43 +09008223 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeanfa33a752020-01-14 22:46:36 +09008224 final boolean suspended =
8225 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8226 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8227 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8228 // state. This is because the network could have been suspended before connecting,
8229 // or it could be disconnecting while being suspended, and in both these cases
8230 // the state should not be overridden. Note that the only detailed state that
8231 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8232 // worry about multiple different substates of CONNECTED.
8233 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8234 info.getExtraInfo());
Chiachang Wang59f5d112020-02-12 17:01:59 +08008235 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8236 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8237 // network agent is created, then goes to suspended, then goes out of suspended without
8238 // ever setting connected. Check if network agent is ever connected to update the state.
8239 newInfo.setDetailedState(nai.everConnected
8240 ? NetworkInfo.DetailedState.CONNECTED
8241 : NetworkInfo.DetailedState.CONNECTING,
8242 info.getReason(),
8243 info.getExtraInfo());
Chalard Jeanfa33a752020-01-14 22:46:36 +09008244 }
Chalard Jeanc212ed12020-01-15 00:49:43 +09008245 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeanfa33a752020-01-14 22:46:36 +09008246 return newInfo;
8247 }
8248
8249 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8250 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8251
Erik Kline81fdc8a2017-02-15 19:59:17 +09008252 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07008253 NetworkInfo oldInfo = null;
8254 synchronized (networkAgent) {
8255 oldInfo = networkAgent.networkInfo;
8256 networkAgent.networkInfo = newInfo;
8257 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008258
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008259 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09008260 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8261 + oldInfo.getState() + " to " + state);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008262 }
Robert Greenwalt54d534f2014-05-13 21:41:06 -07008263
Robin Leebc024e52016-05-01 23:00:00 +01008264 if (!networkAgent.created
8265 && (state == NetworkInfo.State.CONNECTED
8266 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09008267
8268 // A network that has just connected has zero requests and is thus a foreground network.
8269 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8270
Luke Huang135c5262019-04-09 18:41:49 +08008271 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti01d37632020-12-02 00:48:09 +09008272 if (networkAgent.supportsUnderlyingNetworks()) {
8273 // Initialize the network's capabilities to their starting values according to the
8274 // underlying networks. This ensures that the capabilities are correct before
8275 // anything happens to the network.
8276 updateCapabilitiesForNetwork(networkAgent);
Chalard Jean8c5e4582020-05-07 12:07:03 +09008277 }
Paul Jensen956fa9f2014-08-04 12:21:19 -04008278 networkAgent.created = true;
Chiachang Wang85d72bd2021-03-24 18:39:17 +08008279 networkAgent.onNetworkCreated();
Robin Leebc024e52016-05-01 23:00:00 +01008280 }
8281
8282 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8283 networkAgent.everConnected = true;
8284
lucaslinb2d10842019-04-03 17:09:28 +08008285 // NetworkCapabilities need to be set before sending the private DNS config to
8286 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean8ffefba2019-11-22 22:39:56 +09008287 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8288
Erik Kline076bd3d2018-03-21 07:18:33 -07008289 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin34cd3942018-11-28 12:51:55 +08008290 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8291 null);
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008292
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09008293 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8294 // command must be sent after updating LinkProperties to maximize chances of
8295 // NetworkMonitor seeing the correct LinkProperties when starting.
8296 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colitticf595362020-01-12 22:28:37 +09008297 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti260d9982019-05-31 15:41:29 +09008298 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09008299 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09008300 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VAN3b1d8b42020-05-10 16:11:11 +09008301 new LinkProperties(networkAgent.linkProperties,
8302 true /* parcelSensitiveFields */),
8303 networkAgent.networkCapabilities);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09008304 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008305
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09008306 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8307 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8308 // capabilities, so it only needs to be done once on initial connect, not every time the
8309 // network's capabilities change. Note that we do this before rematching the network,
8310 // so we could decide to tear it down immediately afterwards. That's fine though - on
8311 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8312 // doing.
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09008313 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09008314
junyulaif6d98ec2020-12-14 18:41:52 +08008315 // Before first rematching networks, put an inactivity timer without any request, this
8316 // allows {@code updateInactivityState} to update the state accordingly and prevent
8317 // tearing down for any {@code unneeded} evaluation in this period.
8318 // Note that the timer will not be rescheduled since the expiry time is
8319 // fixed after connection regardless of the network satisfying other requests or not.
8320 // But it will be removed as soon as the network satisfies a request for the first time.
8321 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8322 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai2f4a5b32021-03-26 00:40:48 +08008323 networkAgent.setInactive();
junyulaif6d98ec2020-12-14 18:41:52 +08008324
Paul Jensen19d1d362014-09-11 11:00:39 -04008325 // Consider network even though it is not yet validated.
Chalard Jean60902092019-11-07 18:54:49 +09008326 rematchAllNetworksAndRequests();
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008327
8328 // This has to happen after matching the requests, because callbacks are just requests.
8329 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008330 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008331 networkAgent.disconnect();
Paul Jensena8a49e02014-05-07 15:27:40 -04008332 if (networkAgent.isVPN()) {
Chalard Jeana39c91c2018-01-16 18:43:05 +09008333 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensena8a49e02014-05-07 15:27:40 -04008334 }
Chalard Jeanefaf6532018-05-11 20:19:20 +09008335 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00008336 if (networkAgent.isVPN()) {
8337 // As the active or bound network changes for apps, broadcast the default proxy, as
8338 // apps may need to update their proxy data. This is called after disconnecting from
8339 // VPN to make sure we do not broadcast the old proxy data.
8340 // TODO(b/122649188): send the broadcast only to VPN users.
8341 mProxyTracker.sendProxyBroadcast();
8342 }
Yintang Gu4bb19242019-06-18 14:24:32 +08008343 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8344 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008345 mLegacyTypeTracker.update(networkAgent);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008346 }
8347 }
8348
Chalard Jeandd753522020-12-21 18:36:52 +09008349 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jeande419812020-03-04 17:45:08 +09008350 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8351 nai.setScore(score);
Chalard Jean60902092019-11-07 18:54:49 +09008352 rematchAllNetworksAndRequests();
Robert Greenwaltcf82b832014-05-27 13:20:24 -07008353 }
8354
Erik Kline81fdc8a2017-02-15 19:59:17 +09008355 // Notify only this one new request of the current state. Transfer all the
8356 // current state by calling NetworkCapabilities and LinkProperties callbacks
8357 // so that callers can be guaranteed to have as close to atomicity in state
8358 // transfer as can be supported by this current API.
8359 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen88087222016-10-27 15:05:50 -07008360 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline81fdc8a2017-02-15 19:59:17 +09008361 if (nri.mPendingIntent != null) {
8362 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8363 // Attempt no subsequent state pushes where intents are involved.
8364 return;
Jeremy Joslin94c30992014-11-05 10:32:09 -08008365 }
Erik Kline81fdc8a2017-02-15 19:59:17 +09008366
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008367 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulai5ab727b2018-08-07 19:50:45 +08008368 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008369 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8370 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8371 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulai5ab727b2018-08-07 19:50:45 +08008372 }
8373
Chalard Jeand915e362019-12-04 18:49:18 +09008374 // Notify the requests on this NAI that the network is now lingered.
8375 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2a4f0062021-02-03 20:15:30 +08008376 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jeand915e362019-12-04 18:49:18 +09008377 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8378 }
8379
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008380 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8381 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8382 return vpnBlocked
8383 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8384 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8385 }
8386
8387 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8388 if (blockedReasons == BLOCKED_REASON_NONE) {
8389 mUidBlockedReasons.delete(uid);
8390 } else {
8391 mUidBlockedReasons.put(uid, blockedReasons);
8392 }
8393 }
8394
junyulai5ab727b2018-08-07 19:50:45 +08008395 /**
8396 * Notify of the blocked state apps with a registered callback matching a given NAI.
8397 *
8398 * Unlike other callbacks, blocked status is different between each individual uid. So for
8399 * any given nai, all requests need to be considered according to the uid who filed it.
8400 *
8401 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008402 * @param oldMetered True if the previous network capabilities were metered.
8403 * @param newMetered True if the current network capabilities are metered.
8404 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8405 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulai5ab727b2018-08-07 19:50:45 +08008406 */
8407 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008408 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8409 List<UidRange> newBlockedUidRanges) {
junyulai5ab727b2018-08-07 19:50:45 +08008410
8411 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8412 NetworkRequest nr = nai.requestAt(i);
8413 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008414
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008415 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8416 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8417 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colittif2514122021-03-12 22:50:57 +09008418 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008419 : oldVpnBlocked;
8420
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008421 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8422 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8423 if (oldBlockedState != newBlockedState) {
junyulai5ab727b2018-08-07 19:50:45 +08008424 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008425 newBlockedState);
junyulai5ab727b2018-08-07 19:50:45 +08008426 }
8427 }
8428 }
8429
8430 /**
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008431 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulai5ab727b2018-08-07 19:50:45 +08008432 * @param uid The uid for which the rules changed.
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008433 * @param blockedReasons The reasons for why an uid is blocked.
junyulai5ab727b2018-08-07 19:50:45 +08008434 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008435 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008436 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai5ab727b2018-08-07 19:50:45 +08008437 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008438 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008439
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008440 final int oldBlockedState = getBlockedState(
8441 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8442 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8443 if (oldBlockedState == newBlockedState) {
junyulaiec82da12019-04-08 16:58:22 +08008444 continue;
junyulai5ab727b2018-08-07 19:50:45 +08008445 }
junyulai5ab727b2018-08-07 19:50:45 +08008446 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8447 NetworkRequest nr = nai.requestAt(i);
8448 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colittif2514122021-03-12 22:50:57 +09008449 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008450 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8451 newBlockedState);
junyulai5ab727b2018-08-07 19:50:45 +08008452 }
8453 }
8454 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07008455 }
8456
Chalard Jean8cc4e872019-04-10 23:07:55 +09008457 @VisibleForTesting
8458 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittid55162b2014-07-31 23:20:17 +09008459 // The NetworkInfo we actually send out has no bearing on the real
8460 // state of affairs. For example, if the default connection is mobile,
8461 // and a request for HIPRI has just gone away, we need to pretend that
8462 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8463 // the state to DISCONNECTED, even though the network is of type MOBILE
8464 // and is still connected.
8465 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8466 info.setType(type);
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09008467 filterForLegacyLockdown(info);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008468 if (state != DetailedState.DISCONNECTED) {
8469 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klinee2d50122014-12-08 16:25:20 +09008470 sendConnectedBroadcast(info);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008471 } else {
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008472 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt5a367872014-06-02 15:32:02 -07008473 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8474 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8475 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8476 if (info.isFailover()) {
8477 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8478 nai.networkInfo.setFailover(false);
8479 }
8480 if (info.getReason() != null) {
8481 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8482 }
8483 if (info.getExtraInfo() != null) {
8484 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8485 }
8486 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean1bc77a92021-02-04 13:12:59 +09008487 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattisf61f7be2021-01-31 17:06:19 -08008488 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt5a367872014-06-02 15:32:02 -07008489 if (newDefaultAgent != null) {
8490 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8491 newDefaultAgent.networkInfo);
8492 } else {
8493 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8494 }
8495 }
8496 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8497 mDefaultInetConditionPublished);
Erik Klinee2d50122014-12-08 16:25:20 +09008498 sendStickyBroadcast(intent);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008499 if (newDefaultAgent != null) {
Erik Klinee2d50122014-12-08 16:25:20 +09008500 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008501 }
8502 }
8503 }
8504
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008505 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09008506 if (VDBG || DDBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09008507 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean373391b2019-12-10 21:07:02 +09008508 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09008509 }
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09008510 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8511 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07008512 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8513 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin94c30992014-11-05 10:32:09 -08008514 if (nri.mPendingIntent == null) {
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008515 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin94c30992014-11-05 10:32:09 -08008516 } else {
8517 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8518 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008519 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008520 }
Robert Greenwalt54d534f2014-05-13 21:41:06 -07008521
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008522 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8523 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8524 }
8525
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008526 /**
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008527 * Returns the list of all interfaces that could be used by network traffic that does not
8528 * explicitly specify a network. This includes the default network, but also all VPNs that are
8529 * currently connected.
8530 *
8531 * Must be called on the handler thread.
8532 */
junyulaic9a235a2021-01-26 15:29:15 +08008533 @NonNull
8534 private ArrayList<Network> getDefaultNetworks() {
Varun Anand5e980f42019-02-07 14:13:13 -08008535 ensureRunningOnConnectivityServiceThread();
James Mattis8af2d602020-12-20 11:09:58 -08008536 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattisf61f7be2021-01-31 17:06:19 -08008537 final Set<Integer> activeNetIds = new ArraySet<>();
8538 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8539 if (nri.isBeingSatisfied()) {
8540 activeNetIds.add(nri.getSatisfier().network().netId);
8541 }
8542 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008543 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisf61f7be2021-01-31 17:06:19 -08008544 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008545 defaultNetworks.add(nai.network);
8546 }
8547 }
junyulaic9a235a2021-01-26 15:29:15 +08008548 return defaultNetworks;
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008549 }
8550
8551 /**
Lorenzo Colittif8a48e12019-06-24 13:50:45 +09008552 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8553 * active iface's tracked properties has changed.
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008554 */
Jeff Davidson9804c892016-01-20 11:35:38 -08008555 private void notifyIfacesChangedForNetworkStats() {
Varun Anand5e980f42019-02-07 14:13:13 -08008556 ensureRunningOnConnectivityServiceThread();
8557 String activeIface = null;
8558 LinkProperties activeLinkProperties = getActiveLinkProperties();
8559 if (activeLinkProperties != null) {
8560 activeIface = activeLinkProperties.getInterfaceName();
8561 }
Benedict Wongb98e0692019-06-12 17:46:31 +00008562
junyulai62d35f72021-01-23 09:46:34 +08008563 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008564 try {
junyulai527859f2021-01-22 22:46:01 +08008565 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
8566 // TODO: Directly use NetworkStateSnapshot when feasible.
8567 for (final NetworkState state : getAllNetworkState()) {
junyulaic6e83552020-12-30 19:03:32 +08008568 final NetworkStateSnapshot snapshot = new NetworkStateSnapshot(state.network,
8569 state.networkCapabilities, state.linkProperties, state.subscriberId,
junyulai527859f2021-01-22 22:46:01 +08008570 state.legacyNetworkType);
8571 snapshots.add(snapshot);
8572 }
junyulaic9a235a2021-01-26 15:29:15 +08008573 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8574 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008575 } catch (Exception ignored) {
8576 }
8577 }
8578
Sreeram Ramachandran1892fa52014-07-27 14:18:26 -07008579 @Override
Udam Saini53b71ee2016-01-04 12:16:14 -08008580 public String getCaptivePortalServerUrl() {
paulhud70b7dd2019-08-12 16:25:11 +08008581 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09008582 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09008583 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgren741013d2018-12-07 11:08:04 +01008584
8585 if (!TextUtils.isEmpty(settingUrl)) {
8586 return settingUrl;
8587 }
8588
8589 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08008590 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgren741013d2018-12-07 11:08:04 +01008591 if (!TextUtils.isEmpty(settingUrl)) {
8592 return settingUrl;
8593 }
8594
8595 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Saini53b71ee2016-01-04 12:16:14 -08008596 }
8597
8598 @Override
junyulai9f872232019-01-16 20:23:34 +08008599 public void startNattKeepalive(Network network, int intervalSeconds,
8600 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008601 enforceKeepalivePermission();
8602 mKeepaliveTracker.startNattKeepalive(
junyulai61143782019-03-04 22:45:36 +08008603 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai9f872232019-01-16 20:23:34 +08008604 intervalSeconds, cb,
junyulai21c06d02019-01-03 18:50:15 +08008605 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008606 }
8607
8608 @Override
Chiachang Wang979f46a2021-01-19 15:35:03 +08008609 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai9f872232019-01-16 20:23:34 +08008610 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai48a59382019-01-15 11:32:44 +08008611 String dstAddr) {
Josh Gaobd97cc82020-06-16 15:58:11 -07008612 try {
Chiachang Wang979f46a2021-01-19 15:35:03 +08008613 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gaobd97cc82020-06-16 15:58:11 -07008614 mKeepaliveTracker.startNattKeepalive(
8615 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8616 intervalSeconds, cb,
8617 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8618 } finally {
8619 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8620 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang979f46a2021-01-19 15:35:03 +08008621 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8622 IoUtils.closeQuietly(pfd);
Josh Gaobd97cc82020-06-16 15:58:11 -07008623 }
8624 }
junyulai48a59382019-01-15 11:32:44 +08008625 }
8626
8627 @Override
Chiachang Wang979f46a2021-01-19 15:35:03 +08008628 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai9f872232019-01-16 20:23:34 +08008629 ISocketKeepaliveCallback cb) {
Josh Gaobd97cc82020-06-16 15:58:11 -07008630 try {
8631 enforceKeepalivePermission();
Chiachang Wang979f46a2021-01-19 15:35:03 +08008632 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gaobd97cc82020-06-16 15:58:11 -07008633 mKeepaliveTracker.startTcpKeepalive(
8634 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8635 } finally {
8636 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8637 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang979f46a2021-01-19 15:35:03 +08008638 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8639 IoUtils.closeQuietly(pfd);
Josh Gaobd97cc82020-06-16 15:58:11 -07008640 }
8641 }
junyulaic7ea1242019-01-08 20:04:33 +08008642 }
8643
8644 @Override
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008645 public void stopKeepalive(Network network, int slot) {
8646 mHandler.sendMessage(mHandler.obtainMessage(
junyulai21c06d02019-01-03 18:50:15 +08008647 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008648 }
8649
8650 @Override
Stuart Scottca888bf2015-04-02 18:00:02 -07008651 public void factoryReset() {
paulhud70b7dd2019-08-12 16:25:11 +08008652 enforceSettingsPermission();
Stuart Scott493cca02015-04-20 14:07:45 -07008653
8654 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
8655 return;
8656 }
8657
lucaslin86086772020-12-17 04:14:35 +08008658 final long token = Binder.clearCallingIdentity();
8659 try {
Heemin Seogd5085f32019-06-12 09:21:44 -07008660 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8661 ipMemoryStore.factoryReset();
lucaslin86086772020-12-17 04:14:35 +08008662 } finally {
8663 Binder.restoreCallingIdentity(token);
8664 }
Xiao Ma51410062019-04-10 19:01:52 +09008665
Stuart Scottca888bf2015-04-02 18:00:02 -07008666 // Turn airplane mode off
8667 setAirplaneMode(false);
8668
Xiao Ma00ed6182019-06-12 16:31:14 +09008669 // restore private DNS settings to default mode (opportunistic)
8670 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_PRIVATE_DNS)) {
lucaslin30779882021-04-23 21:03:39 +08008671 ConnectivitySettingsManager.setPrivateDnsMode(mContext, PRIVATE_DNS_MODE_OPPORTUNISTIC);
Xiao Ma00ed6182019-06-12 16:31:14 +09008672 }
8673
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09008674 Settings.Global.putString(mContext.getContentResolver(),
paulhu1510c9c2021-03-17 17:19:09 +08008675 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottca888bf2015-04-02 18:00:02 -07008676 }
Paul Jensen8c23d5f2015-07-01 14:16:32 -04008677
Ricky Waid53cf002018-01-23 04:09:45 +00008678 @Override
8679 public byte[] getNetworkWatchlistConfigHash() {
8680 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8681 if (nwm == null) {
8682 loge("Unable to get NetworkWatchlistManager");
8683 return null;
8684 }
8685 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8686 return nwm.getWatchlistConfigHash();
8687 }
8688
Hugo Benichi3bdc8352016-05-31 16:28:06 +09008689 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiad9dc5b2017-11-11 08:06:43 +09008690 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayev284cb872020-12-07 22:43:07 -08008691 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Kline2e815d32016-04-14 17:30:59 +09008692 }
Hugo Benichi7f919fe2017-04-21 15:07:12 +09008693
8694 private static boolean toBool(int encodedBoolean) {
8695 return encodedBoolean != 0; // Only 0 means false.
8696 }
8697
8698 private static int encodeBool(boolean b) {
8699 return b ? 1 : 0;
8700 }
mswest46c6a5bcf2018-03-12 10:34:34 -07008701
8702 @Override
Chiachang Wang0efaff82020-10-12 15:20:07 +08008703 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8704 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8705 @NonNull String[] args) {
8706 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8707 err.getFileDescriptor(), args);
mswest46c6a5bcf2018-03-12 10:34:34 -07008708 }
8709
Chiachang Wang0efaff82020-10-12 15:20:07 +08008710 private class ShellCmd extends BasicShellCommandHandler {
mswest46c6a5bcf2018-03-12 10:34:34 -07008711 @Override
8712 public int onCommand(String cmd) {
8713 if (cmd == null) {
8714 return handleDefaultCommands(cmd);
8715 }
8716 final PrintWriter pw = getOutPrintWriter();
8717 try {
8718 switch (cmd) {
8719 case "airplane-mode":
8720 final String action = getNextArg();
8721 if ("enable".equals(action)) {
8722 setAirplaneMode(true);
8723 return 0;
8724 } else if ("disable".equals(action)) {
8725 setAirplaneMode(false);
8726 return 0;
8727 } else if (action == null) {
8728 final ContentResolver cr = mContext.getContentResolver();
8729 final int enabled = Settings.Global.getInt(cr,
8730 Settings.Global.AIRPLANE_MODE_ON);
8731 pw.println(enabled == 0 ? "disabled" : "enabled");
8732 return 0;
8733 } else {
8734 onHelp();
8735 return -1;
8736 }
8737 default:
8738 return handleDefaultCommands(cmd);
8739 }
8740 } catch (Exception e) {
8741 pw.println(e);
8742 }
8743 return -1;
8744 }
8745
8746 @Override
8747 public void onHelp() {
8748 PrintWriter pw = getOutPrintWriter();
8749 pw.println("Connectivity service commands:");
8750 pw.println(" help");
8751 pw.println(" Print this help text.");
8752 pw.println(" airplane-mode [enable|disable]");
8753 pw.println(" Turn airplane mode on or off.");
8754 pw.println(" airplane-mode");
8755 pw.println(" Get airplane mode.");
8756 }
8757 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008758
Remi NGUYEN VAN52950ed2021-03-06 00:11:24 +09008759 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittibd015f42021-02-04 00:18:27 +09008760 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8761 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8762 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang2e98f6c2021-04-20 15:41:24 +08008763 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008764 }
8765
8766 /**
8767 * @param connectionInfo the connection to resolve.
8768 * @return {@code uid} if the connection is found and the app has permission to observe it
8769 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8770 * connection is not found.
8771 */
8772 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008773 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8774 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8775 }
8776
Lorenzo Colittidbcd5d62021-02-04 01:47:38 +09008777 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008778 connectionInfo.local, connectionInfo.remote);
8779
Lorenzo Colittibd015f42021-02-04 00:18:27 +09008780 if (uid == INVALID_UID) return uid; // Not found.
8781
8782 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8783 // VPN, if any, that applies to the UID that owns the connection.
8784 if (checkNetworkStackPermission()) return uid;
8785
8786 final NetworkAgentInfo vpn = getVpnForUid(uid);
8787 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colittie0857092021-03-12 22:39:08 +09008788 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008789 return INVALID_UID;
8790 }
8791
8792 return uid;
8793 }
Pavel Grafov23d65702018-12-14 13:51:07 +00008794
Benedict Wong7f6071d2018-11-09 14:45:34 -08008795 /**
8796 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8797 *
8798 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8799 */
8800 @Override
8801 public IBinder startOrGetTestNetworkService() {
8802 synchronized (mTNSLock) {
8803 TestNetworkService.enforceTestNetworkPermissions(mContext);
8804
8805 if (mTNS == null) {
lucaslind5d3dc12021-02-24 13:49:42 +08008806 mTNS = new TestNetworkService(mContext);
Benedict Wong7f6071d2018-11-09 14:45:34 -08008807 }
8808
8809 return mTNS;
8810 }
8811 }
Cody Kesting9c69dd42019-12-17 12:55:28 -08008812
Cody Kesting0ffbf922019-12-18 10:57:50 -08008813 /**
8814 * Handler used for managing all Connectivity Diagnostics related functions.
8815 *
8816 * @see android.net.ConnectivityDiagnosticsManager
8817 *
8818 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8819 */
8820 @VisibleForTesting
8821 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kestinga58c07c2020-01-07 11:18:54 -08008822 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8823
Cody Kesting0ffbf922019-12-18 10:57:50 -08008824 /**
8825 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8826 * android.net.ConnectivityDiagnosticsManager}.
8827 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8828 * NetworkRequestInfo to be registered
8829 */
8830 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8831
8832 /**
8833 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
8834 * android.net.ConnectivityDiagnosticsManager}.
8835 * obj = the IConnectivityDiagnosticsCallback to be unregistered
8836 * arg1 = the uid of the caller
8837 */
8838 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
8839
Cody Kestingd292a332020-01-05 14:06:39 -08008840 /**
8841 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
8842 * after processing {@link #EVENT_NETWORK_TESTED} events.
8843 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
8844 * NetworkMonitor.
8845 * data = PersistableBundle of extras passed from NetworkMonitor.
8846 *
8847 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
8848 */
8849 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
8850
Cody Kesting1d326382020-01-06 16:55:35 -08008851 /**
8852 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
8853 * been detected on the network.
8854 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
8855 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
8856 * arg2 = NetID.
8857 * data = PersistableBundle of extras passed from NetworkMonitor.
8858 */
8859 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
8860
Cody Kestinga58c07c2020-01-07 11:18:54 -08008861 /**
8862 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
8863 * the platform. This event will invoke {@link
8864 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
8865 * callbacks.
8866 * obj = Network that was reported on
8867 * arg1 = boolint for the quality reported
8868 */
8869 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
8870
Cody Kesting0ffbf922019-12-18 10:57:50 -08008871 private ConnectivityDiagnosticsHandler(Looper looper) {
8872 super(looper);
8873 }
8874
8875 @Override
8876 public void handleMessage(Message msg) {
8877 switch (msg.what) {
8878 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8879 handleRegisterConnectivityDiagnosticsCallback(
8880 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
8881 break;
8882 }
8883 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8884 handleUnregisterConnectivityDiagnosticsCallback(
8885 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
8886 break;
8887 }
Cody Kestingd292a332020-01-05 14:06:39 -08008888 case EVENT_NETWORK_TESTED: {
8889 final ConnectivityReportEvent reportEvent =
8890 (ConnectivityReportEvent) msg.obj;
8891
Aaron Huang0d1be642021-01-21 15:47:41 +08008892 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kestingd292a332020-01-05 14:06:39 -08008893 break;
8894 }
Cody Kesting1d326382020-01-06 16:55:35 -08008895 case EVENT_DATA_STALL_SUSPECTED: {
8896 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang0d1be642021-01-21 15:47:41 +08008897 final Pair<Long, PersistableBundle> arg =
8898 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kesting1d326382020-01-06 16:55:35 -08008899 if (nai == null) break;
8900
Aaron Huang0d1be642021-01-21 15:47:41 +08008901 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kesting1d326382020-01-06 16:55:35 -08008902 break;
8903 }
Cody Kestinga58c07c2020-01-07 11:18:54 -08008904 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
8905 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
8906 break;
8907 }
8908 default: {
8909 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
8910 }
Cody Kesting0ffbf922019-12-18 10:57:50 -08008911 }
8912 }
8913 }
8914
8915 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
8916 @VisibleForTesting
8917 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
8918 @NonNull private final IConnectivityDiagnosticsCallback mCb;
8919 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kestingd292a332020-01-05 14:06:39 -08008920 @NonNull private final String mCallingPackageName;
Cody Kesting0ffbf922019-12-18 10:57:50 -08008921
8922 @VisibleForTesting
8923 ConnectivityDiagnosticsCallbackInfo(
Cody Kestingd292a332020-01-05 14:06:39 -08008924 @NonNull IConnectivityDiagnosticsCallback cb,
8925 @NonNull NetworkRequestInfo nri,
8926 @NonNull String callingPackageName) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08008927 mCb = cb;
8928 mRequestInfo = nri;
Cody Kestingd292a332020-01-05 14:06:39 -08008929 mCallingPackageName = callingPackageName;
Cody Kesting0ffbf922019-12-18 10:57:50 -08008930 }
8931
8932 @Override
8933 public void binderDied() {
8934 log("ConnectivityDiagnosticsCallback IBinder died.");
8935 unregisterConnectivityDiagnosticsCallback(mCb);
8936 }
8937 }
8938
Cody Kestingd292a332020-01-05 14:06:39 -08008939 /**
8940 * Class used for sending information from {@link
8941 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
8942 */
8943 private static class NetworkTestedResults {
8944 private final int mNetId;
8945 private final int mTestResult;
8946 private final long mTimestampMillis;
8947 @Nullable private final String mRedirectUrl;
8948
8949 private NetworkTestedResults(
8950 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
8951 mNetId = netId;
8952 mTestResult = testResult;
8953 mTimestampMillis = timestampMillis;
8954 mRedirectUrl = redirectUrl;
8955 }
8956 }
8957
8958 /**
8959 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
8960 * ConnectivityDiagnosticsHandler}.
8961 */
8962 private static class ConnectivityReportEvent {
8963 private final long mTimestampMillis;
8964 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang0d1be642021-01-21 15:47:41 +08008965 private final PersistableBundle mExtras;
Cody Kestingd292a332020-01-05 14:06:39 -08008966
Aaron Huang0d1be642021-01-21 15:47:41 +08008967 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
8968 PersistableBundle p) {
Cody Kestingd292a332020-01-05 14:06:39 -08008969 mTimestampMillis = timestampMillis;
8970 mNai = nai;
Aaron Huang0d1be642021-01-21 15:47:41 +08008971 mExtras = p;
Cody Kestingd292a332020-01-05 14:06:39 -08008972 }
8973 }
8974
Cody Kesting0ffbf922019-12-18 10:57:50 -08008975 private void handleRegisterConnectivityDiagnosticsCallback(
8976 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
8977 ensureRunningOnConnectivityServiceThread();
8978
8979 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting0c55a302020-03-05 10:46:02 -08008980 final IBinder iCb = cb.asBinder();
Cody Kesting0ffbf922019-12-18 10:57:50 -08008981 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
8982
James Mattis65d0d1c2020-11-24 17:40:49 -08008983 // Connectivity Diagnostics are meant to be used with a single network request. It would be
8984 // confusing for these networks to change when an NRI is satisfied in another layer.
8985 if (nri.isMultilayerRequest()) {
8986 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
8987 + "network requests.");
8988 }
8989
Cody Kesting0ffbf922019-12-18 10:57:50 -08008990 // This means that the client registered the same callback multiple times. Do
8991 // not override the previous entry, and exit silently.
Cody Kesting0c55a302020-03-05 10:46:02 -08008992 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08008993 if (VDBG) log("Diagnostics callback is already registered");
8994
8995 // Decrement the reference count for this NetworkRequestInfo. The reference count is
8996 // incremented when the NetworkRequestInfo is created as part of
8997 // enforceRequestCountLimit().
Chalard Jean70b2d9a2021-04-01 16:41:04 +09008998 nri.decrementRequestCount();
Cody Kesting0ffbf922019-12-18 10:57:50 -08008999 return;
9000 }
9001
Cody Kesting0c55a302020-03-05 10:46:02 -08009002 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009003
9004 try {
Cody Kesting0c55a302020-03-05 10:46:02 -08009005 iCb.linkToDeath(cbInfo, 0);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009006 } catch (RemoteException e) {
9007 cbInfo.binderDied();
Cody Kesting905b4752020-02-12 14:50:58 -08009008 return;
9009 }
9010
9011 // Once registered, provide ConnectivityReports for matching Networks
9012 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9013 synchronized (mNetworkForNetId) {
9014 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9015 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis65d0d1c2020-11-24 17:40:49 -08009016 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9017 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kesting905b4752020-02-12 14:50:58 -08009018 matchingNetworks.add(nai);
9019 }
9020 }
9021 }
9022 for (final NetworkAgentInfo nai : matchingNetworks) {
9023 final ConnectivityReport report = nai.getConnectivityReport();
9024 if (report == null) {
9025 continue;
9026 }
9027 if (!checkConnectivityDiagnosticsPermissions(
9028 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9029 continue;
9030 }
9031
9032 try {
9033 cb.onConnectivityReportAvailable(report);
9034 } catch (RemoteException e) {
9035 // Exception while sending the ConnectivityReport. Move on to the next network.
9036 }
Cody Kesting0ffbf922019-12-18 10:57:50 -08009037 }
9038 }
9039
9040 private void handleUnregisterConnectivityDiagnosticsCallback(
9041 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9042 ensureRunningOnConnectivityServiceThread();
Cody Kesting0c55a302020-03-05 10:46:02 -08009043 final IBinder iCb = cb.asBinder();
Cody Kesting0ffbf922019-12-18 10:57:50 -08009044
Cody Kesting970e7792020-03-30 12:43:49 -07009045 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9046 mConnectivityDiagnosticsCallbacks.remove(iCb);
9047 if (cbInfo == null) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08009048 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9049 return;
9050 }
9051
Cody Kesting970e7792020-03-30 12:43:49 -07009052 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting0ffbf922019-12-18 10:57:50 -08009053
Cody Kesting054451e2020-12-02 12:16:56 -08009054 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9055 // (if the Binder died)
9056 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9057 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting0ffbf922019-12-18 10:57:50 -08009058 return;
9059 }
9060
Cody Kestingfc14fbe2020-03-04 13:35:20 -08009061 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9062 // incremented when the NetworkRequestInfo is created as part of
9063 // enforceRequestCountLimit().
Chalard Jean70b2d9a2021-04-01 16:41:04 +09009064 nri.decrementRequestCount();
Cody Kestingfc14fbe2020-03-04 13:35:20 -08009065
Cody Kesting0c55a302020-03-05 10:46:02 -08009066 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009067 }
9068
Cody Kestingd292a332020-01-05 14:06:39 -08009069 private void handleNetworkTestedWithExtras(
9070 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9071 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting2abe6112020-02-11 10:03:26 -08009072 final NetworkCapabilities networkCapabilities =
Cody Kesting70897532020-03-05 22:13:31 -08009073 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingd292a332020-01-05 14:06:39 -08009074 final ConnectivityReport report =
9075 new ConnectivityReport(
9076 reportEvent.mNai.network,
9077 reportEvent.mTimestampMillis,
9078 nai.linkProperties,
Cody Kesting2abe6112020-02-11 10:03:26 -08009079 networkCapabilities,
Cody Kestingd292a332020-01-05 14:06:39 -08009080 extras);
Cody Kesting905b4752020-02-12 14:50:58 -08009081 nai.setConnectivityReport(report);
Cody Kestingd292a332020-01-05 14:06:39 -08009082 final List<IConnectivityDiagnosticsCallback> results =
9083 getMatchingPermissionedCallbacks(nai);
9084 for (final IConnectivityDiagnosticsCallback cb : results) {
9085 try {
Cody Kestinge4d2df52020-03-05 15:19:48 -08009086 cb.onConnectivityReportAvailable(report);
Cody Kestingd292a332020-01-05 14:06:39 -08009087 } catch (RemoteException ex) {
9088 loge("Error invoking onConnectivityReport", ex);
9089 }
9090 }
9091 }
9092
Cody Kesting1d326382020-01-06 16:55:35 -08009093 private void handleDataStallSuspected(
9094 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9095 @NonNull PersistableBundle extras) {
Cody Kesting2abe6112020-02-11 10:03:26 -08009096 final NetworkCapabilities networkCapabilities =
Cody Kesting70897532020-03-05 22:13:31 -08009097 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting1d326382020-01-06 16:55:35 -08009098 final DataStallReport report =
Cody Kesting4a773072020-02-04 21:52:09 -08009099 new DataStallReport(
9100 nai.network,
9101 timestampMillis,
9102 detectionMethod,
9103 nai.linkProperties,
Cody Kesting2abe6112020-02-11 10:03:26 -08009104 networkCapabilities,
Cody Kesting4a773072020-02-04 21:52:09 -08009105 extras);
Cody Kesting1d326382020-01-06 16:55:35 -08009106 final List<IConnectivityDiagnosticsCallback> results =
9107 getMatchingPermissionedCallbacks(nai);
9108 for (final IConnectivityDiagnosticsCallback cb : results) {
9109 try {
9110 cb.onDataStallSuspected(report);
9111 } catch (RemoteException ex) {
9112 loge("Error invoking onDataStallSuspected", ex);
9113 }
9114 }
9115 }
9116
Cody Kestinga58c07c2020-01-07 11:18:54 -08009117 private void handleNetworkConnectivityReported(
9118 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9119 final List<IConnectivityDiagnosticsCallback> results =
9120 getMatchingPermissionedCallbacks(nai);
9121 for (final IConnectivityDiagnosticsCallback cb : results) {
9122 try {
9123 cb.onNetworkConnectivityReported(nai.network, connectivity);
9124 } catch (RemoteException ex) {
9125 loge("Error invoking onNetworkConnectivityReported", ex);
9126 }
9127 }
9128 }
9129
Cody Kesting70897532020-03-05 22:13:31 -08009130 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colittib8756a82021-05-10 00:49:14 +09009131 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9132 NetworkCapabilities.REDACT_ALL);
Cody Kesting70897532020-03-05 22:13:31 -08009133 sanitized.setUids(null);
9134 sanitized.setAdministratorUids(new int[0]);
9135 sanitized.setOwnerUid(Process.INVALID_UID);
9136 return sanitized;
Cody Kesting2abe6112020-02-11 10:03:26 -08009137 }
9138
Cody Kestingd292a332020-01-05 14:06:39 -08009139 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9140 @NonNull NetworkAgentInfo nai) {
9141 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting0c55a302020-03-05 10:46:02 -08009142 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kestingd292a332020-01-05 14:06:39 -08009143 mConnectivityDiagnosticsCallbacks.entrySet()) {
9144 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9145 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
James Mattis65d0d1c2020-11-24 17:40:49 -08009146 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9147 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingd292a332020-01-05 14:06:39 -08009148 if (checkConnectivityDiagnosticsPermissions(
9149 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
Cody Kesting0c55a302020-03-05 10:46:02 -08009150 results.add(entry.getValue().mCb);
Cody Kestingd292a332020-01-05 14:06:39 -08009151 }
9152 }
9153 }
9154 return results;
9155 }
9156
9157 @VisibleForTesting
9158 boolean checkConnectivityDiagnosticsPermissions(
9159 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9160 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9161 return true;
9162 }
9163
Cody Kesting5df8e982020-02-07 14:49:34 -08009164 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9165 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9166 // call in a try-catch.
9167 try {
9168 if (!mLocationPermissionChecker.checkLocationPermission(
9169 callbackPackageName, null /* featureId */, callbackUid, null /* message */)) {
9170 return false;
9171 }
9172 } catch (SecurityException e) {
Cody Kestingd292a332020-01-05 14:06:39 -08009173 return false;
9174 }
9175
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09009176 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colitti82f9a002020-11-16 23:41:21 +09009177 if (virtual.supportsUnderlyingNetworks()
9178 && virtual.networkCapabilities.getOwnerUid() == callbackUid
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09009179 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, nai.network)) {
Lorenzo Colitti82f9a002020-11-16 23:41:21 +09009180 return true;
9181 }
Cody Kestingd292a332020-01-05 14:06:39 -08009182 }
9183
9184 // Administrator UIDs also contains the Owner UID
Cody Kestingc5cadf62020-03-16 18:15:28 -07009185 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09009186 return CollectionUtils.contains(administratorUids, callbackUid);
Cody Kestingd292a332020-01-05 14:06:39 -08009187 }
9188
Cody Kesting9c69dd42019-12-17 12:55:28 -08009189 @Override
9190 public void registerConnectivityDiagnosticsCallback(
Cody Kestingd292a332020-01-05 14:06:39 -08009191 @NonNull IConnectivityDiagnosticsCallback callback,
9192 @NonNull NetworkRequest request,
9193 @NonNull String callingPackageName) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08009194 if (request.legacyType != TYPE_NONE) {
9195 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9196 + " Please use NetworkCapabilities instead.");
9197 }
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009198 final int callingUid = mDeps.getCallingUid();
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08009199 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009200
9201 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9202 // and administrator uids to be safe.
9203 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08009204 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009205
9206 final NetworkRequest requestWithId =
9207 new NetworkRequest(
9208 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9209
9210 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9211 //
9212 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9213 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9214 // callback's binder death.
Lorenzo Colittif2514122021-03-12 22:50:57 +09009215 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009216 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kestingd292a332020-01-05 14:06:39 -08009217 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009218
9219 mConnectivityDiagnosticsHandler.sendMessage(
9220 mConnectivityDiagnosticsHandler.obtainMessage(
9221 ConnectivityDiagnosticsHandler
9222 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9223 cbInfo));
Cody Kesting9c69dd42019-12-17 12:55:28 -08009224 }
9225
9226 @Override
9227 public void unregisterConnectivityDiagnosticsCallback(
9228 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huang6a16a412021-04-09 12:06:42 +08009229 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting0ffbf922019-12-18 10:57:50 -08009230 mConnectivityDiagnosticsHandler.sendMessage(
9231 mConnectivityDiagnosticsHandler.obtainMessage(
9232 ConnectivityDiagnosticsHandler
9233 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009234 mDeps.getCallingUid(),
Cody Kesting0ffbf922019-12-18 10:57:50 -08009235 0,
9236 callback));
Cody Kesting9c69dd42019-12-17 12:55:28 -08009237 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009238
9239 @Override
9240 public void simulateDataStall(int detectionMethod, long timestampMillis,
9241 @NonNull Network network, @NonNull PersistableBundle extras) {
9242 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9243 android.Manifest.permission.NETWORK_STACK);
9244 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9245 if (!nc.hasTransport(TRANSPORT_TEST)) {
9246 throw new SecurityException("Data Stall simluation is only possible for test networks");
9247 }
9248
9249 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009250 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009251 throw new SecurityException("Data Stall simulation is only possible for network "
9252 + "creators");
9253 }
9254
Cody Kesting51691052020-05-21 12:08:21 -07009255 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9256 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9257 // Data Stall information as a DataStallReportParcelable and passing to
9258 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9259 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kesting43a47ef2020-05-15 10:36:01 -07009260 final DataStallReportParcelable p = new DataStallReportParcelable();
9261 p.timestampMillis = timestampMillis;
9262 p.detectionMethod = detectionMethod;
9263
9264 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9265 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9266 }
9267 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9268 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9269 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9270 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9271 }
9272
Serik Beketayev284cb872020-12-07 22:43:07 -08009273 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009274 }
lucaslin6d502ed2021-01-21 02:02:55 +08009275
lucaslindb201da2021-02-23 01:12:55 +08009276 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9277 @Override
lucasline17f3472021-02-25 15:10:29 +08009278 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslindb201da2021-02-23 01:12:55 +08009279 long timestampNs, int uid) {
lucasline17f3472021-02-25 15:10:29 +08009280 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslindb201da2021-02-23 01:12:55 +08009281 }
lucaslin357f5862021-01-21 19:48:09 +08009282
9283 @Override
9284 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucasline17f3472021-02-25 15:10:29 +08009285 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin357f5862021-01-21 19:48:09 +08009286 nai.clatd.interfaceLinkStateChanged(iface, up);
9287 }
9288 }
9289
9290 @Override
9291 public void onInterfaceRemoved(String iface) {
lucasline17f3472021-02-25 15:10:29 +08009292 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin357f5862021-01-21 19:48:09 +08009293 nai.clatd.interfaceRemoved(iface);
9294 }
lucaslindb201da2021-02-23 01:12:55 +08009295 }
9296 }
9297
lucaslin6d502ed2021-01-21 02:02:55 +08009298 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9299
9300 /**
9301 * Class used for updating network activity tracking with netd and notify network activity
9302 * changes.
9303 */
9304 private static final class LegacyNetworkActivityTracker {
lucaslin32028e02021-01-21 02:03:17 +08009305 private static final int NO_UID = -1;
lucaslin6d502ed2021-01-21 02:02:55 +08009306 private final Context mContext;
lucaslina5e9bdb2021-01-21 02:04:15 +08009307 private final INetd mNetd;
lucaslina5e9bdb2021-01-21 02:04:15 +08009308 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9309 new RemoteCallbackList<>();
9310 // Indicate the current system default network activity is active or not.
9311 @GuardedBy("mActiveIdleTimers")
9312 private boolean mNetworkActive;
9313 @GuardedBy("mActiveIdleTimers")
9314 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9315 private final Handler mHandler;
lucaslin6d502ed2021-01-21 02:02:55 +08009316
lucaslina5e9bdb2021-01-21 02:04:15 +08009317 private class IdleTimerParams {
9318 public final int timeout;
9319 public final int transportType;
9320
9321 IdleTimerParams(int timeout, int transport) {
9322 this.timeout = timeout;
9323 this.transportType = transport;
9324 }
9325 }
9326
9327 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslinea5378c2021-02-20 18:59:47 +08009328 @NonNull INetd netd) {
lucaslin6d502ed2021-01-21 02:02:55 +08009329 mContext = context;
lucaslina5e9bdb2021-01-21 02:04:15 +08009330 mNetd = netd;
9331 mHandler = handler;
lucaslin6d502ed2021-01-21 02:02:55 +08009332 }
9333
lucaslindb201da2021-02-23 01:12:55 +08009334 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9335 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9336 synchronized (mActiveIdleTimers) {
9337 mNetworkActive = active;
9338 // If there are no idle timers, it means that system is not monitoring
9339 // activity, so the system default network for those default network
9340 // unspecified apps is always considered active.
9341 //
9342 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9343 // any network activity change event. Whenever this event is received,
9344 // the mActiveIdleTimers should be always not empty. The legacy behavior
9345 // is no-op. Remove to refer to mNetworkActive only.
9346 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9347 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9348 }
9349 }
9350 }
lucaslin6d502ed2021-01-21 02:02:55 +08009351
lucaslina5e9bdb2021-01-21 02:04:15 +08009352 // The network activity should only be updated from ConnectivityService handler thread
9353 // when mActiveIdleTimers lock is held.
9354 @GuardedBy("mActiveIdleTimers")
9355 private void reportNetworkActive() {
9356 final int length = mNetworkActivityListeners.beginBroadcast();
9357 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9358 try {
9359 for (int i = 0; i < length; i++) {
9360 try {
9361 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9362 } catch (RemoteException | RuntimeException e) {
9363 loge("Fail to send network activie to listener " + e);
9364 }
9365 }
9366 } finally {
9367 mNetworkActivityListeners.finishBroadcast();
9368 }
9369 }
9370
9371 @GuardedBy("mActiveIdleTimers")
9372 public void handleReportNetworkActivity() {
9373 synchronized (mActiveIdleTimers) {
9374 reportNetworkActive();
9375 }
9376 }
9377
lucaslin6d502ed2021-01-21 02:02:55 +08009378 // This is deprecated and only to support legacy use cases.
9379 private int transportTypeToLegacyType(int type) {
9380 switch (type) {
9381 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009382 return TYPE_MOBILE;
lucaslin6d502ed2021-01-21 02:02:55 +08009383 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009384 return TYPE_WIFI;
lucaslin6d502ed2021-01-21 02:02:55 +08009385 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009386 return TYPE_BLUETOOTH;
lucaslin6d502ed2021-01-21 02:02:55 +08009387 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009388 return TYPE_ETHERNET;
lucaslin6d502ed2021-01-21 02:02:55 +08009389 default:
9390 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9391 }
9392 return ConnectivityManager.TYPE_NONE;
9393 }
9394
9395 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9396 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9397 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9398 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9399 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9400 final long ident = Binder.clearCallingIdentity();
9401 try {
9402 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9403 RECEIVE_DATA_ACTIVITY_CHANGE,
9404 null /* resultReceiver */,
9405 null /* scheduler */,
9406 0 /* initialCode */,
9407 null /* initialData */,
9408 null /* initialExtra */);
9409 } finally {
9410 Binder.restoreCallingIdentity(ident);
9411 }
9412 }
9413
9414 /**
9415 * Setup data activity tracking for the given network.
9416 *
9417 * Every {@code setupDataActivityTracking} should be paired with a
9418 * {@link #removeDataActivityTracking} for cleanup.
9419 */
9420 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9421 final String iface = networkAgent.linkProperties.getInterfaceName();
9422
9423 final int timeout;
9424 final int type;
9425
9426 if (networkAgent.networkCapabilities.hasTransport(
9427 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9428 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08009429 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin6d502ed2021-01-21 02:02:55 +08009430 10);
9431 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9432 } else if (networkAgent.networkCapabilities.hasTransport(
9433 NetworkCapabilities.TRANSPORT_WIFI)) {
9434 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08009435 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin6d502ed2021-01-21 02:02:55 +08009436 15);
9437 type = NetworkCapabilities.TRANSPORT_WIFI;
9438 } else {
9439 return; // do not track any other networks
9440 }
9441
lucaslin32028e02021-01-21 02:03:17 +08009442 updateRadioPowerState(true /* isActive */, type);
9443
lucaslin6d502ed2021-01-21 02:02:55 +08009444 if (timeout > 0 && iface != null) {
9445 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08009446 synchronized (mActiveIdleTimers) {
9447 // Networks start up.
9448 mNetworkActive = true;
9449 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9450 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9451 reportNetworkActive();
9452 }
lucaslin6d502ed2021-01-21 02:02:55 +08009453 } catch (Exception e) {
9454 // You shall not crash!
9455 loge("Exception in setupDataActivityTracking " + e);
9456 }
9457 }
9458 }
9459
9460 /**
9461 * Remove data activity tracking when network disconnects.
9462 */
9463 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9464 final String iface = networkAgent.linkProperties.getInterfaceName();
9465 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9466
lucaslin32028e02021-01-21 02:03:17 +08009467 if (iface == null) return;
9468
9469 final int type;
9470 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9471 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9472 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9473 type = NetworkCapabilities.TRANSPORT_WIFI;
9474 } else {
9475 return; // do not track any other networks
9476 }
9477
9478 try {
9479 updateRadioPowerState(false /* isActive */, type);
lucaslina5e9bdb2021-01-21 02:04:15 +08009480 synchronized (mActiveIdleTimers) {
9481 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9482 // The call fails silently if no idle timer setup for this interface
9483 mNetd.idletimerRemoveInterface(iface, params.timeout,
9484 Integer.toString(params.transportType));
lucaslin6d502ed2021-01-21 02:02:55 +08009485 }
lucaslin32028e02021-01-21 02:03:17 +08009486 } catch (Exception e) {
9487 // You shall not crash!
9488 loge("Exception in removeDataActivityTracking " + e);
lucaslin6d502ed2021-01-21 02:02:55 +08009489 }
9490 }
9491
9492 /**
9493 * Update data activity tracking when network state is updated.
9494 */
9495 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9496 NetworkAgentInfo oldNetwork) {
9497 if (newNetwork != null) {
9498 setupDataActivityTracking(newNetwork);
9499 }
9500 if (oldNetwork != null) {
9501 removeDataActivityTracking(oldNetwork);
9502 }
9503 }
lucaslin32028e02021-01-21 02:03:17 +08009504
9505 private void updateRadioPowerState(boolean isActive, int transportType) {
9506 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9507 switch (transportType) {
9508 case NetworkCapabilities.TRANSPORT_CELLULAR:
9509 bs.reportMobileRadioPowerState(isActive, NO_UID);
9510 break;
9511 case NetworkCapabilities.TRANSPORT_WIFI:
9512 bs.reportWifiRadioPowerState(isActive, NO_UID);
9513 break;
9514 default:
9515 logw("Untracked transport type:" + transportType);
9516 }
9517 }
lucaslina5e9bdb2021-01-21 02:04:15 +08009518
9519 public boolean isDefaultNetworkActive() {
9520 synchronized (mActiveIdleTimers) {
9521 // If there are no idle timers, it means that system is not monitoring activity,
9522 // so the default network is always considered active.
9523 //
9524 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9525 // tracking is disabled (negative idle timer value configured), or no active default
9526 // network. In the latter case, this reports active but it should report inactive.
9527 return mNetworkActive || mActiveIdleTimers.isEmpty();
9528 }
9529 }
9530
9531 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9532 mNetworkActivityListeners.register(l);
9533 }
9534
9535 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9536 mNetworkActivityListeners.unregister(l);
9537 }
lucaslin3756fcc2021-01-21 02:04:35 +08009538
9539 public void dump(IndentingPrintWriter pw) {
9540 synchronized (mActiveIdleTimers) {
9541 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9542 pw.println("Idle timers:");
9543 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9544 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9545 final IdleTimerParams params = ent.getValue();
9546 pw.print(" timeout="); pw.print(params.timeout);
9547 pw.print(" type="); pw.println(params.transportType);
9548 }
9549 }
9550 }
lucaslin6d502ed2021-01-21 02:02:55 +08009551 }
James Mattised87a672021-01-01 14:13:35 -08009552
Daniel Bright60f02ed2020-06-15 16:10:01 -07009553 /**
9554 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9555 *
9556 * @param socketInfo the socket information
9557 * @param callback the callback to register
9558 */
9559 @Override
9560 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9561 @NonNull final IQosCallback callback) {
9562 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9563 if (nai == null || nai.networkCapabilities == null) {
9564 try {
9565 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9566 } catch (final RemoteException ex) {
9567 loge("registerQosCallbackInternal: RemoteException", ex);
9568 }
9569 return;
9570 }
9571 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9572 }
9573
9574 /**
9575 * Register a {@link IQosCallback} with base {@link QosFilter}.
9576 *
9577 * @param filter the filter to register
9578 * @param callback the callback to register
9579 * @param nai the agent information related to the filter's network
9580 */
9581 @VisibleForTesting
9582 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9583 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9584 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9585 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9586
9587 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9588 enforceConnectivityRestrictedNetworksPermission();
9589 }
9590 mQosCallbackTracker.registerCallback(callback, filter, nai);
9591 }
9592
9593 /**
9594 * Unregisters the given callback.
9595 *
9596 * @param callback the callback to unregister
9597 */
9598 @Override
9599 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huang6a16a412021-04-09 12:06:42 +08009600 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07009601 mQosCallbackTracker.unregisterCallback(callback);
9602 }
James Mattised87a672021-01-01 14:13:35 -08009603
Chalard Jean9d968182021-02-25 21:46:34 +09009604 // Network preference per-profile and OEM network preferences can't be set at the same
9605 // time, because it is unclear what should happen if both preferences are active for
9606 // one given UID. To make it possible, the stack would have to clarify what would happen
9607 // in case both are active at the same time. The implementation may have to be adjusted
9608 // to implement the resulting rules. For example, a priority could be defined between them,
9609 // where the OEM preference would be considered less or more important than the enterprise
9610 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9611 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9612 // are set at the right level. Other solutions are possible, e.g. merging of the
9613 // preferences for the relevant UIDs.
9614 private static void throwConcurrentPreferenceException() {
9615 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9616 + "set OemNetworkPreference at the same time");
James Mattis6e6fabf2021-01-10 14:24:24 -08009617 }
9618
9619 /**
Chalard Jean03433052021-02-25 17:23:40 +09009620 * Request that a user profile is put by default on a network matching a given preference.
9621 *
9622 * See the documentation for the individual preferences for a description of the supported
9623 * behaviors.
9624 *
9625 * @param profile the profile concerned.
9626 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9627 * constants.
9628 * @param listener an optional listener to listen for completion of the operation.
9629 */
9630 @Override
9631 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9632 @ConnectivityManager.ProfileNetworkPreference final int preference,
9633 @Nullable final IOnCompleteListener listener) {
Chalard Jean9d968182021-02-25 21:46:34 +09009634 Objects.requireNonNull(profile);
9635 PermissionUtils.enforceNetworkStackPermission(mContext);
9636 if (DBG) {
9637 log("setProfileNetworkPreference " + profile + " to " + preference);
9638 }
9639 if (profile.getIdentifier() < 0) {
9640 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9641 + "UserHandle.CURRENT not supported)");
9642 }
Chalard Jean0a04bdb2021-04-02 19:24:44 +09009643 final UserManager um = mContext.getSystemService(UserManager.class);
9644 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jean9d968182021-02-25 21:46:34 +09009645 throw new IllegalArgumentException("Profile must be a managed profile");
9646 }
9647 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9648 // handler thread. However it is an immutable object, so reading the reference is
9649 // safe - it's just possible the value is slightly outdated. For the final check,
9650 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9651 // lot easier to understand, so opportunistically check it.
9652 if (!mOemNetworkPreferences.isEmpty()) {
9653 throwConcurrentPreferenceException();
9654 }
9655 final NetworkCapabilities nc;
9656 switch (preference) {
9657 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9658 nc = null;
9659 break;
9660 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9661 final UidRange uids = UidRange.createForUser(profile);
9662 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9663 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9664 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9665 break;
9666 default:
9667 throw new IllegalArgumentException(
9668 "Invalid preference in setProfileNetworkPreference");
9669 }
9670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9671 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9672 }
9673
9674 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9675 @Nullable final NetworkCapabilities nc) {
9676 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9677 ensureRequestableCapabilities(nc);
9678 }
9679
9680 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9681 @NonNull final ProfileNetworkPreferences prefs) {
9682 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9683 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9684 // The NRI for a user should be comprised of two layers:
9685 // - The request for the capabilities
9686 // - The request for the default network, for fallback. Create an image of it to
9687 // have the correct UIDs in it (also a request can only be part of one NRI, because
9688 // of lookups in 1:1 associations like mNetworkRequests).
9689 // Note that denying a fallback can be implemented simply by not adding the second
9690 // request.
9691 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9692 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
James Mattis6402e582021-04-20 17:26:30 -07009693 nrs.add(createDefaultInternetRequestForTransport(
9694 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Chiachang Wangd5034c72021-02-22 18:36:38 +08009695 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
Lorenzo Colittif2514122021-03-12 22:50:57 +09009696 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
Chalard Jean9d968182021-02-25 21:46:34 +09009697 result.add(nri);
9698 }
9699 return result;
9700 }
9701
9702 private void handleSetProfileNetworkPreference(
9703 @NonNull final ProfileNetworkPreferences.Preference preference,
9704 @Nullable final IOnCompleteListener listener) {
9705 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9706 // particular because it's not clear what preference should win in case both apply
9707 // to the same app.
9708 // The binder call has already checked this, but as mOemNetworkPreferences is only
9709 // touched on the handler thread, it's theoretically not impossible that it has changed
9710 // since.
9711 if (!mOemNetworkPreferences.isEmpty()) {
Chalard Jean6bb468c2021-03-09 21:09:20 +09009712 // This may happen on a device with an OEM preference set when a user is removed.
9713 // In this case, it's safe to ignore. In particular this happens in the tests.
9714 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
Chalard Jean9d968182021-02-25 21:46:34 +09009715 return;
9716 }
9717
9718 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9719
9720 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
James Mattisfff0b7c2021-03-28 17:41:09 -07009721 mSystemNetworkRequestCounter.transact(
9722 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9723 () -> {
9724 final ArraySet<NetworkRequestInfo> nris =
9725 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9726 replaceDefaultNetworkRequestsForPreference(nris);
9727 });
Chalard Jean9d968182021-02-25 21:46:34 +09009728 // Finally, rematch.
9729 rematchAllNetworksAndRequests();
9730
9731 if (null != listener) {
9732 try {
9733 listener.onComplete();
9734 } catch (RemoteException e) {
9735 loge("Listener for setProfileNetworkPreference has died");
9736 }
9737 }
9738 }
9739
James Mattis6e6fabf2021-01-10 14:24:24 -08009740 private void enforceAutomotiveDevice() {
9741 final boolean isAutomotiveDevice =
9742 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9743 if (!isAutomotiveDevice) {
9744 throw new UnsupportedOperationException(
9745 "setOemNetworkPreference() is only available on automotive devices.");
9746 }
9747 }
9748
9749 /**
9750 * Used by automotive devices to set the network preferences used to direct traffic at an
9751 * application level as per the given OemNetworkPreferences. An example use-case would be an
9752 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9753 * vehicle via a particular network.
9754 *
9755 * Calling this will overwrite the existing preference.
9756 *
James Mattis7a253542021-01-26 16:23:52 -08009757 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jeancc9ad152021-03-03 16:37:13 +09009758 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis6e6fabf2021-01-10 14:24:24 -08009759 * to communicate completion of setOemNetworkPreference();
James Mattis6e6fabf2021-01-10 14:24:24 -08009760 */
James Mattised87a672021-01-01 14:13:35 -08009761 @Override
James Mattis6e6fabf2021-01-10 14:24:24 -08009762 public void setOemNetworkPreference(
9763 @NonNull final OemNetworkPreferences preference,
Chalard Jeancc9ad152021-03-03 16:37:13 +09009764 @Nullable final IOnCompleteListener listener) {
James Mattis981865c2021-01-26 14:05:36 -08009765
James Mattis6e6fabf2021-01-10 14:24:24 -08009766 enforceAutomotiveDevice();
James Mattis7a253542021-01-26 16:23:52 -08009767 enforceOemNetworkPreferencesPermission();
James Mattis6e6fabf2021-01-10 14:24:24 -08009768
Chalard Jean9d968182021-02-25 21:46:34 +09009769 if (!mProfileNetworkPreferences.isEmpty()) {
9770 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9771 // handler thread. However it is an immutable object, so reading the reference is
9772 // safe - it's just possible the value is slightly outdated. For the final check,
9773 // see #handleSetOemPreference. But if this can be caught here it is a
9774 // lot easier to understand, so opportunistically check it.
9775 throwConcurrentPreferenceException();
9776 }
9777
James Mattis6e6fabf2021-01-10 14:24:24 -08009778 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9779 validateOemNetworkPreferences(preference);
9780 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9781 new Pair<>(preference, listener)));
9782 }
9783
9784 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9785 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9786 : preference.getNetworkPreferences().values()) {
9787 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9788 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9789 throw new IllegalArgumentException(msg);
9790 }
9791 }
9792 }
9793
9794 private void handleSetOemNetworkPreference(
9795 @NonNull final OemNetworkPreferences preference,
Chalard Jeancc9ad152021-03-03 16:37:13 +09009796 @Nullable final IOnCompleteListener listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08009797 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9798 if (DBG) {
9799 log("set OEM network preferences :" + preference.toString());
9800 }
Chalard Jean9d968182021-02-25 21:46:34 +09009801 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9802 // particular because it's not clear what preference should win in case both apply
9803 // to the same app.
9804 // The binder call has already checked this, but as mOemNetworkPreferences is only
9805 // touched on the handler thread, it's theoretically not impossible that it has changed
9806 // since.
9807 if (!mProfileNetworkPreferences.isEmpty()) {
9808 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9809 return;
9810 }
9811
James Mattis6e4405f2021-04-06 17:07:42 -07009812 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
James Mattisfff0b7c2021-03-28 17:41:09 -07009813 final int uniquePreferenceCount = new ArraySet<>(
9814 preference.getNetworkPreferences().values()).size();
9815 mSystemNetworkRequestCounter.transact(
9816 mDeps.getCallingUid(), uniquePreferenceCount,
9817 () -> {
9818 final ArraySet<NetworkRequestInfo> nris =
9819 new OemNetworkRequestFactory()
9820 .createNrisFromOemNetworkPreferences(preference);
9821 replaceDefaultNetworkRequestsForPreference(nris);
9822 });
James Mattis6e6fabf2021-01-10 14:24:24 -08009823 mOemNetworkPreferences = preference;
James Mattis6e6fabf2021-01-10 14:24:24 -08009824
9825 if (null != listener) {
Chalard Jeandc974072021-03-01 22:00:20 +09009826 try {
9827 listener.onComplete();
9828 } catch (RemoteException e) {
James Mattis3bf8b7a2021-03-01 17:09:11 -08009829 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jeandc974072021-03-01 22:00:20 +09009830 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009831 }
9832 }
9833
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009834 private void replaceDefaultNetworkRequestsForPreference(
James Mattise494cbb2021-02-09 18:18:28 -08009835 @NonNull final Set<NetworkRequestInfo> nris) {
James Mattis15c1b212021-02-20 14:40:51 -08009836 // Pass in a defensive copy as this collection will be updated on remove.
9837 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
James Mattise494cbb2021-02-09 18:18:28 -08009838 addPerAppDefaultNetworkRequests(nris);
James Mattis6e6fabf2021-01-10 14:24:24 -08009839 }
9840
James Mattise494cbb2021-02-09 18:18:28 -08009841 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9842 ensureRunningOnConnectivityServiceThread();
9843 mDefaultNetworkRequests.addAll(nris);
9844 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9845 getPerAppCallbackRequestsToUpdate();
James Mattise494cbb2021-02-09 18:18:28 -08009846 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
James Mattisfff0b7c2021-03-28 17:41:09 -07009847 mSystemNetworkRequestCounter.transact(
9848 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9849 () -> {
9850 nrisToRegister.addAll(
9851 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9852 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9853 handleRegisterNetworkRequests(nrisToRegister);
9854 });
James Mattise494cbb2021-02-09 18:18:28 -08009855 }
9856
9857 /**
9858 * All current requests that are tracking the default network need to be assessed as to whether
9859 * or not the current set of per-application default requests will be changing their default
9860 * network. If so, those requests will need to be updated so that they will send callbacks for
9861 * default network changes at the appropriate time. Additionally, those requests tracking the
9862 * default that were previously updated by this flow will need to be reassessed.
9863 * @return the nris which will need to be updated.
9864 */
9865 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9866 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9867 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9868 // same nri in the map's values for each of its NetworkRequest objects.
9869 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis6e6fabf2021-01-10 14:24:24 -08009870 for (final NetworkRequestInfo nri : nris) {
James Mattise494cbb2021-02-09 18:18:28 -08009871 // Include this nri if it is currently being tracked.
9872 if (isPerAppTrackedNri(nri)) {
9873 defaultCallbackRequests.add(nri);
9874 continue;
9875 }
9876 // We only track callbacks for requests tracking the default.
9877 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9878 continue;
9879 }
9880 // Include this nri if it will be tracked by the new per-app default requests.
9881 final boolean isNriGoingToBeTracked =
Lorenzo Colittif2514122021-03-12 22:50:57 +09009882 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattise494cbb2021-02-09 18:18:28 -08009883 if (isNriGoingToBeTracked) {
9884 defaultCallbackRequests.add(nri);
James Mattis6e6fabf2021-01-10 14:24:24 -08009885 }
9886 }
James Mattise494cbb2021-02-09 18:18:28 -08009887 return defaultCallbackRequests;
James Mattis6e6fabf2021-01-10 14:24:24 -08009888 }
9889
James Mattise494cbb2021-02-09 18:18:28 -08009890 /**
9891 * Create nris for those network requests that are currently tracking the default network that
9892 * are being controlled by a per-application default.
9893 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
9894 * foundation when creating the nri. Important items include the calling uid's original
9895 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
9896 * requests are assumed to have already been validated as needing to be updated.
9897 * @return the Set of nris to use when registering network requests.
9898 */
9899 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
9900 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
9901 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
9902 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
9903 final NetworkRequestInfo trackingNri =
Lorenzo Colittif2514122021-03-12 22:50:57 +09009904 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattise494cbb2021-02-09 18:18:28 -08009905
9906 // If this nri is not being tracked, the change it back to an untracked nri.
9907 if (trackingNri == mDefaultRequest) {
9908 callbackRequestsToRegister.add(new NetworkRequestInfo(
9909 callbackRequest,
9910 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
9911 continue;
9912 }
9913
Lorenzo Colittif2514122021-03-12 22:50:57 +09009914 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattise494cbb2021-02-09 18:18:28 -08009915 callbackRequestsToRegister.add(new NetworkRequestInfo(
9916 callbackRequest,
9917 copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09009918 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colittib199b962021-03-12 22:48:07 +09009919 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattise494cbb2021-02-09 18:18:28 -08009920 }
9921 return callbackRequestsToRegister;
James Mattis6e6fabf2021-01-10 14:24:24 -08009922 }
9923
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009924 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
9925 @NonNull final Set<UidRange> uids) {
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009926 for (final NetworkRequest req : requests) {
Chiachang Wangd5034c72021-02-22 18:36:38 +08009927 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009928 }
9929 }
9930
James Mattis6e6fabf2021-01-10 14:24:24 -08009931 /**
9932 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
9933 */
9934 @VisibleForTesting
9935 final class OemNetworkRequestFactory {
James Mattise494cbb2021-02-09 18:18:28 -08009936 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis6e6fabf2021-01-10 14:24:24 -08009937 @NonNull final OemNetworkPreferences preference) {
James Mattise494cbb2021-02-09 18:18:28 -08009938 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis6e6fabf2021-01-10 14:24:24 -08009939 final SparseArray<Set<Integer>> uids =
9940 createUidsFromOemNetworkPreferences(preference);
9941 for (int i = 0; i < uids.size(); i++) {
9942 final int key = uids.keyAt(i);
9943 final Set<Integer> value = uids.valueAt(i);
9944 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
9945 // No need to add an nri without any requests.
9946 if (0 == nri.mRequests.size()) {
9947 continue;
9948 }
9949 nris.add(nri);
9950 }
9951
9952 return nris;
9953 }
9954
9955 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
9956 @NonNull final OemNetworkPreferences preference) {
9957 final SparseArray<Set<Integer>> uids = new SparseArray<>();
9958 final PackageManager pm = mContext.getPackageManager();
James Mattis3bf8b7a2021-03-01 17:09:11 -08009959 final List<UserHandle> users =
9960 mContext.getSystemService(UserManager.class).getUserHandles(true);
9961 if (null == users || users.size() == 0) {
9962 if (VDBG || DDBG) {
9963 log("No users currently available for setting the OEM network preference.");
9964 }
9965 return uids;
9966 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009967 for (final Map.Entry<String, Integer> entry :
9968 preference.getNetworkPreferences().entrySet()) {
9969 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
9970 try {
9971 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
9972 if (!uids.contains(pref)) {
9973 uids.put(pref, new ArraySet<>());
9974 }
James Mattis3bf8b7a2021-03-01 17:09:11 -08009975 for (final UserHandle ui : users) {
9976 // Add the rules for all users as this policy is device wide.
Chiachang Wang97565cf2021-04-08 11:10:51 +08009977 uids.get(pref).add(ui.getUid(uid));
James Mattis3bf8b7a2021-03-01 17:09:11 -08009978 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009979 } catch (PackageManager.NameNotFoundException e) {
9980 // Although this may seem like an error scenario, it is ok that uninstalled
9981 // packages are sent on a network preference as the system will watch for
9982 // package installations associated with this network preference and update
9983 // accordingly. This is done so as to minimize race conditions on app install.
James Mattis6e6fabf2021-01-10 14:24:24 -08009984 continue;
9985 }
9986 }
9987 return uids;
9988 }
9989
9990 private NetworkRequestInfo createNriFromOemNetworkPreferences(
9991 @OemNetworkPreferences.OemNetworkPreference final int preference,
9992 @NonNull final Set<Integer> uids) {
9993 final List<NetworkRequest> requests = new ArrayList<>();
9994 // Requests will ultimately be evaluated by order of insertion therefore it matters.
9995 switch (preference) {
9996 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
9997 requests.add(createUnmeteredNetworkRequest());
9998 requests.add(createOemPaidNetworkRequest());
James Mattis6402e582021-04-20 17:26:30 -07009999 requests.add(createDefaultInternetRequestForTransport(
10000 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis6e6fabf2021-01-10 14:24:24 -080010001 break;
10002 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10003 requests.add(createUnmeteredNetworkRequest());
10004 requests.add(createOemPaidNetworkRequest());
10005 break;
10006 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10007 requests.add(createOemPaidNetworkRequest());
10008 break;
10009 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10010 requests.add(createOemPrivateNetworkRequest());
10011 break;
10012 default:
10013 // This should never happen.
10014 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10015 + " called with invalid preference of " + preference);
10016 }
10017
Chalard Jean9a3a0ea2021-03-01 14:06:28 +090010018 final ArraySet ranges = new ArraySet<Integer>();
10019 for (final int uid : uids) {
10020 ranges.add(new UidRange(uid, uid));
10021 }
10022 setNetworkRequestUids(requests, ranges);
Lorenzo Colittif2514122021-03-12 22:50:57 +090010023 return new NetworkRequestInfo(Process.myUid(), requests);
James Mattis6e6fabf2021-01-10 14:24:24 -080010024 }
10025
10026 private NetworkRequest createUnmeteredNetworkRequest() {
10027 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10028 .addCapability(NET_CAPABILITY_NOT_METERED)
10029 .addCapability(NET_CAPABILITY_VALIDATED);
10030 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10031 }
10032
10033 private NetworkRequest createOemPaidNetworkRequest() {
10034 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10035 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10036 .addCapability(NET_CAPABILITY_OEM_PAID)
10037 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10038 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10039 }
10040
10041 private NetworkRequest createOemPrivateNetworkRequest() {
10042 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10043 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10044 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10045 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10046 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10047 }
10048
10049 private NetworkCapabilities createDefaultPerAppNetCap() {
10050 final NetworkCapabilities netCap = new NetworkCapabilities();
10051 netCap.addCapability(NET_CAPABILITY_INTERNET);
10052 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10053 return netCap;
10054 }
James Mattised87a672021-01-01 14:13:35 -080010055 }
Nathan Harold6179b142018-07-30 13:38:01 -070010056}