blob: 061b5bd5f6bd8b86bc09d823a06108726360835b [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
Chiachang Wangdc8fdde2021-05-17 16:57:15 +08001048 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1049 // legacy output for dumpsys connectivity.
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001050 // TODO: Integrate into signal dump.
1051 dumpNormal(fd, pw, args);
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001052 }
Vishnu Nair9154a422017-10-26 10:08:50 -07001053 }
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08001054 }
Vishnu Nair9154a422017-10-26 10:08:50 -07001055
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001056 /**
Daniel Bright60f02ed2020-06-15 16:10:01 -07001057 * Keeps track of the number of requests made under different uids.
1058 */
1059 public static class PerUidCounter {
1060 private final int mMaxCountPerUid;
1061
1062 // Map from UID to number of NetworkRequests that UID has filed.
James Mattisfff0b7c2021-03-28 17:41:09 -07001063 @VisibleForTesting
Daniel Bright60f02ed2020-06-15 16:10:01 -07001064 @GuardedBy("mUidToNetworkRequestCount")
James Mattisfff0b7c2021-03-28 17:41:09 -07001065 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Bright60f02ed2020-06-15 16:10:01 -07001066
1067 /**
1068 * Constructor
1069 *
1070 * @param maxCountPerUid the maximum count per uid allowed
1071 */
1072 public PerUidCounter(final int maxCountPerUid) {
1073 mMaxCountPerUid = maxCountPerUid;
1074 }
1075
1076 /**
1077 * Increments the request count of the given uid. Throws an exception if the number
1078 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1079 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1080 *
1081 * @throws ServiceSpecificException with
1082 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1083 * the uid exceed the allowed number.
1084 *
1085 * @param uid the uid that the request was made under
1086 */
1087 public void incrementCountOrThrow(final int uid) {
1088 synchronized (mUidToNetworkRequestCount) {
James Mattisfff0b7c2021-03-28 17:41:09 -07001089 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001090 }
1091 }
1092
James Mattisfff0b7c2021-03-28 17:41:09 -07001093 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1094 final int newRequestCount =
1095 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1096 if (newRequestCount >= mMaxCountPerUid) {
1097 throw new ServiceSpecificException(
1098 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1099 }
1100 mUidToNetworkRequestCount.put(uid, newRequestCount);
1101 }
1102
Daniel Bright60f02ed2020-06-15 16:10:01 -07001103 /**
1104 * Decrements the request count of the given uid.
1105 *
1106 * @param uid the uid that the request was made under
1107 */
1108 public void decrementCount(final int uid) {
1109 synchronized (mUidToNetworkRequestCount) {
James Mattisfff0b7c2021-03-28 17:41:09 -07001110 decrementCount(uid, 1 /* numToDecrement */);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001111 }
1112 }
James Mattisfff0b7c2021-03-28 17:41:09 -07001113
1114 private void decrementCount(final int uid, final int numToDecrement) {
1115 final int newRequestCount =
1116 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1117 if (newRequestCount < 0) {
1118 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1119 } else if (newRequestCount == 0) {
1120 mUidToNetworkRequestCount.delete(uid);
1121 } else {
1122 mUidToNetworkRequestCount.put(uid, newRequestCount);
1123 }
1124 }
1125
1126 /**
1127 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1128 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1129 * are used to create the new nris upon set. Therefore the request count limit can be
1130 * artificially hit. This method is used as a workaround for this particular case so that
1131 * the request counts are accounted for correctly.
1132 * @param uid the uid to adjust counts for
1133 * @param numOfNewRequests the new request count to account for
1134 * @param r the runnable to execute
1135 */
1136 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1137 // This should only be used on the handler thread as per all current and foreseen
1138 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1139 // no ref to the outer ConnectivityService.
1140 synchronized (mUidToNetworkRequestCount) {
1141 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1142 decrementCount(uid, reqCountOverage);
1143 r.run();
1144 incrementCountOrThrow(uid, reqCountOverage);
1145 }
1146 }
1147
1148 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1149 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1150 + numOfNewRequests;
1151 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1152 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1153 }
Daniel Bright60f02ed2020-06-15 16:10:01 -07001154 }
1155
1156 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001157 * Dependencies of ConnectivityService, for injection in tests.
1158 */
1159 @VisibleForTesting
1160 public static class Dependencies {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001161 public int getCallingUid() {
1162 return Binder.getCallingUid();
1163 }
1164
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001165 /**
1166 * Get system properties to use in ConnectivityService.
1167 */
1168 public MockableSystemProperties getSystemProperties() {
1169 return new MockableSystemProperties();
1170 }
1171
1172 /**
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09001173 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1174 */
1175 public ConnectivityResources getResources(@NonNull Context ctx) {
1176 return new ConnectivityResources(ctx);
1177 }
1178
1179 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001180 * Create a HandlerThread to use in ConnectivityService.
1181 */
1182 public HandlerThread makeHandlerThread() {
1183 return new HandlerThread("ConnectivityServiceThread");
1184 }
1185
1186 /**
Remi NGUYEN VANe58b2002021-03-06 00:26:43 +09001187 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001188 */
Remi NGUYEN VANe58b2002021-03-06 00:26:43 +09001189 public NetworkStackClientBase getNetworkStack() {
1190 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001191 }
1192
1193 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001194 * @see ProxyTracker
1195 */
1196 public ProxyTracker makeProxyTracker(@NonNull Context context,
1197 @NonNull Handler connServiceHandler) {
1198 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1199 }
1200
1201 /**
1202 * @see NetIdManager
1203 */
1204 public NetIdManager makeNetIdManager() {
1205 return new NetIdManager();
1206 }
1207
1208 /**
1209 * @see NetworkUtils#queryUserAccess(int, int)
1210 */
Lorenzo Colittid81932b2021-03-23 21:01:07 +09001211 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1212 return cs.queryUserAccess(uid, network);
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001213 }
1214
1215 /**
Lorenzo Colittidbcd5d62021-02-04 01:47:38 +09001216 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1217 * requires CAP_NET_ADMIN, which the unit tests do not have.
1218 */
1219 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1220 InetSocketAddress remote) {
1221 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1222 }
1223
1224 /**
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001225 * @see MultinetworkPolicyTracker
1226 */
1227 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1228 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1229 return new MultinetworkPolicyTracker(c, h, r);
1230 }
1231
Aaron Huange044c462020-10-27 03:36:19 +08001232 /**
1233 * @see BatteryStatsManager
1234 */
1235 public void reportNetworkInterfaceForTransports(Context context, String iface,
1236 int[] transportTypes) {
Lorenzo Colitti4c9e2022021-03-10 16:39:18 +09001237 final BatteryStatsManager batteryStats =
Aaron Huange044c462020-10-27 03:36:19 +08001238 context.getSystemService(BatteryStatsManager.class);
1239 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1240 }
Lorenzo Colitti4c9e2022021-03-10 16:39:18 +09001241
1242 public boolean getCellular464XlatEnabled() {
1243 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1244 }
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001245 }
1246
junyulaic9a235a2021-01-26 15:29:15 +08001247 public ConnectivityService(Context context) {
1248 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VANe58b2002021-03-06 00:26:43 +09001249 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1250 new Dependencies());
Hugo Benichi638621a2016-07-28 17:53:06 +09001251 }
1252
1253 @VisibleForTesting
junyulaic9a235a2021-01-26 15:29:15 +08001254 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1255 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001256 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001257
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00001258 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001259 mSystemProperties = mDeps.getSystemProperties();
1260 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00001261 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09001262 mResources = deps.getResources(mContext);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001263 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colittib4f8d8e2021-03-30 19:29:00 +09001264 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitti756a0222017-03-21 18:54:11 +09001265
Hugo Benichi638621a2016-07-28 17:53:06 +09001266 mMetricsLog = logger;
Chalard Jean58d486c2019-12-10 22:16:53 +09001267 mNetworkRanker = new NetworkRanker();
James Mattis6e6fabf2021-01-10 14:24:24 -08001268 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1269 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colittif2514122021-03-12 22:50:57 +09001270 Process.myUid(), defaultInternetRequest, null,
Roshan Pius7992afd2020-12-22 15:10:42 -08001271 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis6e6fabf2021-01-10 14:24:24 -08001272 null /* attributionTags */);
Chalard Jean1bc77a92021-02-04 13:12:59 +09001273 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1274 mDefaultNetworkRequests.add(mDefaultRequest);
1275 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline74d68ef2015-04-30 12:58:40 +09001276
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09001277 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09001278 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt948aea52014-04-11 15:53:27 -07001279
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001280 // The default WiFi request is a background request so that apps using WiFi are
1281 // migrated to a better network (typically ethernet) when one comes up, instead
1282 // of staying on WiFi forever.
1283 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1284 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1285
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001286 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1287 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1288 NetworkRequest.Type.BACKGROUND_REQUEST);
1289
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001290 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti1b8b5cd2015-08-07 20:17:27 +09001291 mHandlerThread.start();
1292 mHandler = new InternalHandler(mHandlerThread.getLooper());
1293 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting0ffbf922019-12-18 10:57:50 -08001294 mConnectivityDiagnosticsHandler =
1295 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001296
Jeremy Joslinb9846d02014-12-03 17:15:28 -08001297 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08001298 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslinb9846d02014-12-03 17:15:28 -08001299
Lorenzo Colitti756a0222017-03-21 18:54:11 +09001300 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
junyulaif6d98ec2020-12-14 18:41:52 +08001301 // TODO: Consider making the timer customizable.
1302 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09001303
junyulaic9a235a2021-01-26 15:29:15 +08001304 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu7121b5e2020-12-29 18:15:13 +08001305 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00001306 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001307 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi0a28d302017-02-11 17:04:43 +09001308
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00001309 mNetd = netd;
Wink Saville690cb182013-06-29 21:10:57 -07001310 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kestingd292a332020-01-05 14:06:39 -08001311 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1312 mLocationPermissionChecker = new LocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001313
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00001314 // To ensure uid state is synchronized with Network Policy, register for
junyulai5ab727b2018-08-07 19:50:45 +08001315 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1316 // reading existing policy from disk.
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00001317 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001318
1319 final PowerManager powerManager = (PowerManager) context.getSystemService(
1320 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001321 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin94c30992014-11-05 10:32:09 -08001322 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001323
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09001324 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1325 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09001326 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001327 for (int p : protectedNetworks) {
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09001328 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001329 mProtectedNetworks.add(p);
1330 } else {
1331 if (DBG) loge("Ignoring protectedNetwork " + p);
1332 }
1333 }
1334
soma, kawata90913e92019-05-23 09:30:40 +09001335 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1336
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00001337 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranc5756e42014-09-24 09:16:19 -07001338
James Mattisbd275dc2021-03-13 19:27:21 -08001339 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09001340 // Listen for user add/removes to inform PermissionMonitor.
Varun Anand273f9002019-02-06 10:13:38 -08001341 // Should run on mHandler to avoid any races.
James Mattisbd275dc2021-03-13 19:27:21 -08001342 final IntentFilter userIntentFilter = new IntentFilter();
1343 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1344 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1345 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1346 null /* broadcastPermission */, mHandler);
paulhufa229ae2020-10-13 15:56:13 +08001347
James Mattisbd275dc2021-03-13 19:27:21 -08001348 // Listen to package add/removes for netd
1349 final IntentFilter packageIntentFilter = new IntentFilter();
1350 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1351 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1352 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1353 packageIntentFilter.addDataScheme("package");
1354 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09001355 null /* broadcastPermission */, mHandler);
junyulaib56dc512020-08-28 13:44:33 +08001356
lucaslinea5378c2021-02-20 18:59:47 +08001357 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001358
lucaslindb201da2021-02-23 01:12:55 +08001359 mNetdCallback = new NetdCallback();
1360 try {
1361 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1362 } catch (RemoteException | ServiceSpecificException e) {
1363 loge("Error registering event listener :" + e);
1364 }
1365
Erik Kline74d68ef2015-04-30 12:58:40 +09001366 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1367 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001368
junyulai61143782019-03-04 22:45:36 +08001369 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu13cafd92020-10-14 09:51:54 +08001370 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Bright60f02ed2020-06-15 16:10:01 -07001371 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colittie5ebb712016-08-29 14:03:11 +09001372
1373 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08001374 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colittie5ebb712016-08-29 14:03:11 +09001375 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1376 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08001377 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colittie5ebb712016-08-29 14:03:11 +09001378 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1379 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti49d32fe2016-09-16 23:43:38 +09001380
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09001381 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jean78515442021-03-19 13:49:56 +09001382 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09001383 mMultinetworkPolicyTracker.start();
Erik Klinecca88b02017-12-13 19:40:49 +09001384
Chiachang Wang67106862020-10-20 15:38:58 +08001385 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Klinec06d4f92018-01-11 21:07:29 +09001386 registerPrivateDnsSettingsCallbacks();
James Mattis1238af22020-12-23 16:37:26 -08001387
Chalard Jeandd753522020-12-21 18:36:52 +09001388 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1389 // request that doesn't allow fallback to the default network. It should never be visible
1390 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1391 // arguments like the handler or the DnsResolver.
1392 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslinea5378c2021-02-20 18:59:47 +08001393 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen69ed8432021-05-14 14:30:43 +08001394 new Network(INetd.UNREACHABLE_NET_ID),
James Mattis1238af22020-12-23 16:37:26 -08001395 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeandd753522020-12-21 18:36:52 +09001396 new LinkProperties(), new NetworkCapabilities(),
1397 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jeane634b282021-03-05 23:07:53 +09001398 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1399 mLingerDelayMs, mQosCallbackTracker, mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001400 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001401
Chalard Jeand9605fb2018-04-18 20:18:38 +09001402 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Chalard Jean9d968182021-02-25 21:46:34 +09001403 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1404 }
1405
1406 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1407 @NonNull final UidRange uids) {
Chalard Jeand9605fb2018-04-18 20:18:38 +09001408 final NetworkCapabilities netCap = new NetworkCapabilities();
1409 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai71d157f2021-01-13 18:13:11 +08001410 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jeand9605fb2018-04-18 20:18:38 +09001411 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Chiachang Wangd5034c72021-02-22 18:36:38 +08001412 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
Chalard Jeand9605fb2018-04-18 20:18:38 +09001413 return netCap;
1414 }
1415
James Mattis6e6fabf2021-01-10 14:24:24 -08001416 private NetworkRequest createDefaultRequest() {
1417 return createDefaultInternetRequestForTransport(
1418 TYPE_NONE, NetworkRequest.Type.REQUEST);
1419 }
1420
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09001421 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09001422 int transportType, NetworkRequest.Type type) {
Erik Kline72306522018-06-14 17:36:40 +09001423 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittid21a5262015-05-14 17:07:20 +09001424 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai71d157f2021-01-13 18:13:11 +08001425 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08001426 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis6e6fabf2021-01-10 14:24:24 -08001427 if (transportType > TYPE_NONE) {
Erik Kline74d68ef2015-04-30 12:58:40 +09001428 netCap.addTransportType(transportType);
1429 }
James Mattis6e6fabf2021-01-10 14:24:24 -08001430 return createNetworkRequest(type, netCap);
1431 }
1432
1433 private NetworkRequest createNetworkRequest(
1434 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09001435 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline74d68ef2015-04-30 12:58:40 +09001436 }
1437
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001438 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1439 NetworkRequest.Type type) {
1440 final NetworkCapabilities netCap = new NetworkCapabilities();
1441 netCap.clearAll();
1442 netCap.addCapability(capability);
1443 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1444 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1445 }
1446
Lorenzo Colitti6caa9fe2016-06-05 21:00:23 +09001447 // Used only for testing.
1448 // TODO: Delete this and either:
Erik Kline076bd3d2018-03-21 07:18:33 -07001449 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti6caa9fe2016-06-05 21:00:23 +09001450 // changing ContentResolver to make registerContentObserver non-final).
1451 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1452 // by subclassing SettingsObserver.
1453 @VisibleForTesting
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001454 void updateAlwaysOnNetworks() {
1455 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti6caa9fe2016-06-05 21:00:23 +09001456 }
1457
Erik Kline076bd3d2018-03-21 07:18:33 -07001458 // See FakeSettingsProvider comment above.
1459 @VisibleForTesting
1460 void updatePrivateDnsSettings() {
1461 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1462 }
1463
Remi NGUYEN VAN52950ed2021-03-06 00:11:24 +09001464 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001465 final boolean enable = mContext.getResources().getBoolean(id);
1466 handleAlwaysOnNetworkRequest(networkRequest, enable);
1467 }
1468
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001469 private void handleAlwaysOnNetworkRequest(
1470 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09001471 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001472 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08001473 handleAlwaysOnNetworkRequest(networkRequest, enable);
1474 }
1475
1476 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001477 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline74d68ef2015-04-30 12:58:40 +09001478 if (enable == isEnabled) {
1479 return; // Nothing to do.
1480 }
1481
1482 if (enable) {
1483 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittif2514122021-03-12 22:50:57 +09001484 Process.myUid(), networkRequest, null, new Binder(),
Roshan Pius7992afd2020-12-22 15:10:42 -08001485 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis6e6fabf2021-01-10 14:24:24 -08001486 null /* attributionTags */));
Erik Kline74d68ef2015-04-30 12:58:40 +09001487 } else {
Etan Cohen06633de2019-01-08 12:09:18 -08001488 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1489 /* callOnUnavailable */ false);
Erik Kline74d68ef2015-04-30 12:58:40 +09001490 }
1491 }
1492
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001493 private void handleConfigureAlwaysOnNetworks() {
paulhu79260c22021-03-17 20:30:33 +08001494 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1495 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1496 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1497 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09001498 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1499 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN4806af52021-05-19 12:05:13 +09001500 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001501 }
1502
Erik Kline74d68ef2015-04-30 12:58:40 +09001503 private void registerSettingsCallbacks() {
1504 // Watch for global HTTP proxy changes.
1505 mSettingsObserver.observe(
1506 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1507 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1508
1509 // Watch for whether or not to keep mobile data always on.
1510 mSettingsObserver.observe(
paulhu79260c22021-03-17 20:30:33 +08001511 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001512 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1513
1514 // Watch for whether or not to keep wifi always on.
1515 mSettingsObserver.observe(
paulhu79260c22021-03-17 20:30:33 +08001516 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07001517 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Kline74d68ef2015-04-30 12:58:40 +09001518 }
1519
Erik Klinec06d4f92018-01-11 21:07:29 +09001520 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline076bd3d2018-03-21 07:18:33 -07001521 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1522 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinec06d4f92018-01-11 21:07:29 +09001523 }
1524 }
1525
Robert Greenwalt469fa2a2014-05-18 16:22:10 -07001526 private synchronized int nextNetworkRequestId() {
junyulai5ef392c2020-12-14 18:51:02 +08001527 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1528 // doing that.
Robert Greenwalt469fa2a2014-05-18 16:22:10 -07001529 return mNextNetworkRequestId++;
1530 }
1531
junyulaica1fbb62018-06-13 15:00:37 +08001532 @VisibleForTesting
1533 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001534 if (network == null) {
1535 return null;
1536 }
Serik Beketayev284cb872020-12-07 22:43:07 -08001537 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline076bd3d2018-03-21 07:18:33 -07001538 }
1539
1540 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001541 synchronized (mNetworkForNetId) {
Erik Kline076bd3d2018-03-21 07:18:33 -07001542 return mNetworkForNetId.get(netId);
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001543 }
Jeff Sharkeyea403782016-04-22 09:50:16 -06001544 }
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001545
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001546 // TODO: determine what to do when more than one VPN applies to |uid|.
1547 private NetworkAgentInfo getVpnForUid(int uid) {
1548 synchronized (mNetworkForNetId) {
1549 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1550 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1551 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1552 return nai;
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001553 }
1554 }
1555 }
1556 return null;
1557 }
1558
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001559 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09001560 if (mLockdownEnabled) return null;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001561 final NetworkAgentInfo nai = getVpnForUid(uid);
1562 if (nai != null) return nai.declaredUnderlyingNetworks;
1563 return null;
1564 }
1565
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001566 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattisf61f7be2021-01-31 17:06:19 -08001567 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandranaf655d92014-11-11 16:09:21 -08001568
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001569 final Network[] networks = getVpnUnderlyingNetworks(uid);
1570 if (networks != null) {
1571 // getUnderlyingNetworks() returns:
1572 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1573 // empty array => the VPN explicitly said "no default network".
1574 // non-empty array => the VPN specified one or more default networks; we use the
1575 // first one.
1576 if (networks.length > 0) {
1577 nai = getNetworkAgentInfoForNetwork(networks[0]);
1578 } else {
1579 nai = null;
Sreeram Ramachandranaf655d92014-11-11 16:09:21 -08001580 }
1581 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001582 return nai;
Paul Jensen57d231c2014-08-29 09:54:01 -04001583 }
1584
1585 /**
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001586 * Check if UID should be blocked from using the specified network.
Paul Jensen57d231c2014-08-29 09:54:01 -04001587 */
paulhu3b063e32020-12-30 00:42:19 +08001588 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1589 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001590 // Networks aren't blocked when ignoring blocked status
Hugo Benichi0a28d302017-02-11 17:04:43 +09001591 if (ignoreBlocked) {
1592 return false;
1593 }
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09001594 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu3b063e32020-12-30 00:42:19 +08001595 final long ident = Binder.clearCallingIdentity();
1596 try {
1597 final boolean metered = nc == null ? true : nc.isMetered();
1598 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1599 } finally {
1600 Binder.restoreCallingIdentity(ident);
1601 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001602 }
1603
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001604 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichi7b3bf372016-07-11 11:05:12 +09001605 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1606 return;
1607 }
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001608 final boolean blocked;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001609 synchronized (mBlockedAppUids) {
1610 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001611 blocked = true;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001612 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001613 blocked = false;
1614 } else {
1615 return;
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001616 }
1617 }
Hugo Benichi23ec1c92017-03-30 10:46:05 +09001618 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1619 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1620 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09001621 }
1622
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001623 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulai5ab727b2018-08-07 19:50:45 +08001624 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1625 return;
1626 }
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001627 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattis622428c2020-12-02 14:12:41 -08001628 final int requestId = nri.getActiveRequest() != null
1629 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai02025672020-05-29 14:44:42 +08001630 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09001631 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankab9c396e2021-04-21 07:23:54 +00001632 Integer.toHexString(blocked)));
junyulai5ab727b2018-08-07 19:50:45 +08001633 }
1634
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001635 /**
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001636 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkeyea403782016-04-22 09:50:16 -06001637 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu3b063e32020-12-30 00:42:19 +08001638 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001639 */
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001640 @NonNull
1641 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1642 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti36567092021-03-03 14:39:04 +09001643 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1644 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1645 // but only exists if an app asks about them or requests them. Ensure the requesting app
1646 // gets the type it asks for.
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001647 filtered.setType(type);
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09001648 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1649 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1650 null /* extraInfo */);
1651 }
1652 filterForLegacyLockdown(filtered);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001653 return filtered;
1654 }
1655
1656 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1657 boolean ignoreBlocked) {
1658 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1659 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001660 }
1661
1662 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001663 * Return NetworkInfo for the active (i.e., connected) network interface.
1664 * It is assumed that at most one network is active at a time. If more
1665 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001666 * @return the info for the active network, or {@code null} if none is
1667 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001668 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001669 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001670 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001671 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001672 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001673 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1674 if (nai == null) return null;
1675 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1676 maybeLogBlockedNetworkInfo(networkInfo, uid);
1677 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001678 }
1679
Paul Jensenc2569432015-02-13 14:18:39 -05001680 @Override
1681 public Network getActiveNetwork() {
1682 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001683 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Leeda4d2e22016-03-24 12:07:00 +00001684 }
1685
1686 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001687 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu5e094422021-01-25 18:53:17 +08001688 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001689 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leeda4d2e22016-03-24 12:07:00 +00001690 }
1691
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001692 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001693 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1694 if (vpnNai != null) {
1695 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1696 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1697 return vpnNai.network;
Chalard Jeand9605fb2018-04-18 20:18:38 +09001698 }
Paul Jensenc2569432015-02-13 14:18:39 -05001699 }
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001700
James Mattisf61f7be2021-01-31 17:06:19 -08001701 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001702 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1703 ignoreBlocked)) {
1704 return null;
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001705 }
Lorenzo Colittia68139a2020-12-15 15:47:24 +09001706 return nai.network;
Paul Jensenc2569432015-02-13 14:18:39 -05001707 }
1708
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001709 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001710 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu5e094422021-01-25 18:53:17 +08001711 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001712 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1713 if (nai == null) return null;
1714 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001715 }
1716
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001717 /** Returns a NetworkInfo object for a network that doesn't exist. */
1718 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1719 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1720 getNetworkTypeName(networkType), "" /* subtypeName */);
1721 info.setIsAvailable(true);
1722 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1723 // background data is restricted.
1724 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1725 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1726 ? DetailedState.BLOCKED
1727 : DetailedState.DISCONNECTED;
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09001728 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1729 filterForLegacyLockdown(info);
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001730 return info;
1731 }
1732
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001733 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001734 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1735 return null;
1736 }
1737 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti998a02f2021-03-02 23:28:49 +09001738 if (nai == null) {
1739 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001740 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001741 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1742 false);
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001743 }
1744
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001745 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001746 public NetworkInfo getNetworkInfo(int networkType) {
1747 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001748 final int uid = mDeps.getCallingUid();
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001749 if (getVpnUnderlyingNetworks(uid) != null) {
1750 // A VPN is active, so we may need to return one of its underlying networks. This
1751 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001752 // getNetworkAgentInfoForUid.
1753 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1754 if (nai == null) return null;
1755 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1756 if (networkInfo.getType() == networkType) {
1757 return networkInfo;
Lorenzo Colitti66d4ed02015-02-05 13:57:17 +09001758 }
1759 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001760 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001761 }
1762
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001763 @Override
Jeff Sharkey833c35b2016-04-28 15:33:18 -06001764 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001765 enforceAccessPermission();
Jeff Sharkeyea403782016-04-22 09:50:16 -06001766 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001767 if (nai == null) return null;
1768 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001769 }
1770
1771 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001772 public NetworkInfo[] getAllNetworkInfo() {
1773 enforceAccessPermission();
Serik Beketayeveb7e8c62021-01-15 16:47:25 -08001774 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensene8015422014-09-19 11:14:12 -04001775 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1776 networkType++) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001777 NetworkInfo info = getNetworkInfo(networkType);
1778 if (info != null) {
1779 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001780 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001781 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001782 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001783 }
1784
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001785 @Override
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001786 public Network getNetworkForType(int networkType) {
1787 enforceAccessPermission();
Lorenzo Colitti6f55e612021-01-15 23:35:16 +09001788 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1789 return null;
1790 }
1791 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1792 if (nai == null) {
1793 return null;
1794 }
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001795 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001796 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1797 return null;
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001798 }
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001799 return nai.network;
Lorenzo Colitti2b2d73c2014-08-22 17:10:50 -07001800 }
1801
1802 @Override
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001803 public Network[] getAllNetworks() {
1804 enforceAccessPermission();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001805 synchronized (mNetworkForNetId) {
Paul Jensen71299dd2015-04-06 11:54:53 -04001806 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001807 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensen71299dd2015-04-06 11:54:53 -04001808 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001809 }
Paul Jensen71299dd2015-04-06 11:54:53 -04001810 return result;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001811 }
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001812 }
1813
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001814 @Override
Qingxi Libf6bf082020-01-08 12:51:49 -08001815 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusc97d8062020-12-17 14:53:09 -08001816 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001817 // The basic principle is: if an app's traffic could possibly go over a
1818 // network, without the app doing anything multinetwork-specific,
1819 // (hence, by "default"), then include that network's capabilities in
1820 // the array.
1821 //
1822 // In the normal case, app traffic only goes over the system's default
1823 // network connection, so that's the only network returned.
1824 //
1825 // With a VPN in force, some app traffic may go into the VPN, and thus
1826 // over whatever underlying networks the VPN specifies, while other app
1827 // traffic may go over the system default network (e.g.: a split-tunnel
1828 // VPN, or an app disallowed by the VPN), so the set of networks
1829 // returned includes the VPN's underlying networks and the system
1830 // default.
1831 enforceAccessPermission();
1832
Chalard Jean4ec33bf2018-06-04 13:33:12 +09001833 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001834
James Mattisf61f7be2021-01-31 17:06:19 -08001835 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1836 if (!nri.isBeingSatisfied()) {
1837 continue;
1838 }
1839 final NetworkAgentInfo nai = nri.getSatisfier();
1840 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1841 if (null != nc
1842 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1843 && !result.containsKey(nai.network)) {
1844 result.put(
1845 nai.network,
1846 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08001847 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001848 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1849 callingAttributionTag));
James Mattisf61f7be2021-01-31 17:06:19 -08001850 }
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001851 }
1852
Lorenzo Colitti011f29d2020-12-15 00:49:41 +09001853 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colittie0857092021-03-12 22:39:08 +09001854 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattisf61f7be2021-01-31 17:06:19 -08001855 if (null != networks) {
1856 for (final Network network : networks) {
1857 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1858 if (null != nc) {
Roshan Pius423fff62020-12-28 09:01:49 -08001859 result.put(
1860 network,
1861 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08001862 nc,
1863 false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001864 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusc97d8062020-12-17 14:53:09 -08001865 callingAttributionTag));
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09001866 }
1867 }
1868 }
1869
1870 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1871 out = result.values().toArray(out);
1872 return out;
1873 }
1874
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001875 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001876 public boolean isNetworkSupported(int networkType) {
1877 enforceAccessPermission();
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001878 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001879 }
1880
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001881 /**
1882 * Return LinkProperties for the active (i.e., connected) default
James Mattisf61f7be2021-01-31 17:06:19 -08001883 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001884 * @return the ip properties for the active network, or {@code null} if
1885 * none is active
1886 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001887 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001888 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001889 enforceAccessPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001890 final int uid = mDeps.getCallingUid();
Lorenzo Colitticb1d6a12021-01-19 01:33:05 +09001891 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1892 if (nai == null) return null;
1893 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001894 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001895 }
1896
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001897 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001898 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001899 enforceAccessPermission();
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08001900 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001901 final LinkProperties lp = getLinkProperties(nai);
1902 if (lp == null) return null;
1903 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001904 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001905 }
1906
Robert Greenwalt54d534f2014-05-13 21:41:06 -07001907 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07001908 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001909 public LinkProperties getLinkProperties(Network network) {
1910 enforceAccessPermission();
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001911 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1912 if (lp == null) return null;
1913 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001914 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9a35d82017-04-06 16:01:44 +09001915 }
1916
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001917 @Nullable
1918 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09001919 if (nai == null) {
1920 return null;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001921 }
Hugo Benichie9a35d82017-04-06 16:01:44 +09001922 synchronized (nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001923 return nai.linkProperties;
Hugo Benichie9a35d82017-04-06 16:01:44 +09001924 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001925 }
1926
Qingxi Libf6bf082020-01-08 12:51:49 -08001927 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1928 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1929 }
1930
Lorenzo Colitti98097292015-05-14 17:28:27 +09001931 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001932 if (nai == null) return null;
1933 synchronized (nai) {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09001934 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001935 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt701a5c32014-06-23 11:40:00 -07001936 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07001937 }
1938
1939 @Override
Roshan Piusc97d8062020-12-17 14:53:09 -08001940 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1941 @Nullable String callingAttributionTag) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09001942 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colitti98097292015-05-14 17:28:27 +09001943 enforceAccessPermission();
Roshan Pius423fff62020-12-28 09:01:49 -08001944 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Libf6bf082020-01-08 12:51:49 -08001945 getNetworkCapabilitiesInternal(network),
Roshan Pius7992afd2020-12-22 15:10:42 -08001946 false /* includeLocationSensitiveInfo */,
Roshan Pius332e7a22021-03-21 17:55:29 +00001947 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colitti98097292015-05-14 17:28:27 +09001948 }
1949
Qingxi Libb3347b2020-01-17 17:54:27 -08001950 @VisibleForTesting
1951 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean88953062018-02-21 18:43:54 +09001952 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean058cd312018-04-11 21:09:10 +09001953 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jeand9605fb2018-04-18 20:18:38 +09001954 if (!checkSettingsPermission(callerPid, callerUid)) {
1955 newNc.setUids(null);
1956 newNc.setSSID(null);
1957 }
Etan Cohenc069b062018-12-30 17:59:59 -08001958 if (newNc.getNetworkSpecifier() != null) {
1959 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1960 }
Cody Kestingc5cadf62020-03-16 18:15:28 -07001961 newNc.setAdministratorUids(new int[0]);
Benedict Wong4310e452021-03-24 14:01:51 -07001962 if (!checkAnyPermissionOf(
1963 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai58153cc2021-04-14 23:33:31 +08001964 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong4310e452021-03-24 14:01:51 -07001965 }
Qingxi Libb3347b2020-01-17 17:54:27 -08001966
Chalard Jean058cd312018-04-11 21:09:10 +09001967 return newNc;
Chalard Jeanb70f7cc2018-01-26 19:24:40 +09001968 }
1969
Roshan Pius332e7a22021-03-21 17:55:29 +00001970 /**
1971 * Wrapper used to cache the permission check results performed for the corresponding
1972 * app. This avoid performing multiple permission checks for different fields in
1973 * NetworkCapabilities.
1974 * Note: This wrapper does not support any sort of invalidation and thus must not be
1975 * persistent or long-lived. It may only be used for the time necessary to
1976 * compute the redactions required by one particular NetworkCallback or
1977 * synchronous call.
1978 */
1979 private class RedactionPermissionChecker {
1980 private final int mCallingPid;
1981 private final int mCallingUid;
1982 @NonNull private final String mCallingPackageName;
1983 @Nullable private final String mCallingAttributionTag;
1984
1985 private Boolean mHasLocationPermission = null;
1986 private Boolean mHasLocalMacAddressPermission = null;
1987 private Boolean mHasSettingsPermission = null;
1988
1989 RedactionPermissionChecker(int callingPid, int callingUid,
1990 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
1991 mCallingPid = callingPid;
1992 mCallingUid = callingUid;
1993 mCallingPackageName = callingPackageName;
1994 mCallingAttributionTag = callingAttributionTag;
Roshan Pius423fff62020-12-28 09:01:49 -08001995 }
Roshan Pius332e7a22021-03-21 17:55:29 +00001996
1997 private boolean hasLocationPermissionInternal() {
1998 final long token = Binder.clearCallingIdentity();
1999 try {
2000 return mLocationPermissionChecker.checkLocationPermission(
2001 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2002 null /* message */);
2003 } finally {
2004 Binder.restoreCallingIdentity(token);
2005 }
2006 }
2007
2008 /**
2009 * Returns whether the app holds location permission or not (might return cached result
2010 * if the permission was already checked before).
2011 */
2012 public boolean hasLocationPermission() {
2013 if (mHasLocationPermission == null) {
2014 // If there is no cached result, perform the check now.
2015 mHasLocationPermission = hasLocationPermissionInternal();
2016 }
2017 return mHasLocationPermission;
2018 }
2019
2020 /**
2021 * Returns whether the app holds local mac address permission or not (might return cached
2022 * result if the permission was already checked before).
2023 */
2024 public boolean hasLocalMacAddressPermission() {
2025 if (mHasLocalMacAddressPermission == null) {
2026 // If there is no cached result, perform the check now.
2027 mHasLocalMacAddressPermission =
2028 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2029 }
2030 return mHasLocalMacAddressPermission;
2031 }
2032
2033 /**
2034 * Returns whether the app holds settings permission or not (might return cached
2035 * result if the permission was already checked before).
2036 */
2037 public boolean hasSettingsPermission() {
2038 if (mHasSettingsPermission == null) {
2039 // If there is no cached result, perform the check now.
2040 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2041 }
2042 return mHasSettingsPermission;
2043 }
2044 }
2045
2046 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2047 @NetworkCapabilities.NetCapability long redaction) {
2048 return (redactions & redaction) != 0;
2049 }
2050
2051 /**
2052 * Use the provided |applicableRedactions| to check the receiving app's
2053 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2054 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2055 * before being sent to the corresponding app.
2056 */
2057 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2058 @NetworkCapabilities.RedactionType long applicableRedactions,
2059 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2060 boolean includeLocationSensitiveInfo) {
2061 long redactions = applicableRedactions;
2062 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2063 if (includeLocationSensitiveInfo
2064 && redactionPermissionChecker.hasLocationPermission()) {
2065 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2066 }
2067 }
2068 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2069 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2070 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2071 }
2072 }
2073 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2074 if (redactionPermissionChecker.hasSettingsPermission()) {
2075 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2076 }
2077 }
2078 return redactions;
Roshan Pius423fff62020-12-28 09:01:49 -08002079 }
2080
Qingxi Libf6bf082020-01-08 12:51:49 -08002081 @VisibleForTesting
2082 @Nullable
Roshan Pius423fff62020-12-28 09:01:49 -08002083 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius7992afd2020-12-22 15:10:42 -08002084 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius332e7a22021-03-21 17:55:29 +00002085 int callingPid, int callingUid, @NonNull String callingPkgName,
2086 @Nullable String callingAttributionTag) {
Qingxi Libf6bf082020-01-08 12:51:49 -08002087 if (nc == null) {
2088 return null;
2089 }
Roshan Pius423fff62020-12-28 09:01:49 -08002090 // Avoid doing location permission check if the transport info has no location sensitive
2091 // data.
Roshan Pius332e7a22021-03-21 17:55:29 +00002092 final RedactionPermissionChecker redactionPermissionChecker =
2093 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2094 callingAttributionTag);
2095 final long redactions = retrieveRequiredRedactions(
2096 nc.getApplicableRedactions(), redactionPermissionChecker,
2097 includeLocationSensitiveInfo);
2098 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius423fff62020-12-28 09:01:49 -08002099 // Reset owner uid if not destined for the owner app.
Roshan Pius332e7a22021-03-21 17:55:29 +00002100 if (callingUid != nc.getOwnerUid()) {
Qingxi Libf6bf082020-01-08 12:51:49 -08002101 newNc.setOwnerUid(INVALID_UID);
2102 return newNc;
2103 }
Benedict Wonge3bcbc02020-06-08 11:55:38 -07002104 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2105 if (nc.hasTransport(TRANSPORT_VPN)) {
2106 // Owner UIDs already checked above. No need to re-check.
2107 return newNc;
2108 }
Roshan Pius332e7a22021-03-21 17:55:29 +00002109 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2110 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius7992afd2020-12-22 15:10:42 -08002111 // compatibility for older apps.
2112 if (!includeLocationSensitiveInfo
2113 && isTargetSdkAtleast(
Roshan Pius332e7a22021-03-21 17:55:29 +00002114 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius7992afd2020-12-22 15:10:42 -08002115 newNc.setOwnerUid(INVALID_UID);
2116 return newNc;
2117 }
Roshan Pius423fff62020-12-28 09:01:49 -08002118 // Reset owner uid if the app has no location permission.
Roshan Pius332e7a22021-03-21 17:55:29 +00002119 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius423fff62020-12-28 09:01:49 -08002120 newNc.setOwnerUid(INVALID_UID);
2121 }
Qingxi Libf6bf082020-01-08 12:51:49 -08002122 return newNc;
Qingxi Libb3347b2020-01-17 17:54:27 -08002123 }
2124
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09002125 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2126 LinkProperties lp, int callerPid, int callerUid) {
2127 if (lp == null) return new LinkProperties();
2128
2129 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2130 final boolean needsSanitization =
2131 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2132 if (!needsSanitization) {
2133 return new LinkProperties(lp);
2134 }
2135
2136 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VANc3895462020-03-16 14:48:37 +09002137 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09002138 }
2139
2140 final LinkProperties newLp = new LinkProperties(lp);
2141 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2142 // object gets parceled.
2143 newLp.setCaptivePortalApiUrl(null);
2144 newLp.setCaptivePortalData(null);
2145 return newLp;
2146 }
2147
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002148 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2149 int callerUid, String callerPackageName) {
Lorenzo Colittid82c1ec2021-05-17 20:31:21 +09002150 // There is no need to track the effective UID of the request here. If the caller
2151 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean88953062018-02-21 18:43:54 +09002152 if (!checkSettingsPermission()) {
Lorenzo Colittid82c1ec2021-05-17 20:31:21 +09002153 // Unprivileged apps can only pass in null or their own UID.
2154 if (nc.getUids() == null) {
2155 // If the caller passes in null, the callback will also match networks that do not
2156 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2157 // In this case, redact everything in the request immediately. This ensures that the
2158 // app is not able to get any redacted information by filing an unredacted request
2159 // and observing whether the request matches something.
2160 if (nc.getNetworkSpecifier() != null) {
2161 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2162 }
2163 } else {
2164 nc.setSingleUid(callerUid);
2165 }
Chalard Jean88953062018-02-21 18:43:54 +09002166 }
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08002167 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kestingc5cadf62020-03-16 18:15:28 -07002168 nc.setAdministratorUids(new int[0]);
Qingxi Libb3347b2020-01-17 17:54:27 -08002169
2170 // Clear owner UID; this can never come from an app.
2171 nc.setOwnerUid(INVALID_UID);
Chalard Jean88953062018-02-21 18:43:54 +09002172 }
2173
Chalard Jeana43eede2018-03-20 19:13:57 +09002174 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002175 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jeana43eede2018-03-20 19:13:57 +09002176 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2177 }
2178 }
2179
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09002180 @Override
2181 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2182 enforceAccessPermission();
2183 final int callerUid = Binder.getCallingUid();
2184 final long token = Binder.clearCallingIdentity();
2185 try {
2186 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2187 } finally {
2188 Binder.restoreCallingIdentity(token);
2189 }
2190 }
2191
junyulai57840802021-03-03 12:09:05 +08002192 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colitti98097292015-05-14 17:28:27 +09002193 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002194 public NetworkState[] getAllNetworkState() {
paulhud70b7dd2019-08-12 16:25:11 +08002195 // This contains IMSI details, so make sure the caller is privileged.
paulhu5e094422021-01-25 18:53:17 +08002196 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfe0b08d2014-12-02 18:30:14 -08002197
Serik Beketayeveb7e8c62021-01-15 16:47:25 -08002198 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huang20605e52021-04-17 13:46:25 +08002199 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulai57840802021-03-03 12:09:05 +08002200 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2201 // NetworkAgentInfo.
Aaron Huangc8081e92021-04-20 17:19:46 +08002202 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaidddf2b62020-12-29 19:17:01 +08002203 if (nai != null && nai.networkInfo.isConnected()) {
junyulai57840802021-03-03 12:09:05 +08002204 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangc8081e92021-04-20 17:19:46 +08002205 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2206 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002207 }
2208 }
2209 return result.toArray(new NetworkState[result.size()]);
2210 }
2211
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002212 @Override
junyulai57840802021-03-03 12:09:05 +08002213 @NonNull
Aaron Huang20605e52021-04-17 13:46:25 +08002214 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulai57840802021-03-03 12:09:05 +08002215 // This contains IMSI details, so make sure the caller is privileged.
junyulai91113d42021-05-14 18:04:29 +08002216 enforceNetworkStackOrSettingsPermission();
junyulai57840802021-03-03 12:09:05 +08002217
2218 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2219 for (Network network : getAllNetworks()) {
2220 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2221 // TODO: Consider include SUSPENDED networks, which should be considered as
2222 // temporary shortage of connectivity of a connected network.
2223 if (nai != null && nai.networkInfo.isConnected()) {
2224 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2225 // NetworkCapabilities, which may contain UIDs of apps to which the
2226 // network applies. Should the UIDs be cleared so as not to leak or
2227 // interfere ?
2228 result.add(nai.getNetworkStateSnapshot());
2229 }
2230 }
2231 return result;
2232 }
2233
2234 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002235 public boolean isActiveNetworkMetered() {
2236 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002237
Qingxi Libf6bf082020-01-08 12:51:49 -08002238 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkey41a72692017-07-12 10:50:42 -06002239 if (caps != null) {
2240 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2241 } else {
2242 // Always return the most conservative value
2243 return true;
2244 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002245 }
2246
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002247 /**
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002248 * Ensures that the system cannot call a particular method.
2249 */
2250 private boolean disallowedBecauseSystemCaller() {
2251 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admal6d761f92019-04-05 10:06:37 -07002252 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2253 // for devices launched with Q and above. However, existing devices upgrading to Q and
2254 // above must continued to be supported for few more releases.
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002255 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admal6d761f92019-04-05 10:06:37 -07002256 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002257 log("This method exists only for app backwards compatibility"
2258 + " and must not be called by system services.");
2259 return true;
2260 }
2261 return false;
2262 }
2263
2264 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002265 * Ensure that a network route exists to deliver traffic to the specified
2266 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002267 * @param networkType the type of the network over which traffic to the
2268 * specified host is to be routed
2269 * @param hostAddress the IP address of the host to which the route is
2270 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002271 * @return {@code true} on success, {@code false} on failure
2272 */
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09002273 @Override
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002274 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2275 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti62f752c2018-09-28 11:31:55 +09002276 if (disallowedBecauseSystemCaller()) {
2277 return false;
2278 }
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002279 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002280 if (mProtectedNetworks.contains(networkType)) {
paulhud70b7dd2019-08-12 16:25:11 +08002281 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002282 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002283
Chad Brubaker83ec7fc2014-02-14 13:24:29 -08002284 InetAddress addr;
2285 try {
2286 addr = InetAddress.getByAddress(hostAddress);
2287 } catch (UnknownHostException e) {
2288 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2289 return false;
2290 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002291
The Android Open Source Project28527d22009-03-03 19:31:44 -08002292 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002293 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002294 return false;
2295 }
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002296
2297 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2298 if (nai == null) {
2299 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2300 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2301 } else {
2302 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2303 }
2304 return false;
Ken Mixter7caa36a2013-11-07 22:08:24 -08002305 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002306
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002307 DetailedState netState;
2308 synchronized (nai) {
2309 netState = nai.networkInfo.getDetailedState();
2310 }
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002311
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002312 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002313 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07002314 log("requestRouteToHostAddress on down network "
2315 + "(" + networkType + ") - dropped"
Robert Greenwalt7d19a362014-06-03 17:22:11 -07002316 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002317 }
2318 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002319 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002320
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002321 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002322 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002323 try {
Paul Jensen8b6260f2014-07-11 08:17:29 -04002324 LinkProperties lp;
2325 int netId;
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002326 synchronized (nai) {
2327 lp = nai.linkProperties;
Serik Beketayev284cb872020-12-07 22:43:07 -08002328 netId = nai.network.getNetId();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07002329 }
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002330 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colitti7e27c542021-04-10 01:01:43 +09002331 if (DBG) {
2332 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2333 }
Wink Saville690cb182013-06-29 21:10:57 -07002334 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002335 } finally {
2336 Binder.restoreCallingIdentity(token);
2337 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002338 }
2339
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002340 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002341 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002342 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002343 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002344 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002345 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002346 if (bestRoute.getGateway().equals(addr)) {
2347 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08002348 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002349 } else {
2350 // if we will connect to this through another route, add a direct route
2351 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08002352 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002353 }
2354 }
Lorenzo Colittice3a70b2015-09-04 13:12:42 +09002355 if (DBG) log("Adding legacy route " + bestRoute +
2356 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wangfd3fa0a2020-11-06 14:48:30 +08002357
2358 final String dst = bestRoute.getDestinationLinkAddress().toString();
2359 final String nextHop = bestRoute.hasGateway()
2360 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002361 try {
Chiachang Wangfd3fa0a2020-11-06 14:48:30 +08002362 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2363 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc05e2a92014-07-19 23:21:46 -07002364 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002365 return false;
2366 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002367 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002368 }
2369
paulhu0a2aa802021-01-08 00:51:49 +08002370 class DnsResolverUnsolicitedEventCallback extends
2371 IDnsResolverUnsolicitedEventListener.Stub {
dalykf4977492018-03-05 12:42:22 -05002372 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002373 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalykf4977492018-03-05 12:42:22 -05002374 try {
2375 mHandler.sendMessage(mHandler.obtainMessage(
2376 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu0a2aa802021-01-08 00:51:49 +08002377 new PrivateDnsValidationUpdate(event.netId,
2378 InetAddresses.parseNumericAddress(event.ipAddress),
2379 event.hostname, event.validation)));
dalykf4977492018-03-05 12:42:22 -05002380 } catch (IllegalArgumentException e) {
2381 loge("Error parsing ip address in validation event");
2382 }
2383 }
Chiachang Wangea46de72018-11-27 18:00:05 +08002384
2385 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002386 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2387 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wangea46de72018-11-27 18:00:05 +08002388 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2389 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2390 // event callback for certain nai. e.g. cellular. Register here to pass to
2391 // NetworkMonitor instead.
Remi NGUYEN VAN76b14fd2019-02-04 10:25:11 +09002392 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2393 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2394 // multiple NetworkMonitor registrants.
Chalard Jean1bc77a92021-02-04 13:12:59 +09002395 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu0a2aa802021-01-08 00:51:49 +08002396 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wangea46de72018-11-27 18:00:05 +08002397 }
2398 }
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09002399
2400 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002401 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2402 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2403 event.prefixAddress, event.prefixLength));
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09002404 }
dalykf4977492018-03-05 12:42:22 -05002405
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002406 @Override
paulhu0a2aa802021-01-08 00:51:49 +08002407 public int getInterfaceVersion() {
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002408 return this.VERSION;
2409 }
2410
2411 @Override
2412 public String getInterfaceHash() {
2413 return this.HASH;
2414 }
paulhu0a2aa802021-01-08 00:51:49 +08002415 }
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002416
2417 @VisibleForTesting
paulhu0a2aa802021-01-08 00:51:49 +08002418 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2419 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti7c761102021-01-07 17:16:24 +09002420
paulhu0a2aa802021-01-08 00:51:49 +08002421 private void registerDnsResolverUnsolicitedEventListener() {
dalykf4977492018-03-05 12:42:22 -05002422 try {
paulhu0a2aa802021-01-08 00:51:49 +08002423 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalykf4977492018-03-05 12:42:22 -05002424 } catch (Exception e) {
paulhu0a2aa802021-01-08 00:51:49 +08002425 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalykf4977492018-03-05 12:42:22 -05002426 }
2427 }
2428
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002429 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002430 @Override
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002431 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002432 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2433 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002434 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002435 };
2436
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002437 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002438 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti60104f52021-03-18 00:54:57 +09002439 setUidBlockedReasons(uid, blockedReasons);
junyulai5ab727b2018-08-07 19:50:45 +08002440 }
2441
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002442 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002443 for (String permission : permissions) {
2444 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002445 return true;
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002446 }
2447 }
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002448 return false;
2449 }
2450
paulhua9a6e2a2019-03-22 16:35:06 +08002451 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2452 for (String permission : permissions) {
2453 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2454 return true;
2455 }
2456 }
2457 return false;
2458 }
2459
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002460 private void enforceAnyPermissionOf(String... permissions) {
2461 if (!checkAnyPermissionOf(permissions)) {
2462 throw new SecurityException("Requires one of the following permissions: "
2463 + String.join(", ", permissions) + ".");
2464 }
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002465 }
2466
Paul Jensen57d231c2014-08-29 09:54:01 -04002467 private void enforceInternetPermission() {
2468 mContext.enforceCallingOrSelfPermission(
2469 android.Manifest.permission.INTERNET,
2470 "ConnectivityService");
2471 }
2472
The Android Open Source Project28527d22009-03-03 19:31:44 -08002473 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002474 mContext.enforceCallingOrSelfPermission(
2475 android.Manifest.permission.ACCESS_NETWORK_STATE,
2476 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002477 }
2478
paulhu4418c8e2021-02-22 15:40:43 +08002479 /**
2480 * Performs a strict and comprehensive check of whether a calling package is allowed to
2481 * change the state of network, as the condition differs for pre-M, M+, and
2482 * privileged/preinstalled apps. The caller is expected to have either the
2483 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2484 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2485 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2486 * permission and cannot be revoked. See http://b/23597341
2487 *
2488 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2489 * of this app will be updated to the current time.
2490 */
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07002491 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhu4418c8e2021-02-22 15:40:43 +08002492 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2493 == PackageManager.PERMISSION_GRANTED) {
2494 return;
2495 }
2496
2497 if (callingPkg == null) {
2498 throw new SecurityException("Calling package name is null.");
2499 }
2500
2501 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2502 final int uid = mDeps.getCallingUid();
2503 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2504 callingPkg, callingAttributionTag, null /* message */);
2505
2506 if (mode == AppOpsManager.MODE_ALLOWED) {
2507 return;
2508 }
2509
2510 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2511 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2512 return;
2513 }
2514
2515 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2516 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2517 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002518 }
2519
Charles He729f0b42017-05-15 17:07:18 +01002520 private void enforceSettingsPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002521 enforceAnyPermissionOf(
Charles He729f0b42017-05-15 17:07:18 +01002522 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002523 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He729f0b42017-05-15 17:07:18 +01002524 }
2525
paulhud70b7dd2019-08-12 16:25:11 +08002526 private void enforceNetworkFactoryPermission() {
paulhu44939832020-03-04 09:43:41 +08002527 enforceAnyPermissionOf(
paulhud70b7dd2019-08-12 16:25:11 +08002528 android.Manifest.permission.NETWORK_FACTORY,
paulhu44939832020-03-04 09:43:41 +08002529 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhud70b7dd2019-08-12 16:25:11 +08002530 }
2531
Aaron Huange5c0ba32020-04-14 13:43:49 +08002532 private void enforceNetworkFactoryOrSettingsPermission() {
2533 enforceAnyPermissionOf(
2534 android.Manifest.permission.NETWORK_SETTINGS,
2535 android.Manifest.permission.NETWORK_FACTORY,
2536 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2537 }
2538
2539 private void enforceNetworkFactoryOrTestNetworksPermission() {
2540 enforceAnyPermissionOf(
2541 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2542 android.Manifest.permission.NETWORK_FACTORY,
2543 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2544 }
2545
Chalard Jean88953062018-02-21 18:43:54 +09002546 private boolean checkSettingsPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002547 return checkAnyPermissionOf(
2548 android.Manifest.permission.NETWORK_SETTINGS,
2549 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean88953062018-02-21 18:43:54 +09002550 }
2551
2552 private boolean checkSettingsPermission(int pid, int uid) {
2553 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002554 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2555 || PERMISSION_GRANTED == mContext.checkPermission(
2556 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean88953062018-02-21 18:43:54 +09002557 }
2558
paulhud70b7dd2019-08-12 16:25:11 +08002559 private void enforceNetworkStackOrSettingsPermission() {
2560 enforceAnyPermissionOf(
2561 android.Manifest.permission.NETWORK_SETTINGS,
2562 android.Manifest.permission.NETWORK_STACK,
2563 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2564 }
2565
Lorenzo Colittic4d01862018-10-09 18:55:11 +09002566 private void enforceNetworkStackSettingsOrSetup() {
2567 enforceAnyPermissionOf(
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002568 android.Manifest.permission.NETWORK_SETTINGS,
2569 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov4753f402019-01-25 08:50:06 +00002570 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002571 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov4753f402019-01-25 08:50:06 +00002572 }
2573
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01002574 private void enforceAirplaneModePermission() {
2575 enforceAnyPermissionOf(
2576 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2577 android.Manifest.permission.NETWORK_SETTINGS,
2578 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2579 android.Manifest.permission.NETWORK_STACK,
2580 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2581 }
2582
James Mattis981865c2021-01-26 14:05:36 -08002583 private void enforceOemNetworkPreferencesPermission() {
2584 mContext.enforceCallingOrSelfPermission(
2585 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2586 "ConnectivityService");
2587 }
2588
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07002589 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN7bfa1c02019-01-31 16:42:12 +09002590 return checkAnyPermissionOf(
2591 android.Manifest.permission.NETWORK_STACK,
2592 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07002593 }
2594
Cody Kestingd292a332020-01-05 14:06:39 -08002595 private boolean checkNetworkStackPermission(int pid, int uid) {
2596 return checkAnyPermissionOf(pid, uid,
2597 android.Manifest.permission.NETWORK_STACK,
2598 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2599 }
2600
paulhua9a6e2a2019-03-22 16:35:06 +08002601 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2602 return checkAnyPermissionOf(pid, uid,
2603 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jeancbc7c5b2020-04-13 21:54:58 +09002604 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2605 android.Manifest.permission.NETWORK_SETTINGS);
paulhua9a6e2a2019-03-22 16:35:06 +08002606 }
2607
Hugo Benichic4899352016-07-19 15:59:27 +09002608 private void enforceConnectivityRestrictedNetworksPermission() {
2609 try {
2610 mContext.enforceCallingOrSelfPermission(
2611 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2612 "ConnectivityService");
2613 return;
2614 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhud70b7dd2019-08-12 16:25:11 +08002615 // TODO: Remove this fallback check after all apps have declared
2616 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2617 mContext.enforceCallingOrSelfPermission(
2618 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2619 "ConnectivityService");
Hugo Benichic4899352016-07-19 15:59:27 +09002620 }
2621
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002622 private void enforceKeepalivePermission() {
Lorenzo Colittib793d602015-09-08 13:21:48 +09002623 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002624 }
2625
Roshan Pius332e7a22021-03-21 17:55:29 +00002626 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2627 return PERMISSION_GRANTED == mContext.checkPermission(
2628 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2629 }
2630
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09002631 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002632 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002633 }
2634
2635 private void sendInetConditionBroadcast(NetworkInfo info) {
2636 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2637 }
2638
Wink Saville4f0de1e2011-08-04 15:01:58 -07002639 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002640 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002641 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002642 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002643 if (info.isFailover()) {
2644 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2645 info.setFailover(false);
2646 }
2647 if (info.getReason() != null) {
2648 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2649 }
2650 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002651 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2652 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002653 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002654 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002655 return intent;
2656 }
2657
2658 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2659 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2660 }
2661
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002662 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi47858762017-04-26 14:53:28 +09002663 synchronized (this) {
Chalard Jean9fbd93c2018-06-08 14:24:49 +09002664 if (!mSystemReady
2665 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002666 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002667 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002668 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09002669 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002670 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002671 }
2672
Dianne Hackborn6782e222015-12-09 17:22:26 -08002673 Bundle options = null;
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002674 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn2813a692014-12-04 17:46:42 -08002675 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte577c812015-09-01 08:23:04 -07002676 final NetworkInfo ni = intent.getParcelableExtra(
2677 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhud9ce33f2020-02-03 19:52:43 +08002678 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2679 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2680 options = opts.toBundle();
Chad Brubaker88a4e802018-03-08 10:37:09 -08002681 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn2813a692014-12-04 17:46:42 -08002682 }
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002683 try {
Paul Hu32fd2082021-01-26 02:53:06 +00002684 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002685 } finally {
2686 Binder.restoreCallingIdentity(ident);
2687 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002688 }
2689 }
2690
Remi NGUYEN VANebe52982019-06-20 18:29:36 +09002691 /**
Aaron Huang925d09b2020-06-27 07:18:23 +08002692 * Called by SystemServer through ConnectivityManager when the system is ready.
2693 */
2694 @Override
2695 public void systemReady() {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002696 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang925d09b2020-06-27 07:18:23 +08002697 throw new SecurityException("Calling Uid is not system uid.");
2698 }
2699 systemReadyInternal();
2700 }
2701
2702 /**
2703 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VANebe52982019-06-20 18:29:36 +09002704 */
2705 @VisibleForTesting
Aaron Huang925d09b2020-06-27 07:18:23 +08002706 public void systemReadyInternal() {
Aaron Huang5301b6f2020-12-08 10:03:29 +08002707 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2708 // listening network request which is sent by MultipathPolicyTracker won't be added
2709 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2710 // be called after PermissionMonitor#startMonitoring().
2711 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2712 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2713 // to ensure the tracking will be initialized correctly.
paulhubad55592019-11-19 17:55:31 +08002714 mPermissionMonitor.startMonitoring();
Chalard Jean7b09bbf2018-06-08 12:47:42 +09002715 mProxyTracker.loadGlobalProxy();
paulhu0a2aa802021-01-08 00:51:49 +08002716 registerDnsResolverUnsolicitedEventListener();
Wink Saville89c87b92013-08-29 08:55:16 -07002717
Hugo Benichi47858762017-04-26 14:53:28 +09002718 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002719 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002720 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002721 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002722 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002723 }
2724 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002725
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07002726 // Create network requests for always-on networks.
2727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
The Android Open Source Project28527d22009-03-03 19:31:44 -08002728 }
2729
The Android Open Source Project28527d22009-03-03 19:31:44 -08002730 /**
Chiachang Wangb4bba712020-12-15 15:56:00 +08002731 * Start listening for default data network activity state changes.
2732 */
2733 @Override
2734 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslina5e9bdb2021-01-21 02:04:15 +08002735 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wangb4bba712020-12-15 15:56:00 +08002736 }
2737
2738 /**
2739 * Stop listening for default data network activity state changes.
2740 */
2741 @Override
2742 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslina5e9bdb2021-01-21 02:04:15 +08002743 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wangb4bba712020-12-15 15:56:00 +08002744 }
2745
2746 /**
2747 * Check whether the default network radio is currently active.
2748 */
2749 @Override
2750 public boolean isDefaultNetworkActive() {
lucaslina5e9bdb2021-01-21 02:04:15 +08002751 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wangb4bba712020-12-15 15:56:00 +08002752 }
2753
2754 /**
Chalard Jean73d9db72018-06-04 16:52:49 +09002755 * Reads the network specific MTU size from resources.
sy.yun30043282013-09-02 05:24:09 +09002756 * and set it on it's iface.
2757 */
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002758 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2759 final String iface = newLp.getInterfaceName();
2760 final int mtu = newLp.getMtu();
Pierre Imai98f9c2c2016-02-08 16:01:40 +09002761 if (oldLp == null && mtu == 0) {
2762 // Silently ignore unset MTU value.
2763 return;
2764 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002765 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2766 if (VDBG) log("identical MTU - not setting");
2767 return;
2768 }
paulhu9bb04802019-03-08 16:35:20 +08002769 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09002770 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002771 return;
2772 }
sy.yun30043282013-09-02 05:24:09 +09002773
w19976c3455c32014-08-05 15:18:11 -07002774 // Cannot set MTU without interface name
2775 if (TextUtils.isEmpty(iface)) {
2776 loge("Setting MTU size with null iface.");
2777 return;
2778 }
2779
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002780 try {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09002781 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wangfd478312020-10-26 17:13:09 +08002782 mNetd.interfaceSetMtu(iface, mtu);
2783 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang11e9a312020-10-30 22:04:25 +08002784 loge("exception in interfaceSetMtu()" + e);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07002785 }
2786 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002787
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002788 @VisibleForTesting
2789 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensena871d062015-05-13 14:05:12 -04002790
lucaslin589964b2018-11-28 19:27:52 +08002791 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt03806862014-08-06 12:00:25 -07002792 String[] values = null;
2793 if (tcpBufferSizes != null) {
2794 values = tcpBufferSizes.split(",");
2795 }
2796
2797 if (values == null || values.length != 6) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07002798 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt03806862014-08-06 12:00:25 -07002799 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2800 values = tcpBufferSizes.split(",");
2801 }
2802
2803 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2804
2805 try {
Aaron Huang11e9a312020-10-30 22:04:25 +08002806 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt03806862014-08-06 12:00:25 -07002807
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002808 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2809 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2810 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt03806862014-08-06 12:00:25 -07002811 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng3d9b4902018-11-08 17:36:21 -08002812 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt03806862014-08-06 12:00:25 -07002813 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002814 }
2815 }
2816
Robert Greenwaltb59a91b2014-05-15 18:07:26 -07002817 @Override
2818 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti756a0222017-03-21 18:54:11 +09002819 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002820 NETWORK_RESTORE_DELAY_PROP_NAME);
2821 if(restoreDefaultNetworkDelayStr != null &&
2822 restoreDefaultNetworkDelayStr.length() != 0) {
2823 try {
Narayan Kamath846fa3e2016-04-15 18:32:45 +01002824 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002825 } catch (NumberFormatException e) {
2826 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002827 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002828 // if the system property isn't set, use the value for the apn type
2829 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2830
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09002831 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2832 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002833 }
2834 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002835 }
2836
Lorenzo Colittidad88972016-03-03 17:53:46 +09002837 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2838 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2839 final long DIAG_TIME_MS = 5000;
Hugo Benichi821785c2018-09-03 08:19:02 +09002840 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yud0e42212019-07-05 11:51:34 +08002841 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colittidad88972016-03-03 17:53:46 +09002842 // Start gathering diagnostic information.
2843 netDiags.add(new NetworkDiagnostics(
2844 nai.network,
2845 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yud0e42212019-07-05 11:51:34 +08002846 privateDnsCfg,
Lorenzo Colittidad88972016-03-03 17:53:46 +09002847 DIAG_TIME_MS));
2848 }
2849
2850 for (NetworkDiagnostics netDiag : netDiags) {
2851 pw.println();
2852 netDiag.waitForMeasurements();
2853 netDiag.dump(pw);
2854 }
2855 }
2856
The Android Open Source Project28527d22009-03-03 19:31:44 -08002857 @Override
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09002858 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2859 @Nullable String[] args) {
Chiachang Wang70348a22021-04-19 10:59:24 +08002860 if (!checkDumpPermission(mContext, TAG, writer)) return;
2861
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08002862 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair9154a422017-10-26 10:08:50 -07002863 }
2864
lucaslin9d4b8642020-12-10 15:10:54 +08002865 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2866 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2867 != PackageManager.PERMISSION_GRANTED) {
2868 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09002869 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin9d4b8642020-12-10 15:10:54 +08002870 + " due to missing android.permission.DUMP permission");
2871 return false;
2872 } else {
2873 return true;
2874 }
2875 }
2876
Chiachang Wang9ddf7d32021-03-09 14:55:31 +08002877 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002878 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002879
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002880 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colittidad88972016-03-03 17:53:46 +09002881 dumpNetworkDiagnostics(pw);
2882 return;
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002883 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichif93f4482018-09-03 08:32:56 +09002884 dumpNetworks(pw);
2885 return;
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002886 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichif93f4482018-09-03 08:32:56 +09002887 dumpNetworkRequests(pw);
2888 return;
Lorenzo Colittidad88972016-03-03 17:53:46 +09002889 }
Erik Kline445cad12015-06-05 17:47:34 +09002890
Lorenzo Colitti94c93142020-01-10 00:40:28 +09002891 pw.print("NetworkProviders for:");
2892 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2893 pw.print(" " + npi.name);
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07002894 }
Lorenzo Colitti417c25c2015-06-03 11:18:24 +09002895 pw.println();
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07002896 pw.println();
2897
Chalard Jean1bc77a92021-02-04 13:12:59 +09002898 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalt31a40522014-05-13 15:36:27 -07002899 pw.print("Active default network: ");
Chalard Jean1bc77a92021-02-04 13:12:59 +09002900 if (defaultNai == null) {
Robert Greenwalt31a40522014-05-13 15:36:27 -07002901 pw.println("none");
2902 } else {
Chalard Jean1bc77a92021-02-04 13:12:59 +09002903 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002904 }
Dianne Hackbornb4b09e82014-02-26 16:20:52 -08002905 pw.println();
2906
James Mattis6e6fabf2021-01-10 14:24:24 -08002907 pw.print("Current per-app default networks: ");
2908 pw.increaseIndent();
2909 dumpPerAppNetworkPreferences(pw);
2910 pw.decreaseIndent();
2911 pw.println();
2912
Robert Greenwalt31a40522014-05-13 15:36:27 -07002913 pw.println("Current Networks:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002914 pw.increaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002915 dumpNetworks(pw);
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002916 pw.decreaseIndent();
Robert Greenwalt31a40522014-05-13 15:36:27 -07002917 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002918
junyulai5ab727b2018-08-07 19:50:45 +08002919 pw.println("Status for known UIDs:");
2920 pw.increaseIndent();
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002921 final int size = mUidBlockedReasons.size();
junyulai5ab727b2018-08-07 19:50:45 +08002922 for (int i = 0; i < size; i++) {
2923 // Don't crash if the array is modified while dumping in bugreports.
2924 try {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00002925 final int uid = mUidBlockedReasons.keyAt(i);
2926 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2927 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankab9c396e2021-04-21 07:23:54 +00002928 + Integer.toHexString(blockedReasons));
junyulai5ab727b2018-08-07 19:50:45 +08002929 } catch (ArrayIndexOutOfBoundsException e) {
2930 pw.println(" ArrayIndexOutOfBoundsException");
2931 } catch (ConcurrentModificationException e) {
2932 pw.println(" ConcurrentModificationException");
2933 }
2934 }
2935 pw.println();
2936 pw.decreaseIndent();
2937
Robert Greenwalt31a40522014-05-13 15:36:27 -07002938 pw.println("Network Requests:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002939 pw.increaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002940 dumpNetworkRequests(pw);
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002941 pw.decreaseIndent();
Hugo Benichif93f4482018-09-03 08:32:56 +09002942 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002943
Robert Greenwaltdbd5f312014-07-30 16:31:24 -07002944 mLegacyTypeTracker.dump(pw);
Robert Greenwaltdbd5f312014-07-30 16:31:24 -07002945
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002946 pw.println();
markchien497a0622019-09-30 14:40:57 +08002947 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002948
Lorenzo Colittid1039d12015-06-15 14:29:22 +09002949 pw.println();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09002950 dumpAvoidBadWifiSettings(pw);
Lorenzo Colittidad88972016-03-03 17:53:46 +09002951
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09002952 pw.println();
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09002953
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09002954 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt2784ed62015-06-23 15:03:33 -07002955 pw.println();
Erik Kline47401fa2015-07-09 18:24:03 +09002956 pw.println("mNetworkRequestInfoLogs (most recent first):");
2957 pw.increaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002958 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Kline47401fa2015-07-09 18:24:03 +09002959 pw.decreaseIndent();
Hugo Benichi7b3bf372016-07-11 11:05:12 +09002960
2961 pw.println();
2962 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2963 pw.increaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002964 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichi7b3bf372016-07-11 11:05:12 +09002965 pw.decreaseIndent();
Hugo Benichi23ec1c92017-03-30 10:46:05 +09002966
2967 pw.println();
2968 pw.println("NetTransition WakeLock activity (most recent first):");
2969 pw.increaseIndent();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09002970 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2971 pw.println("total releases: " + mTotalWakelockReleases);
2972 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2973 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2974 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2975 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2976 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2977 }
James Mattis6e4405f2021-04-06 17:07:42 -07002978 mWakelockLogs.reverseDump(pw);
Nathan Harold6179b142018-07-30 13:38:01 -07002979
2980 pw.println();
2981 pw.println("bandwidth update requests (by uid):");
2982 pw.increaseIndent();
2983 synchronized (mBandwidthRequests) {
2984 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2985 pw.println("[" + mBandwidthRequests.keyAt(i)
2986 + "]: " + mBandwidthRequests.valueAt(i));
2987 }
2988 }
2989 pw.decreaseIndent();
James Mattis6e4405f2021-04-06 17:07:42 -07002990 pw.decreaseIndent();
Nathan Harold6179b142018-07-30 13:38:01 -07002991
James Mattis6e4405f2021-04-06 17:07:42 -07002992 pw.println();
2993 pw.println("mOemNetworkPreferencesLogs (most recent first):");
2994 pw.increaseIndent();
2995 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi23ec1c92017-03-30 10:46:05 +09002996 pw.decreaseIndent();
Robert Greenwalt2784ed62015-06-23 15:03:33 -07002997 }
Remi NGUYEN VANa00a3f22019-02-18 11:20:28 +09002998
2999 pw.println();
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00003000
3001 pw.println();
3002 pw.println("Permission Monitor:");
3003 pw.increaseIndent();
3004 mPermissionMonitor.dump(pw);
3005 pw.decreaseIndent();
lucaslin3756fcc2021-01-21 02:04:35 +08003006
3007 pw.println();
3008 pw.println("Legacy network activity:");
3009 pw.increaseIndent();
3010 mNetworkActivityTracker.dump(pw);
3011 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003012 }
3013
Hugo Benichif93f4482018-09-03 08:32:56 +09003014 private void dumpNetworks(IndentingPrintWriter pw) {
3015 for (NetworkAgentInfo nai : networksSortedById()) {
3016 pw.println(nai.toString());
3017 pw.increaseIndent();
3018 pw.println(String.format(
3019 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3020 nai.numForegroundNetworkRequests(),
3021 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3022 nai.numBackgroundNetworkRequests(),
3023 nai.numNetworkRequests()));
3024 pw.increaseIndent();
3025 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3026 pw.println(nai.requestAt(i).toString());
3027 }
3028 pw.decreaseIndent();
junyulai2a4f0062021-02-03 20:15:30 +08003029 pw.println("Inactivity Timers:");
Hugo Benichif93f4482018-09-03 08:32:56 +09003030 pw.increaseIndent();
junyulai2a4f0062021-02-03 20:15:30 +08003031 nai.dumpInactivityTimers(pw);
Hugo Benichif93f4482018-09-03 08:32:56 +09003032 pw.decreaseIndent();
3033 pw.decreaseIndent();
3034 }
3035 }
3036
James Mattis6e6fabf2021-01-10 14:24:24 -08003037 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3038 pw.println("Per-App Network Preference:");
3039 pw.increaseIndent();
3040 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3041 pw.println("none");
3042 } else {
3043 pw.println(mOemNetworkPreferences.toString());
3044 }
3045 pw.decreaseIndent();
3046
3047 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3048 if (mDefaultRequest == defaultRequest) {
3049 continue;
3050 }
3051
3052 final boolean isActive = null != defaultRequest.getSatisfier();
3053 pw.println("Is per-app network active:");
3054 pw.increaseIndent();
3055 pw.println(isActive);
3056 if (isActive) {
3057 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3058 }
3059 pw.println("Tracked UIDs:");
3060 pw.increaseIndent();
3061 if (0 == defaultRequest.mRequests.size()) {
3062 pw.println("none, this should never occur.");
3063 } else {
Chiachang Wangd5034c72021-02-22 18:36:38 +08003064 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
James Mattis6e6fabf2021-01-10 14:24:24 -08003065 }
3066 pw.decreaseIndent();
3067 pw.decreaseIndent();
3068 }
3069 }
3070
Hugo Benichif93f4482018-09-03 08:32:56 +09003071 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3072 for (NetworkRequestInfo nri : requestsSortedById()) {
3073 pw.println(nri.toString());
3074 }
3075 }
3076
Hugo Benichi821785c2018-09-03 08:19:02 +09003077 /**
3078 * Return an array of all current NetworkAgentInfos sorted by network id.
3079 */
3080 private NetworkAgentInfo[] networksSortedById() {
3081 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003082 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayev284cb872020-12-07 22:43:07 -08003083 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichi821785c2018-09-03 08:19:02 +09003084 return networks;
3085 }
3086
3087 /**
3088 * Return an array of all current NetworkRequest sorted by request id.
3089 */
James Mattisf8eb49a2020-11-15 15:04:40 -08003090 @VisibleForTesting
James Mattisc449dde2020-11-20 16:08:10 -08003091 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichi821785c2018-09-03 08:19:02 +09003092 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattis622428c2020-12-02 14:12:41 -08003093 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattisf8eb49a2020-11-15 15:04:40 -08003094 // Sort the array based off the NRI containing the min requestId in its requests.
3095 Arrays.sort(requests,
3096 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3097 Comparator.comparingInt(req -> req.requestId)).requestId
3098 )
3099 );
Hugo Benichi821785c2018-09-03 08:19:02 +09003100 return requests;
3101 }
3102
Lorenzo Colittif0461852016-04-05 17:52:16 +09003103 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran44e21e42014-11-12 22:31:52 -08003104 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwaltcf971852014-08-19 18:58:04 -07003105 if (officialNai != null && officialNai.equals(nai)) return true;
3106 if (officialNai != null || VDBG) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09003107 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwaltcf971852014-08-19 18:58:04 -07003108 " - " + nai);
3109 }
3110 return false;
3111 }
3112
Robert Greenwalt2034b912009-08-12 16:08:25 -07003113 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003114 private class NetworkStateTrackerHandler extends Handler {
3115 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003116 super(looper);
3117 }
3118
Lorenzo Colittif0461852016-04-05 17:52:16 +09003119 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003120 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3121 final NetworkAgentInfo nai = arg.first;
3122 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittif0461852016-04-05 17:52:16 +09003123 if (VDBG) {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09003124 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittif0461852016-04-05 17:52:16 +09003125 }
3126 return;
3127 }
3128
3129 switch (msg.what) {
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003130 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003131 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin25a50472019-03-12 13:08:03 +08003132 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang11e9a312020-10-30 22:04:25 +08003133 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt948aea52014-04-11 15:53:27 -07003134 }
Chalard Jeanb5b172f2020-03-09 21:25:37 +09003135 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3136 // Make sure the original object is not mutated. NetworkAgent normally
3137 // makes a copy of the capabilities when sending the message through
3138 // the Messenger, but if this ever changes, not making a defensive copy
3139 // here will give attack vectors to clients using this code path.
3140 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Cody Kestingba343362020-04-07 16:07:33 -07003141 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
Chalard Jeanb5b172f2020-03-09 21:25:37 +09003142 }
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003143 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichi810f4912016-09-15 18:18:48 +09003144 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt948aea52014-04-11 15:53:27 -07003145 break;
3146 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003147 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003148 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09003149 processLinkPropertiesFromAgent(nai, newLp);
3150 handleUpdateLinkProperties(nai, newLp);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003151 break;
3152 }
3153 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003154 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003155 updateNetworkInfo(nai, info);
3156 break;
3157 }
Robert Greenwaltcf82b832014-05-27 13:20:24 -07003158 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jeandd753522020-12-21 18:36:52 +09003159 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwaltcf82b832014-05-27 13:20:24 -07003160 break;
3161 }
Robert Greenwaltcea86b02014-09-07 16:50:01 -07003162 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colitti72792e22019-06-04 14:37:26 +09003163 if (nai.everConnected) {
3164 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jean67b66082021-01-20 20:47:32 +09003165 // Note that if the NAI had been connected, this would affect the
3166 // score, and therefore would require re-mixing the score and performing
3167 // a rematch.
Paul Jensend4e077c2014-09-26 10:10:22 -04003168 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003169 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3170 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin25a50472019-03-12 13:08:03 +08003171 // Mark the network as temporarily accepting partial connectivity so that it
3172 // will be validated (and possibly become default) even if it only provides
3173 // partial internet access. Note that if user connects to partial connectivity
3174 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3175 // out of wifi coverage) and if the same wifi is available again, the device
3176 // will auto connect to this wifi even though the wifi has "no internet".
3177 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colitticf595362020-01-12 22:28:37 +09003178 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwaltcea86b02014-09-07 16:50:01 -07003179 break;
3180 }
junyulai21c06d02019-01-03 18:50:15 +08003181 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003182 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colittid1039d12015-06-15 14:29:22 +09003183 break;
3184 }
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003185 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09003186 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003187 if (!nai.supportsUnderlyingNetworks()) {
3188 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3189 break;
3190 }
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09003191
Remi NGUYEN VANd793eb32020-12-25 12:45:46 +09003192 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09003193
3194 if (isLegacyLockdownNai(nai)
3195 && (underlying == null || underlying.size() != 1)) {
3196 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3197 + " must have exactly one underlying network: " + underlying);
3198 }
3199
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003200 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3201 nai.declaredUnderlyingNetworks = (underlying != null)
3202 ? underlying.toArray(new Network[0]) : null;
3203
3204 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3205 if (DBG) {
3206 log(nai.toShortString() + " changed underlying networks to "
3207 + Arrays.toString(nai.declaredUnderlyingNetworks));
3208 }
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003209 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003210 notifyIfacesChangedForNetworkStats();
3211 }
Daniel Bright60f02ed2020-06-15 16:10:01 -07003212 break;
Lorenzo Colitti220987b2020-11-09 10:32:56 +09003213 }
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003214 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3215 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3216 nai.teardownDelayMs = msg.arg1;
3217 } else {
3218 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3219 }
Chalard Jeane634b282021-03-05 23:07:53 +09003220 break;
3221 }
3222 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3223 nai.setLingerDuration((int) arg.second);
3224 break;
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003225 }
Lorenzo Colittif0461852016-04-05 17:52:16 +09003226 }
3227 }
3228
3229 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3230 switch (msg.what) {
3231 default:
3232 return false;
lucaslin8cf57f52019-10-22 18:27:33 +08003233 case EVENT_PROBE_STATUS_CHANGED: {
3234 final Integer netId = (Integer) msg.obj;
3235 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3236 if (nai == null) {
3237 break;
3238 }
3239 final boolean probePrivateDnsCompleted =
3240 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3241 final boolean privateDnsBroken =
3242 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3243 if (probePrivateDnsCompleted) {
3244 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3245 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003246 updateCapabilitiesForNetwork(nai);
lucaslin8cf57f52019-10-22 18:27:33 +08003247 }
3248 // Only show the notification when the private DNS is broken and the
3249 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colitticf595362020-01-12 22:28:37 +09003250 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucaslin8cf57f52019-10-22 18:27:33 +08003251 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3252 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003253 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucaslin8cf57f52019-10-22 18:27:33 +08003254 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3255 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3256 // private DNS is broken, it means this network is being reevaluated.
3257 // Either probing private DNS is not necessary any more or it hasn't been
3258 // done yet. In either case, the networkCapabilities should be updated to
3259 // reflect the new status.
3260 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003261 updateCapabilitiesForNetwork(nai);
Lorenzo Colitticf595362020-01-12 22:28:37 +09003262 nai.networkAgentConfig.hasShownBroken = false;
lucaslin8cf57f52019-10-22 18:27:33 +08003263 }
3264 break;
3265 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003266 case EVENT_NETWORK_TESTED: {
Cody Kestingd292a332020-01-05 14:06:39 -08003267 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3268
3269 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Klinec06d4f92018-01-11 21:07:29 +09003270 if (nai == null) break;
3271
Cody Kestingd292a332020-01-05 14:06:39 -08003272 handleNetworkTested(nai, results.mTestResult,
3273 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003274 break;
3275 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003276 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09003277 final int netId = msg.arg2;
Hugo Benichi7f919fe2017-04-21 15:07:12 +09003278 final boolean visible = toBool(msg.arg1);
Erik Kline076bd3d2018-03-21 07:18:33 -07003279 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin On3fd101e2016-10-11 15:10:46 -07003280 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen783c0e02015-06-16 14:27:36 -04003281 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3282 nai.lastCaptivePortalDetected = visible;
3283 nai.everCaptivePortalDetected |= visible;
Calvin On3fd101e2016-10-11 15:10:46 -07003284 if (nai.lastCaptivePortalDetected &&
paulhu79260c22021-03-17 20:30:33 +08003285 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3286 == getCaptivePortalMode()) {
Chalard Jean373391b2019-12-10 21:07:02 +09003287 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003288 nai.onPreventAutomaticReconnect();
Calvin On3fd101e2016-10-11 15:10:46 -07003289 teardownUnneededNetwork(nai);
3290 break;
3291 }
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003292 updateCapabilitiesForNetwork(nai);
Paul Jensen783c0e02015-06-16 14:27:36 -04003293 }
3294 if (!visible) {
lucaslin1ac72392019-01-24 15:55:30 +08003295 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin25a50472019-03-12 13:08:03 +08003296 // notifications belong to the same network may be cleared unexpectedly.
lucaslin1ac72392019-01-24 15:55:30 +08003297 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3298 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen8ba5ffb2014-07-15 12:07:36 -04003299 } else {
Paul Jensenc3deb112014-08-25 22:45:39 -04003300 if (nai == null) {
3301 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3302 break;
3303 }
Lorenzo Colitticf595362020-01-12 22:28:37 +09003304 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittib268f9f2016-08-22 16:46:40 +09003305 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitticf595362020-01-12 22:28:37 +09003306 (PendingIntent) msg.obj,
3307 nai.networkAgentConfig.explicitlySelected);
fionaxu5447c492016-05-23 16:33:16 -07003308 }
Paul Jensen77cbca52014-05-15 10:33:05 -04003309 }
Paul Jensen77cbca52014-05-15 10:33:05 -04003310 break;
3311 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003312 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline076bd3d2018-03-21 07:18:33 -07003313 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinec06d4f92018-01-11 21:07:29 +09003314 if (nai == null) break;
3315
Erik Kline076bd3d2018-03-21 07:18:33 -07003316 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinec06d4f92018-01-11 21:07:29 +09003317 break;
3318 }
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003319 case EVENT_CAPPORT_DATA_CHANGED: {
3320 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3321 if (nai == null) break;
Hai Shalom492febb2021-01-11 18:45:34 -08003322 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003323 break;
3324 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003325 }
Lorenzo Colittif0461852016-04-05 17:52:16 +09003326 return true;
3327 }
3328
Cody Kestingd292a332020-01-05 14:06:39 -08003329 private void handleNetworkTested(
3330 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3331 final boolean wasPartial = nai.partialConnectivity;
3332 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3333 final boolean partialConnectivityChanged =
3334 (wasPartial != nai.partialConnectivity);
3335
3336 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3337 final boolean wasValidated = nai.lastValidated;
Chalard Jean1bc77a92021-02-04 13:12:59 +09003338 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kestingd292a332020-01-05 14:06:39 -08003339
3340 if (DBG) {
3341 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3342 ? " with redirect to " + redirectUrl
3343 : "";
Chalard Jean373391b2019-12-10 21:07:02 +09003344 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kestingd292a332020-01-05 14:06:39 -08003345 }
3346 if (valid != nai.lastValidated) {
Cody Kestingd292a332020-01-05 14:06:39 -08003347 final int oldScore = nai.getCurrentScore();
3348 nai.lastValidated = valid;
3349 nai.everValidated |= valid;
3350 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kestingd292a332020-01-05 14:06:39 -08003351 if (valid) {
3352 handleFreshlyValidatedNetwork(nai);
3353 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3354 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayev284cb872020-12-07 22:43:07 -08003355 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003356 NotificationType.NO_INTERNET);
Serik Beketayev284cb872020-12-07 22:43:07 -08003357 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003358 NotificationType.LOST_INTERNET);
Serik Beketayev284cb872020-12-07 22:43:07 -08003359 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003360 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayev284cb872020-12-07 22:43:07 -08003361 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kestingd292a332020-01-05 14:06:39 -08003362 NotificationType.PRIVATE_DNS_BROKEN);
3363 // If network becomes valid, the hasShownBroken should be reset for
3364 // that network so that the notification will be fired when the private
3365 // DNS is broken again.
3366 nai.networkAgentConfig.hasShownBroken = false;
3367 }
3368 } else if (partialConnectivityChanged) {
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09003369 updateCapabilitiesForNetwork(nai);
Cody Kestingd292a332020-01-05 14:06:39 -08003370 }
3371 updateInetCondition(nai);
3372 // Let the NetworkAgent know the state of its network
Cody Kestingd292a332020-01-05 14:06:39 -08003373 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003374 nai.onValidationStatusChanged(
3375 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3376 redirectUrl);
Cody Kestingd292a332020-01-05 14:06:39 -08003377
3378 // If NetworkMonitor detects partial connectivity before
3379 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3380 // immediately. Re-notify partial connectivity silently if no internet
3381 // notification already there.
3382 if (!wasPartial && nai.partialConnectivity) {
3383 // Remove delayed message if there is a pending message.
3384 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3385 handlePromptUnvalidated(nai.network);
3386 }
3387
3388 if (wasValidated && !nai.lastValidated) {
3389 handleNetworkUnvalidated(nai);
3390 }
3391 }
3392
Calvin On3fd101e2016-10-11 15:10:46 -07003393 private int getCaptivePortalMode() {
3394 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08003395 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3396 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin On3fd101e2016-10-11 15:10:46 -07003397 }
3398
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003399 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3400 switch (msg.what) {
3401 default:
3402 return false;
3403 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3404 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3405 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3406 handleLingerComplete(nai);
3407 }
3408 break;
3409 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003410 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3411 handleNetworkAgentRegistered(msg);
3412 break;
3413 }
3414 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3415 handleNetworkAgentDisconnected(msg);
3416 break;
3417 }
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003418 }
3419 return true;
3420 }
3421
Lorenzo Colittif0461852016-04-05 17:52:16 +09003422 @Override
3423 public void handleMessage(Message msg) {
lifr1c0d9b22021-03-10 13:58:14 +08003424 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN8156bbe2020-01-14 19:48:18 +09003425 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittif0461852016-04-05 17:52:16 +09003426 maybeHandleNetworkAgentMessage(msg);
3427 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003428 }
3429 }
3430
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003431 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean15347192019-05-30 14:58:29 +09003432 private final int mNetId;
3433 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003434
3435 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayev284cb872020-12-07 22:43:07 -08003436 mNetId = nai.network.getNetId();
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09003437 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003438 }
3439
3440 @Override
3441 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3442 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean15347192019-05-30 14:58:29 +09003443 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003444 }
3445
3446 @Override
3447 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003448 // Legacy version of notifyNetworkTestedWithExtras.
3449 // Would only be called if the system has a NetworkStack module older than the
3450 // framework, which does not happen in practice.
Aaron Huang11e9a312020-10-30 22:04:25 +08003451 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kestingd292a332020-01-05 14:06:39 -08003452 }
3453
3454 @Override
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003455 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VANfb0774e2020-04-24 20:56:39 +09003456 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3457 // the same looper so messages will be processed in sequence.
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003458 final Message msg = mTrackerHandler.obtainMessage(
3459 EVENT_NETWORK_TESTED,
3460 new NetworkTestedResults(
3461 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kestingd292a332020-01-05 14:06:39 -08003462 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003463
3464 // Invoke ConnectivityReport generation for this Network test event.
3465 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3466 if (nai == null) return;
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003467
3468 final PersistableBundle extras = new PersistableBundle();
3469 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3470 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3471 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3472
Aaron Huang0d1be642021-01-21 15:47:41 +08003473 ConnectivityReportEvent reportEvent =
3474 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3475 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3476 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003477 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003478 }
3479
3480 @Override
3481 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3482 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3483 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean15347192019-05-30 14:58:29 +09003484 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003485 }
3486
3487 @Override
lucaslin8cf57f52019-10-22 18:27:33 +08003488 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3489 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3490 EVENT_PROBE_STATUS_CHANGED,
3491 probesCompleted, probesSucceeded, new Integer(mNetId)));
3492 }
3493
3494 @Override
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003495 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3496 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3497 EVENT_CAPPORT_DATA_CHANGED,
3498 0, mNetId, data));
3499 }
3500
3501 @Override
Remi NGUYEN VAN8b3999c2019-02-07 21:29:57 +09003502 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003503 final Intent intent = new Intent(action);
Remi NGUYEN VAN8b3999c2019-02-07 21:29:57 +09003504 intent.setPackage(packageName);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003505
3506 final PendingIntent pendingIntent;
3507 // Only the system server can register notifications with package "android"
3508 final long token = Binder.clearCallingIdentity();
3509 try {
paulhu68426192020-06-09 19:07:03 +08003510 pendingIntent = PendingIntent.getBroadcast(
3511 mContext,
3512 0 /* requestCode */,
3513 intent,
3514 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003515 } finally {
3516 Binder.restoreCallingIdentity(token);
3517 }
3518 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3519 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean15347192019-05-30 14:58:29 +09003520 mNetId, pendingIntent));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003521 }
3522
3523 @Override
3524 public void hideProvisioningNotification() {
3525 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean15347192019-05-30 14:58:29 +09003526 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003527 }
Remi NGUYEN VANe72fe2b2019-04-05 15:15:48 +09003528
3529 @Override
Remi NGUYEN VANe15e61e2020-04-15 18:39:28 +09003530 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kesting6784cf62020-05-11 10:06:51 -07003531 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kesting1d326382020-01-06 16:55:35 -08003532 }
3533
3534 @Override
Remi NGUYEN VANe72fe2b2019-04-05 15:15:48 +09003535 public int getInterfaceVersion() {
3536 return this.VERSION;
3537 }
Paul Trautrim69929da2020-01-23 14:55:57 +09003538
3539 @Override
3540 public String getInterfaceHash() {
3541 return this.HASH;
3542 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003543 }
3544
Cody Kesting6784cf62020-05-11 10:06:51 -07003545 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kesting43a47ef2020-05-15 10:36:01 -07003546 log("Data stall detected with methods: " + p.detectionMethod);
3547
Cody Kesting6784cf62020-05-11 10:06:51 -07003548 final PersistableBundle extras = new PersistableBundle();
Cody Kesting43a47ef2020-05-15 10:36:01 -07003549 int detectionMethod = 0;
3550 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3551 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3552 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3553 }
3554 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3555 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3556 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3557 p.tcpMetricsCollectionPeriodMillis);
3558 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kesting6784cf62020-05-11 10:06:51 -07003559 }
3560
Cody Kestingb5c7abd2020-04-15 12:33:28 -07003561 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kesting6784cf62020-05-11 10:06:51 -07003562 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang0d1be642021-01-21 15:47:41 +08003563 new Pair<>(p.timestampMillis, extras));
Cody Kestingb5c7abd2020-04-15 12:33:28 -07003564
3565 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3566 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3567 // the cost of going through two handlers.
3568 mConnectivityDiagnosticsHandler.sendMessage(msg);
3569 }
3570
Cody Kesting43a47ef2020-05-15 10:36:01 -07003571 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3572 return (p.detectionMethod & detectionMethod) != 0;
3573 }
3574
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003575 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3576 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline076bd3d2018-03-21 07:18:33 -07003577 }
3578
Erik Klinee6d899a2018-06-26 18:53:43 +09003579 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3580 if (nai == null) return;
3581 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3582 // in order to restart a validation pass from within netd.
3583 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3584 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayev284cb872020-12-07 22:43:07 -08003585 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinee6d899a2018-06-26 18:53:43 +09003586 }
3587 }
3588
Erik Klinec06d4f92018-01-11 21:07:29 +09003589 private void handlePrivateDnsSettingsChanged() {
3590 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3591
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003592 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline076bd3d2018-03-21 07:18:33 -07003593 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003594 if (networkRequiresPrivateDnsValidation(nai)) {
dalykf4977492018-03-05 12:42:22 -05003595 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3596 }
Erik Klinec06d4f92018-01-11 21:07:29 +09003597 }
3598 }
3599
Erik Kline076bd3d2018-03-21 07:18:33 -07003600 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3601 // Private DNS only ever applies to networks that might provide
3602 // Internet access and therefore also require validation.
Lorenzo Colittiac456b22019-03-22 00:28:28 +09003603 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Klinec06d4f92018-01-11 21:07:29 +09003604
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09003605 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline076bd3d2018-03-21 07:18:33 -07003606 // schedule DNS resolutions. If a DNS resolution is required the
3607 // result will be sent back to us.
Lorenzo Colitti260d9982019-05-31 15:41:29 +09003608 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline076bd3d2018-03-21 07:18:33 -07003609
3610 // With Private DNS bypass support, we can proceed to update the
3611 // Private DNS config immediately, even if we're in strict mode
3612 // and have not yet resolved the provider name into a set of IPs.
3613 updatePrivateDns(nai, cfg);
3614 }
3615
3616 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3617 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayev284cb872020-12-07 22:43:07 -08003618 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinec06d4f92018-01-11 21:07:29 +09003619 }
3620
dalykf4977492018-03-05 12:42:22 -05003621 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3622 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3623 if (nai == null) {
3624 return;
3625 }
3626 mDnsManager.updatePrivateDnsValidation(update);
3627 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3628 }
3629
paulhu0a2aa802021-01-08 00:51:49 +08003630 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003631 int prefixLength) {
3632 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3633 if (nai == null) return;
3634
paulhu0a2aa802021-01-08 00:51:49 +08003635 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3636 netId, operation, prefixAddress, prefixLength));
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003637
3638 IpPrefix prefix = null;
paulhu0a2aa802021-01-08 00:51:49 +08003639 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003640 try {
paulhu0a2aa802021-01-08 00:51:49 +08003641 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003642 prefixLength);
3643 } catch (IllegalArgumentException e) {
paulhu0a2aa802021-01-08 00:51:49 +08003644 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003645 return;
3646 }
3647 }
3648
Lorenzo Colittifff75392020-04-01 20:16:30 +09003649 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colitti8d39bbf2019-01-08 10:04:25 +09003650 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3651 }
3652
Hai Shalom492febb2021-01-11 18:45:34 -08003653 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003654 @Nullable final CaptivePortalData data) {
Hai Shalom492febb2021-01-11 18:45:34 -08003655 nai.capportApiData = data;
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09003656 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3657 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3658 }
3659
Chalard Jeand915e362019-12-04 18:49:18 +09003660 /**
junyulai2a4f0062021-02-03 20:15:30 +08003661 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jeand915e362019-12-04 18:49:18 +09003662 * @param nai the agent info to update
3663 * @param now the timestamp of the event causing this update
junyulai2a4f0062021-02-03 20:15:30 +08003664 * @return whether the network was inactive as a result of this update
Chalard Jeand915e362019-12-04 18:49:18 +09003665 */
junyulai2a4f0062021-02-03 20:15:30 +08003666 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3667 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3668 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003669 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2a4f0062021-02-03 20:15:30 +08003670 // one lingered request, set inactive.
3671 nai.updateInactivityTimer();
junyulaif6d98ec2020-12-14 18:41:52 +08003672 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2a4f0062021-02-03 20:15:30 +08003673 if (DBG) log("Unsetting inactive " + nai.toShortString());
3674 nai.unsetInactive();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003675 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2a4f0062021-02-03 20:15:30 +08003676 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jeand915e362019-12-04 18:49:18 +09003677 if (DBG) {
junyulai2a4f0062021-02-03 20:15:30 +08003678 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3679 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jeand915e362019-12-04 18:49:18 +09003680 }
junyulai2a4f0062021-02-03 20:15:30 +08003681 nai.setInactive();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003682 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jeand915e362019-12-04 18:49:18 +09003683 return true;
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09003684 }
Chalard Jeand915e362019-12-04 18:49:18 +09003685 return false;
Paul Jensen935ceef2014-11-25 15:26:53 -05003686 }
3687
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003688 private void handleNetworkAgentRegistered(Message msg) {
3689 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3690 if (!mNetworkAgentInfos.contains(nai)) {
3691 return;
3692 }
3693
3694 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3695 if (VDBG) log("NetworkAgent registered");
3696 } else {
3697 loge("Error connecting NetworkAgent");
3698 mNetworkAgentInfos.remove(nai);
3699 if (nai != null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09003700 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003701 synchronized (mNetworkForNetId) {
3702 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003703 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003704 mNetIdManager.releaseNetId(nai.network.getNetId());
3705 // Just in case.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003706 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07003707 }
3708 }
3709 }
Paul Jensen935ceef2014-11-25 15:26:53 -05003710
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003711 private void handleNetworkAgentDisconnected(Message msg) {
3712 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3713 if (mNetworkAgentInfos.contains(nai)) {
3714 disconnectAndDestroyNetwork(nai);
3715 }
3716 }
3717
Chalard Jeanefaf6532018-05-11 20:19:20 +09003718 // Destroys a network, remove references to it from the internal state managed by
3719 // ConnectivityService, free its interfaces and clean up.
3720 // Must be called on the Handler thread.
3721 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean4deee632019-11-05 14:40:23 +09003722 ensureRunningOnConnectivityServiceThread();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003723 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09003724 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003725 }
lucaslinb5b671a2019-02-12 15:30:13 +08003726 // Clear all notifications of this network.
Serik Beketayev284cb872020-12-07 22:43:07 -08003727 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003728 // A network agent has disconnected.
3729 // TODO - if we move the logic to the network agent (have them disconnect
3730 // because they lost all their requests or because their score isn't good)
3731 // then they would disconnect organically, report their new state and then
3732 // disconnect the channel.
3733 if (nai.networkInfo.isConnected()) {
3734 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3735 null, null);
3736 }
Chalard Jean1bc77a92021-02-04 13:12:59 +09003737 final boolean wasDefault = isDefaultNetwork(nai);
3738 if (wasDefault) {
Chalard Jeanefaf6532018-05-11 20:19:20 +09003739 mDefaultInetConditionPublished = 0;
Chalard Jeanefaf6532018-05-11 20:19:20 +09003740 }
3741 notifyIfacesChangedForNetworkStats();
3742 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3743 // by other networks that are already connected. Perhaps that can be done by
3744 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3745 // of rematchAllNetworksAndRequests
3746 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai21c06d02019-01-03 18:50:15 +08003747 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Bright60f02ed2020-06-15 16:10:01 -07003748
3749 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003750 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3751 // Disable wakeup packet monitoring for each interface.
3752 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3753 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09003754 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09003755 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti714b7862019-02-19 13:21:56 +09003756 nai.clatd.update();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003757 synchronized (mNetworkForNetId) {
3758 // Remove the NetworkAgent, but don't mark the netId as
3759 // available until we've told netd to delete it below.
Serik Beketayev284cb872020-12-07 22:43:07 -08003760 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeanefaf6532018-05-11 20:19:20 +09003761 }
Lorenzo Colittic284b4b2021-01-12 00:34:44 +09003762 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003763 // Remove all previously satisfied requests.
3764 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattis1238af22020-12-23 16:37:26 -08003765 final NetworkRequest request = nai.requestAt(i);
Chalard Jeane8cf3bf2019-11-05 15:07:09 +09003766 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattis622428c2020-12-02 14:12:41 -08003767 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayev284cb872020-12-07 22:43:07 -08003768 if (currentNetwork != null
3769 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattis1238af22020-12-23 16:37:26 -08003770 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003771 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3772 // rematch not to keep disconnected agents instead of setting it here ; this
3773 // will also allow removing updating the offers below.
James Mattis622428c2020-12-02 14:12:41 -08003774 nri.setSatisfier(null, null);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003775 for (final NetworkOfferInfo noi : mNetworkOffers) {
3776 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis1238af22020-12-23 16:37:26 -08003777 }
James Mattis8af2d602020-12-20 11:09:58 -08003778
Chalard Jean1bc77a92021-02-04 13:12:59 +09003779 if (mDefaultRequest == nri) {
James Mattis8af2d602020-12-20 11:09:58 -08003780 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean1bc77a92021-02-04 13:12:59 +09003781 // active at the same time. For now keep calling this with the default
James Mattis8af2d602020-12-20 11:09:58 -08003782 // network, because while incorrect this is the closest to the old (also
3783 // incorrect) behavior.
3784 mNetworkActivityTracker.updateDataActivityTracking(
3785 null /* newNetwork */, nai);
James Mattis8af2d602020-12-20 11:09:58 -08003786 ensureNetworkTransitionWakelock(nai.toShortString());
3787 }
Chalard Jeanefaf6532018-05-11 20:19:20 +09003788 }
3789 }
junyulai2a4f0062021-02-03 20:15:30 +08003790 nai.clearInactivityState();
James Mattis8af2d602020-12-20 11:09:58 -08003791 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003792 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattis8af2d602020-12-20 11:09:58 -08003793 // Find out why, fix the rematch code, and delete this.
Chalard Jean1bc77a92021-02-04 13:12:59 +09003794 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jean60902092019-11-07 18:54:49 +09003795 rematchAllNetworksAndRequests();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003796 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003797
3798 // Immediate teardown.
3799 if (nai.teardownDelayMs == 0) {
3800 destroyNetwork(nai);
3801 return;
3802 }
3803
3804 // Delayed teardown.
3805 try {
3806 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3807 } catch (RemoteException e) {
3808 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3809 }
3810 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3811 }
3812
3813 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeanefaf6532018-05-11 20:19:20 +09003814 if (nai.created) {
3815 // Tell netd to clean up the configuration for this network
3816 // (routing rules, DNS, etc).
3817 // This may be slow as it requires a lot of netd shelling out to ip and
3818 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean1bc77a92021-02-04 13:12:59 +09003819 // after we've rematched networks with requests (which might change the default
3820 // network or service a new request from an app), so network traffic isn't interrupted
3821 // for an unnecessarily long time.
Luke Huang135c5262019-04-09 18:41:49 +08003822 destroyNativeNetwork(nai);
Chalard Jeanefaf6532018-05-11 20:19:20 +09003823 mDnsManager.removeNetwork(nai.network);
3824 }
Serik Beketayev284cb872020-12-07 22:43:07 -08003825 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colitti6d880782021-03-11 01:32:09 +09003826 nai.onNetworkDestroyed();
Chalard Jeanefaf6532018-05-11 20:19:20 +09003827 }
3828
Ken Chende5e7aa2021-04-09 15:08:42 +08003829 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huang135c5262019-04-09 18:41:49 +08003830 try {
3831 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chende5e7aa2021-04-09 15:08:42 +08003832 final NativeNetworkConfig config;
3833 if (nai.isVPN()) {
3834 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen4e6ae312021-05-12 13:38:13 +08003835 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chende5e7aa2021-04-09 15:08:42 +08003836 return false;
3837 }
3838 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3839 INetd.PERMISSION_NONE,
3840 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3841 getVpnType(nai));
Luke Huang135c5262019-04-09 18:41:49 +08003842 } else {
Ken Chende5e7aa2021-04-09 15:08:42 +08003843 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3844 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3845 VpnManager.TYPE_VPN_NONE);
Luke Huang135c5262019-04-09 18:41:49 +08003846 }
Ken Chende5e7aa2021-04-09 15:08:42 +08003847 mNetd.networkCreate(config);
3848 mDnsResolver.createNetworkCache(nai.network.getNetId());
3849 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3850 nai.networkCapabilities.getTransportTypes());
Luke Huang135c5262019-04-09 18:41:49 +08003851 return true;
3852 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen4e6ae312021-05-12 13:38:13 +08003853 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huang135c5262019-04-09 18:41:49 +08003854 return false;
3855 }
3856 }
3857
Ken Chende5e7aa2021-04-09 15:08:42 +08003858 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huang135c5262019-04-09 18:41:49 +08003859 try {
Ken Chende5e7aa2021-04-09 15:08:42 +08003860 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Oh1abe20f2021-01-20 11:04:46 +09003861 } catch (RemoteException | ServiceSpecificException e) {
3862 loge("Exception destroying network(networkDestroy): " + e);
3863 }
3864 try {
Ken Chende5e7aa2021-04-09 15:08:42 +08003865 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huang135c5262019-04-09 18:41:49 +08003866 } catch (RemoteException | ServiceSpecificException e) {
3867 loge("Exception destroying network: " + e);
3868 }
3869 }
3870
Jeremy Joslin94c30992014-11-05 10:32:09 -08003871 // If this method proves to be too slow then we can maintain a separate
3872 // pendingIntent => NetworkRequestInfo map.
3873 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3874 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003875 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3876 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3877 if (existingPendingIntent != null &&
paulhu94c60a92021-03-04 11:36:55 +08003878 existingPendingIntent.intentFilterEquals(pendingIntent)) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003879 return entry.getValue();
3880 }
3881 }
3882 return null;
3883 }
3884
James Mattis08131f32020-12-13 16:28:14 -08003885 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08003886 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattis08131f32020-12-13 16:28:14 -08003887 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3888 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3889 final NetworkRequestInfo existingRequest =
3890 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003891 if (existingRequest != null) { // remove the existing request.
James Mattis08131f32020-12-13 16:28:14 -08003892 if (DBG) {
3893 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3894 + nri.mRequests.get(0) + " because their intents matched.");
3895 }
Lorenzo Colittie0857092021-03-12 22:39:08 +09003896 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohen06633de2019-01-08 12:09:18 -08003897 /* callOnUnavailable */ false);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003898 }
Erik Kline74d68ef2015-04-30 12:58:40 +09003899 handleRegisterNetworkRequest(nri);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003900 }
3901
James Mattis08131f32020-12-13 16:28:14 -08003902 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattise494cbb2021-02-09 18:18:28 -08003903 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis6e6fabf2021-01-10 14:24:24 -08003904 }
3905
James Mattise494cbb2021-02-09 18:18:28 -08003906 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean4deee632019-11-05 14:40:23 +09003907 ensureRunningOnConnectivityServiceThread();
James Mattis6e6fabf2021-01-10 14:24:24 -08003908 for (final NetworkRequestInfo nri : nris) {
3909 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3910 for (final NetworkRequest req : nri.mRequests) {
3911 mNetworkRequests.put(req, nri);
junyulai8cae3c72021-03-12 20:05:08 +08003912 // TODO: Consider update signal strength for other types.
James Mattis6e6fabf2021-01-10 14:24:24 -08003913 if (req.isListen()) {
3914 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3915 if (req.networkCapabilities.hasSignalStrength()
3916 && network.satisfiesImmutableCapabilitiesOf(req)) {
3917 updateSignalStrengthThresholds(network, "REGISTER", req);
3918 }
James Mattis08131f32020-12-13 16:28:14 -08003919 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09003920 }
3921 }
Chalard Jeand67ab4d2021-03-05 19:18:14 +09003922 // If this NRI has a satisfier already, it is replacing an older request that
3923 // has been removed. Track it.
3924 final NetworkRequest activeRequest = nri.getActiveRequest();
3925 if (null != activeRequest) {
3926 // If there is an active request, then for sure there is a satisfier.
3927 nri.getSatisfier().addRequest(activeRequest);
3928 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09003929 }
James Mattis08131f32020-12-13 16:28:14 -08003930
James Mattis6e6fabf2021-01-10 14:24:24 -08003931 rematchAllNetworksAndRequests();
James Mattis6e6fabf2021-01-10 14:24:24 -08003932
Chalard Jean7b6a33b2021-01-12 10:58:56 +09003933 // Requests that have not been matched to a network will not have been sent to the
3934 // providers, because the old satisfier and the new satisfier are the same (null in this
3935 // case). Send these requests to the providers.
3936 for (final NetworkRequestInfo nri : nris) {
3937 for (final NetworkOfferInfo noi : mNetworkOffers) {
3938 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis6e6fabf2021-01-10 14:24:24 -08003939 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07003940 }
3941 }
3942
James Mattis08131f32020-12-13 16:28:14 -08003943 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3944 final int callingUid) {
3945 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003946 if (nri != null) {
James Mattis08131f32020-12-13 16:28:14 -08003947 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3948 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3949 handleReleaseNetworkRequest(
3950 nri.mRequests.get(0),
3951 callingUid,
3952 /* callOnUnavailable */ false);
Jeremy Joslin94c30992014-11-05 10:32:09 -08003953 }
3954 }
3955
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003956 // Determines whether the network is the best (or could become the best, if it validated), for
3957 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3958 // on the value of reason:
3959 //
3960 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3961 // then it should be torn down.
3962 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3963 // then it should be lingered.
3964 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean4deee632019-11-05 14:40:23 +09003965 ensureRunningOnConnectivityServiceThread();
Chalard Jeanf278aba2021-03-08 22:29:27 +09003966
3967 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
3968 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
3969 return false;
3970 }
3971
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003972 final int numRequests;
3973 switch (reason) {
3974 case TEARDOWN:
3975 numRequests = nai.numRequestNetworkRequests();
3976 break;
3977 case LINGER:
3978 numRequests = nai.numForegroundNetworkRequests();
3979 break;
3980 default:
Aaron Huang11e9a312020-10-30 22:04:25 +08003981 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003982 return true;
3983 }
3984
Chalard Jeanf278aba2021-03-08 22:29:27 +09003985 if (numRequests > 0) return false;
3986
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003987 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattise4e72bb2020-11-16 16:46:28 -08003988 if (reason == UnneededFor.LINGER
3989 && !nri.isMultilayerRequest()
3990 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09003991 // Background requests don't affect lingering.
3992 continue;
3993 }
3994
James Mattise4e72bb2020-11-16 16:46:28 -08003995 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003996 return false;
Paul Jensen203a7442014-12-09 11:43:45 -05003997 }
3998 }
Paul Jensen25eb5fd2015-06-25 15:30:08 -04003999 return true;
Paul Jensen203a7442014-12-09 11:43:45 -05004000 }
4001
James Mattise4e72bb2020-11-16 16:46:28 -08004002 private boolean isNetworkPotentialSatisfier(
4003 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4004 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis65d0d1c2020-11-24 17:40:49 -08004005 // request, return immediately. For multilayer requests, check to see if any of the
4006 // multilayer requests may have a potential satisfier.
junyulai8cae3c72021-03-12 20:05:08 +08004007 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4008 || nri.mRequests.get(0).isListenForBest())) {
James Mattise4e72bb2020-11-16 16:46:28 -08004009 return false;
4010 }
4011 for (final NetworkRequest req : nri.mRequests) {
James Mattis622428c2020-12-02 14:12:41 -08004012 // This multilayer listen request is satisfied therefore no further requests need to be
4013 // evaluated deeming this network not a potential satisfier.
junyulai8cae3c72021-03-12 20:05:08 +08004014 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattis622428c2020-12-02 14:12:41 -08004015 return false;
4016 }
James Mattise4e72bb2020-11-16 16:46:28 -08004017 // As non-multilayer listen requests have already returned, the below would only happen
4018 // for a multilayer request therefore continue to the next request if available.
junyulai8cae3c72021-03-12 20:05:08 +08004019 if (req.isListen() || req.isListenForBest()) {
James Mattise4e72bb2020-11-16 16:46:28 -08004020 continue;
4021 }
4022 // If this Network is already the highest scoring Network for a request, or if
4023 // there is hope for it to become one if it validated, then it is needed.
4024 if (candidate.satisfies(req)) {
4025 // As soon as a network is found that satisfies a request, return. Specifically for
4026 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4027 // is important so as to not evaluate lower priority requests further in
4028 // nri.mRequests.
Chalard Jean3d71e302021-04-07 17:06:19 +09004029 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4030 ? nri.getSatisfier() : null;
4031 // Note that this catches two important cases:
4032 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4033 // is currently satisfying the request. This is desirable when
4034 // cellular ends up validating but WiFi does not.
4035 // 2. Unvalidated WiFi will not be reaped when validated cellular
4036 // is currently satisfying the request. This is desirable when
4037 // WiFi ends up validating and out scoring cellular.
4038 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattise4e72bb2020-11-16 16:46:28 -08004039 }
4040 }
4041
4042 return false;
4043 }
4044
Erik Klineaec3f5e2016-07-07 16:50:58 +09004045 private NetworkRequestInfo getNriForAppRequest(
4046 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattise494cbb2021-02-09 18:18:28 -08004047 // Looking up the app passed param request in mRequests isn't possible since it may return
4048 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4049 // do the lookup since that will also find per-app default managed requests.
James Mattis27aeff02021-02-17 16:13:05 -08004050 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4051 // to avoid potential race conditions when validating a package->uid mapping when sending
4052 // the callback on the very low-chance that an application shuts down prior to the callback
4053 // being sent.
4054 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4055 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004056
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004057 if (nri != null) {
lucaslin2d72a132021-03-15 15:35:38 +08004058 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004059 log(String.format("UID %d attempted to %s for unowned request %s",
4060 callingUid, requestedOperation, nri));
4061 return null;
Paul Jensenabaa0ed2014-05-16 14:31:12 -04004062 }
Erik Klineaec3f5e2016-07-07 16:50:58 +09004063 }
4064
4065 return nri;
4066 }
4067
James Mattis08131f32020-12-13 16:28:14 -08004068 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4069 final String callingMethod) {
4070 if (nri.isMultilayerRequest()) {
4071 throw new IllegalStateException(
4072 callingMethod + " does not support multilayer requests.");
Erik Kline66721822015-11-25 12:49:38 +09004073 }
4074 }
4075
James Mattis08131f32020-12-13 16:28:14 -08004076 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004077 ensureRunningOnConnectivityServiceThread();
James Mattis08131f32020-12-13 16:28:14 -08004078 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4079 // single NetworkRequest and thus does not apply to multilayer requests.
4080 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4081 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004082 return;
4083 }
James Mattisf61f7be2021-01-31 17:06:19 -08004084 if (nri.isBeingSatisfied()) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004085 return;
4086 }
James Mattis08131f32020-12-13 16:28:14 -08004087 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4088 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Klineaec3f5e2016-07-07 16:50:58 +09004089 }
4090 handleRemoveNetworkRequest(nri);
James Mattis08131f32020-12-13 16:28:14 -08004091 callCallbackForRequest(
4092 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004093 }
4094
James Mattis08131f32020-12-13 16:28:14 -08004095 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4096 final int callingUid,
4097 final boolean callOnUnavailable) {
Hugo Benichi4802c802017-03-23 22:40:44 +09004098 final NetworkRequestInfo nri =
4099 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4100 if (nri == null) {
4101 return;
Erik Kline66721822015-11-25 12:49:38 +09004102 }
James Mattis08131f32020-12-13 16:28:14 -08004103 if (VDBG || (DBG && request.isRequest())) {
4104 log("releasing " + request + " (release request)");
Hugo Benichi4802c802017-03-23 22:40:44 +09004105 }
4106 handleRemoveNetworkRequest(nri);
Etan Cohen06633de2019-01-08 12:09:18 -08004107 if (callOnUnavailable) {
4108 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4109 }
Erik Kline66721822015-11-25 12:49:38 +09004110 }
Erik Klineaec3f5e2016-07-07 16:50:58 +09004111
James Mattis622428c2020-12-02 14:12:41 -08004112 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean4deee632019-11-05 14:40:23 +09004113 ensureRunningOnConnectivityServiceThread();
Erik Klineaec3f5e2016-07-07 16:50:58 +09004114 nri.unlinkDeathRecipient();
James Mattis622428c2020-12-02 14:12:41 -08004115 for (final NetworkRequest req : nri.mRequests) {
4116 mNetworkRequests.remove(req);
4117 if (req.isListen()) {
4118 removeListenRequestFromNetworks(req);
4119 }
4120 }
Chalard Jean07dc1862021-03-01 22:08:57 +09004121 if (mDefaultNetworkRequests.remove(nri)) {
4122 // If this request was one of the defaults, then the UID rules need to be updated
4123 // WARNING : if the app(s) for which this network request is the default are doing
4124 // traffic, this will kill their connected sockets, even if an equivalent request
4125 // is going to be reinstated right away ; unconnected traffic will go on the default
4126 // until the new default is set, which will happen very soon.
4127 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4128 // remove ranges for those requests that won't have a replacement
4129 final NetworkAgentInfo satisfier = nri.getSatisfier();
4130 if (null != satisfier) {
4131 try {
4132 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4133 toUidRangeStableParcels(nri.getUids()));
4134 } catch (RemoteException e) {
4135 loge("Exception setting network preference default network", e);
4136 }
4137 }
4138 }
Chalard Jean70b2d9a2021-04-01 16:41:04 +09004139 nri.decrementRequestCount();
Erik Klineaec3f5e2016-07-07 16:50:58 +09004140 mNetworkRequestInfoLogs.log("RELEASE " + nri);
James Mattis622428c2020-12-02 14:12:41 -08004141
4142 if (null != nri.getActiveRequest()) {
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09004143 if (!nri.getActiveRequest().isListen()) {
James Mattis622428c2020-12-02 14:12:41 -08004144 removeSatisfiedNetworkRequestFromNetwork(nri);
4145 } else {
4146 nri.setSatisfier(null, null);
4147 }
4148 }
4149
Chalard Jean7b6a33b2021-01-12 10:58:56 +09004150 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4151 // needed for this offer.
4152 for (final NetworkOfferInfo noi : mNetworkOffers) {
4153 for (final NetworkRequest req : nri.mRequests) {
4154 if (req.isRequest() && noi.offer.neededFor(req)) {
4155 noi.offer.onNetworkUnneeded(req);
4156 }
4157 }
4158 }
James Mattis622428c2020-12-02 14:12:41 -08004159 }
4160
James Mattise494cbb2021-02-09 18:18:28 -08004161 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4162 for (final NetworkRequestInfo nri : nris) {
4163 if (mDefaultRequest == nri) {
4164 // Make sure we never remove the default request.
4165 continue;
4166 }
4167 handleRemoveNetworkRequest(nri);
4168 }
4169 }
4170
James Mattis622428c2020-12-02 14:12:41 -08004171 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4172 // listens don't have a singular affected Network. Check all networks to see
4173 // if this listen request applies and remove it.
4174 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4175 nai.removeRequest(req.requestId);
4176 if (req.networkCapabilities.hasSignalStrength()
4177 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4178 updateSignalStrengthThresholds(nai, "RELEASE", req);
4179 }
4180 }
4181 }
4182
4183 /**
4184 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4185 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4186 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4187 */
4188 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4189 boolean wasKept = false;
4190 final NetworkAgentInfo nai = nri.getSatisfier();
4191 if (nai != null) {
4192 final int requestLegacyType = nri.getActiveRequest().legacyType;
4193 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4194 nai.removeRequest(nri.getActiveRequest().requestId);
4195 if (VDBG || DDBG) {
4196 log(" Removing from current network " + nai.toShortString()
4197 + ", leaving " + nai.numNetworkRequests() + " requests.");
4198 }
4199 // If there are still lingered requests on this network, don't tear it down,
4200 // but resume lingering instead.
4201 final long now = SystemClock.elapsedRealtime();
junyulai2a4f0062021-02-03 20:15:30 +08004202 if (updateInactivityState(nai, now)) {
James Mattis622428c2020-12-02 14:12:41 -08004203 notifyNetworkLosing(nai, now);
4204 }
4205 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4206 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4207 teardownUnneededNetwork(nai);
4208 } else {
4209 wasKept = true;
4210 }
4211 nri.setSatisfier(null, null);
4212 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4213 // Went from foreground to background.
4214 updateCapabilitiesForNetwork(nai);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004215 }
4216
Erik Klineaec3f5e2016-07-07 16:50:58 +09004217 // Maintain the illusion. When this request arrived, we might have pretended
4218 // that a network connected to serve it, even though the network was already
4219 // connected. Now that this request has gone away, we might have to pretend
4220 // that the network disconnected. LegacyTypeTracker will generate that
4221 // phantom disconnect for this type.
James Mattis622428c2020-12-02 14:12:41 -08004222 if (requestLegacyType != TYPE_NONE) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004223 boolean doRemove = true;
4224 if (wasKept) {
4225 // check if any of the remaining requests for this network are for the
4226 // same legacy type - if so, don't remove the nai
4227 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4228 NetworkRequest otherRequest = nai.requestAt(i);
James Mattis622428c2020-12-02 14:12:41 -08004229 if (otherRequest.legacyType == requestLegacyType
4230 && otherRequest.isRequest()) {
Erik Klineaec3f5e2016-07-07 16:50:58 +09004231 if (DBG) log(" still have other legacy request - leaving");
4232 doRemove = false;
Robert Greenwaltb0491bb2015-01-08 14:43:31 -08004233 }
4234 }
Robert Greenwaltbc5794d2014-08-24 22:52:10 -07004235 }
4236
Erik Klineaec3f5e2016-07-07 16:50:58 +09004237 if (doRemove) {
James Mattis622428c2020-12-02 14:12:41 -08004238 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Klineaec3f5e2016-07-07 16:50:58 +09004239 }
4240 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004241 }
4242 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004243
Lorenzo Colittib4f8d8e2021-03-30 19:29:00 +09004244 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4245 return checkAnyPermissionOf(
4246 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4247 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4248 }
4249
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004250 @Override
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004251 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin25a50472019-03-12 13:08:03 +08004252 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004253 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004254 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004255 }
4256
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004257 @Override
lucaslin25a50472019-03-12 13:08:03 +08004258 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4259 enforceNetworkStackSettingsOrSetup();
4260 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4261 encodeBool(accept), encodeBool(always), network));
4262 }
4263
4264 @Override
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004265 public void setAvoidUnvalidated(Network network) {
lucaslin25a50472019-03-12 13:08:03 +08004266 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004267 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4268 }
4269
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004270 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4271 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4272 " accept=" + accept + " always=" + always);
4273
4274 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4275 if (nai == null) {
4276 // Nothing to do.
4277 return;
4278 }
4279
4280 if (nai.everValidated) {
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004281 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004282 return;
4283 }
4284
Lorenzo Colitticf595362020-01-12 22:28:37 +09004285 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang11e9a312020-10-30 22:04:25 +08004286 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004287 }
4288
Lorenzo Colitticf595362020-01-12 22:28:37 +09004289 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4290 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin25a50472019-03-12 13:08:03 +08004291 // If network becomes partial connectivity and user already accepted to use this
4292 // network, we should respect the user's option and don't need to popup the
4293 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004294 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean1fc55292021-03-31 23:19:05 +09004295 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean60902092019-11-07 18:54:49 +09004296 rematchAllNetworksAndRequests();
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004297 }
4298
4299 if (always) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004300 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004301 }
4302
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004303 if (!accept) {
Paul Jensen4afac232015-07-13 15:19:51 -04004304 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004305 nai.onPreventAutomaticReconnect();
Chalard Jean73d9db72018-06-04 16:52:49 +09004306 // Teardown the network.
Paul Jensen4afac232015-07-13 15:19:51 -04004307 teardownUnneededNetwork(nai);
Lorenzo Colitti37a4d552015-05-21 16:17:05 +09004308 }
4309
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004310 }
4311
lucaslin25a50472019-03-12 13:08:03 +08004312 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4313 boolean always) {
4314 if (DBG) {
4315 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4316 + " always=" + always);
4317 }
4318
4319 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4320 if (nai == null) {
4321 // Nothing to do.
4322 return;
4323 }
4324
4325 if (nai.lastValidated) {
4326 // The network validated while the dialog box was up. Take no action.
4327 return;
4328 }
4329
Lorenzo Colitticf595362020-01-12 22:28:37 +09004330 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4331 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin25a50472019-03-12 13:08:03 +08004332 }
4333
4334 // TODO: Use the current design or save the user choice into IpMemoryStore.
4335 if (always) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004336 nai.onSaveAcceptUnvalidated(accept);
lucaslin25a50472019-03-12 13:08:03 +08004337 }
4338
4339 if (!accept) {
4340 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004341 nai.onPreventAutomaticReconnect();
lucaslin25a50472019-03-12 13:08:03 +08004342 // Tear down the network.
4343 teardownUnneededNetwork(nai);
4344 } else {
lucaslin2afb4bc2019-03-20 18:21:59 +08004345 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4346 // result in a partial connectivity result which will be processed by
4347 // maybeHandleNetworkMonitorMessage.
Chiachang Wang9cfa6fe2019-05-23 16:29:30 +08004348 //
4349 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4350 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004351 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin25a50472019-03-12 13:08:03 +08004352 }
4353 }
4354
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004355 private void handleSetAvoidUnvalidated(Network network) {
4356 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4357 if (nai == null || nai.lastValidated) {
4358 // Nothing to do. The network either disconnected or revalidated.
4359 return;
4360 }
4361 if (!nai.avoidUnvalidated) {
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004362 nai.avoidUnvalidated = true;
Chalard Jean1fc55292021-03-31 23:19:05 +09004363 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean60902092019-11-07 18:54:49 +09004364 rematchAllNetworksAndRequests();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004365 }
4366 }
4367
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004368 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09004369 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004370 mHandler.sendMessageDelayed(
4371 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4372 PROMPT_UNVALIDATED_DELAY_MS);
4373 }
4374
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004375 @Override
4376 public void startCaptivePortalApp(Network network) {
paulhud70b7dd2019-08-12 16:25:11 +08004377 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004378 mHandler.post(() -> {
4379 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4380 if (nai == null) return;
4381 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004382 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti755e7962017-04-27 14:30:21 +09004383 });
4384 }
4385
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004386 /**
4387 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4388 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004389 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004390 * @param appExtras Bundle to use as intent extras for the captive portal application.
4391 * Must be treated as opaque to avoid preventing the captive portal app to
4392 * update its arguments.
4393 */
4394 @Override
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004395 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhud203f7a2019-05-14 14:17:44 +08004396 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4397 "ConnectivityService");
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004398
4399 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4400 appIntent.putExtras(appExtras);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004401 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4402 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004403 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4404
lucaslin86086772020-12-17 04:14:35 +08004405 final long token = Binder.clearCallingIdentity();
4406 try {
4407 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4408 } finally {
4409 Binder.restoreCallingIdentity(token);
4410 }
Remi NGUYEN VANf363f5f2019-02-04 11:32:20 +09004411 }
4412
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004413 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4414 private final Network mNetwork;
4415
4416 private CaptivePortalImpl(Network network) {
4417 mNetwork = network;
4418 }
4419
4420 @Override
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004421 public void appResponse(final int response) {
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004422 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4423 enforceSettingsPermission();
4424 }
4425
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004426 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004427 if (nm == null) return;
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004428 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004429 }
4430
4431 @Override
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004432 public void appRequest(final int request) {
4433 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4434 if (nm == null) return;
4435
4436 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wang1fa770d2020-02-12 13:44:50 +08004437 checkNetworkStackPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09004438 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wangef4a17d2020-01-09 13:50:55 +08004439 }
4440 }
4441
4442 @Nullable
4443 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4444 // getNetworkAgentInfoForNetwork is thread-safe
4445 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4446 if (nai == null) return null;
4447
4448 // nai.networkMonitor() is thread-safe
4449 return nai.networkMonitor();
4450 }
Remi NGUYEN VAN89fbdc32019-02-13 20:58:59 +09004451 }
4452
Hugo Benichi4fc79c42016-09-14 23:23:08 +00004453 public boolean avoidBadWifi() {
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004454 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti49d32fe2016-09-16 23:43:38 +09004455 }
4456
Remi NGUYEN VAN338eb2a2019-03-22 11:14:13 +09004457 /**
4458 * Return whether the device should maintain continuous, working connectivity by switching away
4459 * from WiFi networks having no connectivity.
4460 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4461 */
4462 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN3436b6f2019-01-20 20:35:06 +09004463 if (!checkNetworkStackPermission()) {
4464 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4465 }
4466 return avoidBadWifi();
4467 }
4468
Chalard Jean78515442021-03-19 13:49:56 +09004469 private void updateAvoidBadWifi() {
4470 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean1fc55292021-03-31 23:19:05 +09004471 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean78515442021-03-19 13:49:56 +09004472 }
Chalard Jean60902092019-11-07 18:54:49 +09004473 rematchAllNetworksAndRequests();
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004474 }
4475
Erik Klinefc52be92016-10-02 18:02:14 +09004476 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004477 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004478 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004479 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004480 if (!configRestrict) {
4481 pw.println("Bad Wi-Fi avoidance: unrestricted");
4482 return;
4483 }
4484
4485 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4486 pw.increaseIndent();
4487 pw.println("Config restrict: " + configRestrict);
4488
Lorenzo Colittib8dfec42017-01-24 09:41:36 +09004489 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004490 String description;
4491 // Can't use a switch statement because strings are legal case labels, but null is not.
4492 if ("0".equals(value)) {
4493 description = "get stuck";
4494 } else if (value == null) {
4495 description = "prompt";
4496 } else if ("1".equals(value)) {
4497 description = "avoid";
4498 } else {
4499 description = value + " (?)";
4500 }
4501 pw.println("User setting: " + description);
4502 pw.println("Network overrides:");
4503 pw.increaseIndent();
Hugo Benichi821785c2018-09-03 08:19:02 +09004504 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004505 if (nai.avoidUnvalidated) {
Chalard Jean373391b2019-12-10 21:07:02 +09004506 pw.println(nai.toShortString());
Lorenzo Colitti7dabed82016-09-20 16:03:27 +09004507 }
4508 }
4509 pw.decreaseIndent();
4510 pw.decreaseIndent();
4511 }
4512
paulhu68426192020-06-09 19:07:03 +08004513 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4514 // unify the method.
4515 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4516 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4517 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4518 return settingsComponent != null
4519 ? settingsComponent.getPackageName() : "com.android.settings";
4520 }
4521
lucaslin1ac72392019-01-24 15:55:30 +08004522 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004523 final String action;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004524 final boolean highPriority;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004525 switch (type) {
4526 case NO_INTERNET:
4527 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004528 // High priority because it is only displayed for explicitly selected networks.
4529 highPriority = true;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004530 break;
lucaslin8cf57f52019-10-22 18:27:33 +08004531 case PRIVATE_DNS_BROKEN:
4532 action = Settings.ACTION_WIRELESS_SETTINGS;
4533 // High priority because we should let user know why there is no internet.
4534 highPriority = true;
4535 break;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004536 case LOST_INTERNET:
4537 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004538 // High priority because it could help the user avoid unexpected data usage.
4539 highPriority = true;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004540 break;
lucaslin25a50472019-03-12 13:08:03 +08004541 case PARTIAL_CONNECTIVITY:
4542 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004543 // Don't bother the user with a high-priority notification if the network was not
4544 // explicitly selected by the user.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004545 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin25a50472019-03-12 13:08:03 +08004546 break;
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004547 default:
Aaron Huang11e9a312020-10-30 22:04:25 +08004548 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004549 return;
4550 }
4551
4552 Intent intent = new Intent(action);
lucaslin5cba3142020-02-20 16:56:59 +08004553 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wangef52aad2021-03-18 16:20:27 +08004554 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslin1ac72392019-01-24 15:55:30 +08004555 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu68426192020-06-09 19:07:03 +08004556 // Some OEMs have their own Settings package. Thus, need to get the current using
4557 // Settings package name instead of just use default name "com.android.settings".
4558 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4559 intent.setClassName(settingsPkgName,
4560 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslin1ac72392019-01-24 15:55:30 +08004561 }
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004562
paulhufea8f292020-10-11 22:52:27 +08004563 PendingIntent pendingIntent = PendingIntent.getActivity(
4564 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu68426192020-06-09 19:07:03 +08004565 0 /* requestCode */,
4566 intent,
paulhufea8f292020-10-11 22:52:27 +08004567 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colittifaee2602019-06-05 16:08:37 +09004568
Serik Beketayev284cb872020-12-07 22:43:07 -08004569 mNotifier.showNotification(
4570 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004571 }
4572
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004573 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4574 // Don't prompt if the network is validated, and don't prompt on captive portals
4575 // because we're already prompting the user to sign in.
4576 if (nai.everValidated || nai.everCaptivePortalDetected) {
4577 return false;
4578 }
4579
4580 // If a network has partial connectivity, always prompt unless the user has already accepted
4581 // partial connectivity and selected don't ask again. This ensures that if the device
4582 // automatically connects to a network that has partial Internet access, the user will
4583 // always be able to use it, either because they've already chosen "don't ask again" or
4584 // because we have prompt them.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004585 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004586 return true;
4587 }
4588
4589 // If a network has no Internet access, only prompt if the network was explicitly selected
4590 // and if the user has not already told us to use the network regardless of whether it
4591 // validated or not.
Lorenzo Colitticf595362020-01-12 22:28:37 +09004592 if (nai.networkAgentConfig.explicitlySelected
4593 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004594 return true;
4595 }
4596
4597 return false;
4598 }
4599
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004600 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09004601 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004602 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4603
Lorenzo Colitti559503f2019-06-04 19:29:50 +09004604 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004605 return;
4606 }
Lorenzo Colitti50501802019-05-30 16:24:31 +09004607
4608 // Stop automatically reconnecting to this network in the future. Automatically connecting
4609 // to a network that provides no or limited connectivity is not useful, because the user
4610 // cannot use that network except through the notification shown by this method, and the
4611 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09004612 nai.onPreventAutomaticReconnect();
Lorenzo Colitti50501802019-05-30 16:24:31 +09004613
lucaslin25a50472019-03-12 13:08:03 +08004614 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4615 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4616 // popup the notification immediately when the network is partial connectivity.
4617 if (nai.partialConnectivity) {
lucaslin32ecfc42019-03-21 11:59:22 +08004618 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin25a50472019-03-12 13:08:03 +08004619 } else {
4620 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4621 }
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004622 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004623
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004624 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4625 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean373391b2019-12-10 21:07:02 +09004626 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5447c492016-05-23 16:33:16 -07004627
lucaslin25a50472019-03-12 13:08:03 +08004628 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4629 return;
4630 }
4631
4632 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslin1ac72392019-01-24 15:55:30 +08004633 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09004634 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004635 }
4636
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004637 @Override
4638 public int getMultipathPreference(Network network) {
4639 enforceAccessPermission();
4640
4641 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey41a72692017-07-12 10:50:42 -06004642 if (nai != null && nai.networkCapabilities
4643 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004644 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4645 }
4646
Aaron Huang5301b6f2020-12-08 10:03:29 +08004647 final NetworkPolicyManager netPolicyManager =
4648 mContext.getSystemService(NetworkPolicyManager.class);
4649
Remi NGUYEN VAN92f20602021-03-18 14:23:12 +09004650 final long token = Binder.clearCallingIdentity();
4651 final int networkPreference;
4652 try {
4653 networkPreference = netPolicyManager.getMultipathPreference(network);
4654 } finally {
4655 Binder.restoreCallingIdentity(token);
4656 }
Aaron Huang5301b6f2020-12-08 10:03:29 +08004657 if (networkPreference != 0) {
Lorenzo Colitti7e5a1452018-01-24 17:35:07 +09004658 return networkPreference;
4659 }
Lorenzo Colitti231efb02017-01-24 18:08:41 +09004660 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4661 }
4662
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004663 @Override
4664 public NetworkRequest getDefaultRequest() {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004665 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004666 }
4667
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004668 private class InternalHandler extends Handler {
4669 public InternalHandler(Looper looper) {
4670 super(looper);
4671 }
4672
4673 @Override
4674 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004675 switch (msg.what) {
Robert Greenwalt61837eb2014-06-25 16:45:57 -07004676 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004677 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi58aab552017-03-30 23:18:10 +09004678 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004679 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004680 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07004681 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean9fbd93c2018-06-08 14:24:49 +09004682 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004683 break;
4684 }
Jason Monk445cea82013-10-10 14:02:51 -04004685 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangb2ad4a92021-01-18 15:28:01 +08004686 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4687 handleApplyDefaultProxy(arg.second);
Jason Monk445cea82013-10-10 14:02:51 -04004688 break;
4689 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09004690 case EVENT_REGISTER_NETWORK_PROVIDER: {
4691 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07004692 break;
4693 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09004694 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4695 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt948aea52014-04-11 15:53:27 -07004696 break;
4697 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09004698 case EVENT_REGISTER_NETWORK_OFFER: {
4699 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4700 break;
4701 }
4702 case EVENT_UNREGISTER_NETWORK_OFFER: {
4703 final NetworkOfferInfo offer =
4704 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4705 if (null != offer) {
4706 handleUnregisterNetworkOffer(offer);
4707 }
4708 break;
4709 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004710 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09004711 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4712 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4713 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07004714 break;
4715 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004716 case EVENT_REGISTER_NETWORK_REQUEST:
4717 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline74d68ef2015-04-30 12:58:40 +09004718 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004719 break;
4720 }
Paul Jensen9ceed862015-06-17 14:15:39 -04004721 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4722 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin94c30992014-11-05 10:32:09 -08004723 handleRegisterNetworkRequestWithIntent(msg);
4724 break;
4725 }
Erik Kline66721822015-11-25 12:49:38 +09004726 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4727 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4728 handleTimedOutNetworkRequest(nri);
4729 break;
4730 }
Jeremy Joslin94c30992014-11-05 10:32:09 -08004731 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4732 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4733 break;
4734 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004735 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohen06633de2019-01-08 12:09:18 -08004736 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4737 /* callOnUnavailable */ false);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004738 break;
4739 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004740 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004741 Network network = (Network) msg.obj;
4742 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004743 break;
4744 }
lucaslin25a50472019-03-12 13:08:03 +08004745 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4746 Network network = (Network) msg.obj;
4747 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4748 toBool(msg.arg2));
4749 break;
4750 }
Lorenzo Colittie98557f2016-09-19 01:00:19 +09004751 case EVENT_SET_AVOID_UNVALIDATED: {
4752 handleSetAvoidUnvalidated((Network) msg.obj);
4753 break;
4754 }
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09004755 case EVENT_PROMPT_UNVALIDATED: {
4756 handlePromptUnvalidated((Network) msg.obj);
4757 break;
4758 }
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07004759 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4760 handleConfigureAlwaysOnNetworks();
Erik Kline74d68ef2015-04-30 12:58:40 +09004761 break;
4762 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004763 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai21c06d02019-01-03 18:50:15 +08004764 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004765 mKeepaliveTracker.handleStartKeepalive(msg);
4766 break;
4767 }
4768 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai21c06d02019-01-03 18:50:15 +08004769 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09004770 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4771 int slot = msg.arg1;
4772 int reason = msg.arg2;
4773 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4774 break;
4775 }
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004776 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004777 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004778 break;
4779 }
Erik Klinec06d4f92018-01-11 21:07:29 +09004780 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4781 handlePrivateDnsSettingsChanged();
4782 break;
dalykf4977492018-03-05 12:42:22 -05004783 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4784 handlePrivateDnsValidationUpdate(
4785 (PrivateDnsValidationUpdate) msg.obj);
4786 break;
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00004787 case EVENT_UID_BLOCKED_REASON_CHANGED:
4788 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulai5ab727b2018-08-07 19:50:45 +08004789 break;
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09004790 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4791 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4792 break;
Chalard Jeandc974072021-03-01 22:00:20 +09004793 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jeancc9ad152021-03-03 16:37:13 +09004794 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4795 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jeandc974072021-03-01 22:00:20 +09004796 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis6e6fabf2021-01-10 14:24:24 -08004797 break;
Chalard Jeandc974072021-03-01 22:00:20 +09004798 }
Chalard Jean9d968182021-02-25 21:46:34 +09004799 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4800 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4801 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4802 msg.obj;
4803 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhu339d9be2021-05-05 11:04:59 +08004804 break;
Chalard Jean9d968182021-02-25 21:46:34 +09004805 }
lucaslina5e9bdb2021-01-21 02:04:15 +08004806 case EVENT_REPORT_NETWORK_ACTIVITY:
4807 mNetworkActivityTracker.handleReportNetworkActivity();
4808 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004809 }
4810 }
4811 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004812
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004813 @Override
markchien4f949812019-12-16 20:15:20 +08004814 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004815 public int getLastTetherError(String iface) {
markchien4f949812019-12-16 20:15:20 +08004816 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4817 Context.TETHERING_SERVICE);
4818 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -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[] getTetherableIfaces() {
markchien4f949812019-12-16 20:15:20 +08004824 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4825 Context.TETHERING_SERVICE);
4826 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004827 }
4828
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004829 @Override
markchien4f949812019-12-16 20:15:20 +08004830 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004831 public String[] getTetheredIfaces() {
markchien4f949812019-12-16 20:15:20 +08004832 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4833 Context.TETHERING_SERVICE);
4834 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004835 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004836
markchien4f949812019-12-16 20:15:20 +08004837
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004838 @Override
markchien4f949812019-12-16 20:15:20 +08004839 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004840 public String[] getTetheringErroredIfaces() {
markchien4f949812019-12-16 20:15:20 +08004841 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4842 Context.TETHERING_SERVICE);
4843
4844 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004845 }
4846
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004847 @Override
markchien4f949812019-12-16 20:15:20 +08004848 @Deprecated
4849 public String[] getTetherableUsbRegexs() {
4850 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4851 Context.TETHERING_SERVICE);
4852
4853 return tm.getTetherableUsbRegexs();
Robert Greenwalta75c4652014-06-23 14:53:42 -07004854 }
4855
Udam Saini15072332017-06-07 12:06:28 -07004856 @Override
markchien4f949812019-12-16 20:15:20 +08004857 @Deprecated
4858 public String[] getTetherableWifiRegexs() {
4859 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4860 Context.TETHERING_SERVICE);
4861 return tm.getTetherableWifiRegexs();
markchiena005c992019-02-27 14:56:11 +08004862 }
4863
Robert Greenwalt205fd8e2014-07-02 09:59:16 -07004864 // Called when we lose the default network and have no replacement yet.
4865 // This will automatically be cleared after X seconds or a new default network
4866 // becomes CONNECTED, whichever happens first. The timer is started by the
4867 // first caller and not restarted by subsequent callers.
Hugo Benichi58aab552017-03-30 23:18:10 +09004868 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004869 synchronized (this) {
Hugo Benichi58aab552017-03-30 23:18:10 +09004870 if (mNetTransitionWakeLock.isHeld()) {
4871 return;
4872 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004873 mNetTransitionWakeLock.acquire();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09004874 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4875 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004876 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004877 mWakelockLogs.log("ACQUIRE for " + forWhom);
4878 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09004879 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09004880 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09004881 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004882 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07004883
Hugo Benichi58aab552017-03-30 23:18:10 +09004884 // Called when we gain a new default network to release the network transition wakelock in a
4885 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4886 // message is cancelled.
4887 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004888 synchronized (this) {
Hugo Benichi58aab552017-03-30 23:18:10 +09004889 if (!mNetTransitionWakeLock.isHeld()) {
4890 return; // expiry message released the lock first.
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004891 }
4892 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004893 // Cancel self timeout on wakelock hold.
4894 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4895 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4896 mHandler.sendMessageDelayed(msg, 1000);
4897 }
4898
4899 // Called when either message of ensureNetworkTransitionWakelock or
4900 // scheduleReleaseNetworkTransitionWakelock is processed.
4901 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4902 String event = eventName(eventId);
4903 synchronized (this) {
4904 if (!mNetTransitionWakeLock.isHeld()) {
4905 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang11e9a312020-10-30 22:04:25 +08004906 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi58aab552017-03-30 23:18:10 +09004907 return;
4908 }
4909 mNetTransitionWakeLock.release();
Hugo Benichi3ac913c2017-09-05 13:25:07 +09004910 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4911 mTotalWakelockDurationMs += lockDuration;
4912 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4913 mTotalWakelockReleases++;
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004914 }
Hugo Benichi58aab552017-03-30 23:18:10 +09004915 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi23ec1c92017-03-30 10:46:05 +09004916 }
4917
Robert Greenwalt986c7412010-09-08 15:24:47 -07004918 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004919 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07004920 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltb264cd82014-08-06 21:32:18 -07004921 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittibdda6bf2015-02-11 07:39:20 +09004922 if (nai == null) return;
Paul Jensen7aac1b32015-04-07 12:43:13 -04004923 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07004924 }
4925
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09004926 @Override
Paul Jensen7aac1b32015-04-07 12:43:13 -04004927 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen57d231c2014-08-29 09:54:01 -04004928 enforceAccessPermission();
4929 enforceInternetPermission();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09004930 final int uid = mDeps.getCallingUid();
Hugo Benichi7f919fe2017-04-21 15:07:12 +09004931 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kestinga58c07c2020-01-07 11:18:54 -08004932
Cody Kestingb0174782020-06-25 11:13:39 -07004933 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4934 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4935 // does not match the known connectivity of the network - this causes NetworkMonitor to
4936 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
Cody Kestinga58c07c2020-01-07 11:18:54 -08004937 final NetworkAgentInfo nai;
4938 if (network == null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004939 nai = getDefaultNetwork();
Cody Kestinga58c07c2020-01-07 11:18:54 -08004940 } else {
4941 nai = getNetworkAgentInfoForNetwork(network);
4942 }
4943 if (nai != null) {
4944 mConnectivityDiagnosticsHandler.sendMessage(
4945 mConnectivityDiagnosticsHandler.obtainMessage(
4946 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4947 connectivityInfo, 0, nai));
4948 }
Cody Kestingb0174782020-06-25 11:13:39 -07004949
4950 mHandler.sendMessage(
4951 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004952 }
Paul Jensen57d231c2014-08-29 09:54:01 -04004953
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004954 private void handleReportNetworkConnectivity(
4955 Network network, int uid, boolean hasConnectivity) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09004956 final NetworkAgentInfo nai;
Paul Jensen7aac1b32015-04-07 12:43:13 -04004957 if (network == null) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09004958 nai = getDefaultNetwork();
Paul Jensen7aac1b32015-04-07 12:43:13 -04004959 } else {
4960 nai = getNetworkAgentInfoForNetwork(network);
4961 }
Paul Jensen773f4f32015-06-25 10:28:34 -04004962 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4963 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4964 return;
4965 }
Paul Jensen7aac1b32015-04-07 12:43:13 -04004966 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9a35d82017-04-06 16:01:44 +09004967 if (hasConnectivity == nai.lastValidated) {
4968 return;
4969 }
Paul Jensen7aac1b32015-04-07 12:43:13 -04004970 if (DBG) {
Serik Beketayev284cb872020-12-07 22:43:07 -08004971 int netid = nai.network.getNetId();
Hugo Benichi1c7c8d02017-04-06 17:22:18 +09004972 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensen7aac1b32015-04-07 12:43:13 -04004973 }
Hugo Benichie9a35d82017-04-06 16:01:44 +09004974 // Validating a network that has not yet connected could result in a call to
4975 // rematchNetworkAndRequests() which is not meant to work on such networks.
4976 if (!nai.everConnected) {
4977 return;
Paul Jensen57d231c2014-08-29 09:54:01 -04004978 }
paulhu3b063e32020-12-30 00:42:19 +08004979 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
4980 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9a35d82017-04-06 16:01:44 +09004981 return;
4982 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09004983 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07004984 }
4985
Lorenzo Colittid81932b2021-03-23 21:01:07 +09004986 // TODO: call into netd.
4987 private boolean queryUserAccess(int uid, Network network) {
4988 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4989 if (nai == null) return false;
4990
4991 // Any UID can use its default network.
4992 if (nai == getDefaultNetworkForUid(uid)) return true;
4993
4994 // Privileged apps can use any network.
4995 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
4996 return true;
4997 }
4998
4999 // An unprivileged UID can use a VPN iff the VPN applies to it.
5000 if (nai.isVPN()) {
5001 return nai.networkCapabilities.appliesToUid(uid);
5002 }
5003
5004 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5005 // sockets, i.e., if it is the owner.
5006 final NetworkAgentInfo vpn = getVpnForUid(uid);
5007 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5008 && uid != vpn.networkCapabilities.getOwnerUid()) {
5009 return false;
5010 }
5011
5012 // The UID's permission must be at least sufficient for the network. Since the restricted
5013 // permission was already checked above, that just leaves background networks.
5014 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5015 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5016 }
5017
5018 // Unrestricted network. Anyone gets to use it.
5019 return true;
5020 }
5021
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005022 /**
5023 * Returns information about the proxy a certain network is using. If given a null network, it
5024 * it will return the proxy for the bound network for the caller app or the default proxy if
5025 * none.
5026 *
5027 * @param network the network we want to get the proxy information for.
5028 * @return Proxy information if a network has a proxy configured, or otherwise null.
5029 */
Lorenzo Colitti10e796c2016-07-04 12:55:44 +09005030 @Override
Paul Jensenfdec88b2015-05-06 07:32:40 -04005031 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean626c0122018-06-07 18:02:37 +09005032 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensenfdec88b2015-05-06 07:32:40 -04005033 if (globalProxy != null) return globalProxy;
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005034 if (network == null) {
5035 // Get the network associated with the calling UID.
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005036 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005037 true);
5038 if (activeNetwork == null) {
5039 return null;
5040 }
5041 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colittid81932b2021-03-23 21:01:07 +09005042 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005043 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5044 // caller may not have.
5045 return getLinkPropertiesProxyInfo(network);
5046 }
5047 // No proxy info available if the calling UID does not have network access.
5048 return null;
5049 }
5050
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005051
5052 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensenfdec88b2015-05-06 07:32:40 -04005053 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5054 if (nai == null) return null;
5055 synchronized (nai) {
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005056 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5057 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensenfdec88b2015-05-06 07:32:40 -04005058 }
5059 }
5060
Chalard Jean850c29e2018-06-07 18:37:59 +09005061 @Override
Chalard Jeanaac3b872021-03-17 17:03:34 +09005062 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu5e094422021-01-25 18:53:17 +08005063 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean850c29e2018-06-07 18:37:59 +09005064 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005065 }
5066
Chalard Jean626c0122018-06-07 18:02:37 +09005067 @Override
5068 @Nullable
Jason Monk1e3df5d2014-04-25 15:00:09 -04005069 public ProxyInfo getGlobalProxy() {
Chalard Jean626c0122018-06-07 18:02:37 +09005070 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005071 }
5072
Jason Monk1e3df5d2014-04-25 15:00:09 -04005073 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04005074 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard21523a42014-11-20 14:35:32 -05005075 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005076 proxy = null;
5077 }
Chalard Jeanbbd62a02018-06-08 12:20:15 +09005078 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005079 }
5080
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00005081 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5082 // when any network changes proxy.
5083 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5084 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005085 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensen12131352014-12-10 15:12:18 -05005086 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5087 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5088
Chalard Jean80b334a2018-06-07 17:41:29 +09005089 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean07c5bab2018-06-08 19:46:44 +09005090 mProxyTracker.sendProxyBroadcast();
Paul Jensen12131352014-12-10 15:12:18 -05005091 }
5092 }
5093
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005094 private static class SettingsObserver extends ContentObserver {
Erik Kline74d68ef2015-04-30 12:58:40 +09005095 final private HashMap<Uri, Integer> mUriEventMap;
5096 final private Context mContext;
5097 final private Handler mHandler;
5098
5099 SettingsObserver(Context context, Handler handler) {
5100 super(null);
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005101 mUriEventMap = new HashMap<>();
Erik Kline74d68ef2015-04-30 12:58:40 +09005102 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005103 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005104 }
5105
Erik Kline74d68ef2015-04-30 12:58:40 +09005106 void observe(Uri uri, int what) {
5107 mUriEventMap.put(uri, what);
5108 final ContentResolver resolver = mContext.getContentResolver();
5109 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005110 }
5111
5112 @Override
5113 public void onChange(boolean selfChange) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005114 Log.wtf(TAG, "Should never be reached.");
Erik Kline74d68ef2015-04-30 12:58:40 +09005115 }
5116
5117 @Override
5118 public void onChange(boolean selfChange, Uri uri) {
5119 final Integer what = mUriEventMap.get(uri);
5120 if (what != null) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09005121 mHandler.obtainMessage(what).sendToTarget();
Erik Kline74d68ef2015-04-30 12:58:40 +09005122 } else {
5123 loge("No matching event to send for URI=" + uri);
5124 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005125 }
5126 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005127
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005128 private static void log(String s) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005129 Log.d(TAG, s);
5130 }
5131
5132 private static void logw(String s) {
5133 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005134 }
5135
Daniel Bright60f02ed2020-06-15 16:10:01 -07005136 private static void logwtf(String s) {
5137 Log.wtf(TAG, s);
5138 }
5139
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09005140 private static void logwtf(String s, Throwable t) {
5141 Log.wtf(TAG, s, t);
5142 }
5143
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005144 private static void loge(String s) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005145 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005146 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005147
Hugo Benichi0a28d302017-02-11 17:04:43 +09005148 private static void loge(String s, Throwable t) {
Aaron Huang11e9a312020-10-30 22:04:25 +08005149 Log.e(TAG, s, t);
Hugo Benichi0a28d302017-02-11 17:04:43 +09005150 }
5151
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005152 /**
Varun Anand5e980f42019-02-07 14:13:13 -08005153 * Return the information of all ongoing VPNs.
5154 *
5155 * <p>This method is used to update NetworkStatsService.
5156 *
5157 * <p>Must be called on the handler thread.
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005158 */
junyulai62d35f72021-01-23 09:46:34 +08005159 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anand5e980f42019-02-07 14:13:13 -08005160 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005161 if (mLockdownEnabled) {
5162 return new UnderlyingNetworkInfo[0];
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005163 }
junyulai62d35f72021-01-23 09:46:34 +08005164 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colittia68139a2020-12-15 15:47:24 +09005165 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai62d35f72021-01-23 09:46:34 +08005166 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colittia68139a2020-12-15 15:47:24 +09005167 if (info != null) {
5168 infoList.add(info);
5169 }
5170 }
junyulai62d35f72021-01-23 09:46:34 +08005171 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005172 }
5173
5174 /**
5175 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wongb393d282019-06-12 17:46:15 +00005176 * information, e.g underlying ifaces.
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005177 */
junyulai62d35f72021-01-23 09:46:34 +08005178 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005179 if (!nai.isVPN()) return null;
5180
5181 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005182 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5183 // the underlyingNetworks list.
5184 if (underlyingNetworks == null) {
James Mattisf61f7be2021-01-31 17:06:19 -08005185 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5186 nai.networkCapabilities.getOwnerUid());
Benedict Wongb98e0692019-06-12 17:46:31 +00005187 if (defaultNai != null) {
Benedict Wongb393d282019-06-12 17:46:15 +00005188 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005189 }
5190 }
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005191
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005192 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005193
5194 List<String> interfaces = new ArrayList<>();
5195 for (Network network : underlyingNetworks) {
5196 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5197 if (underlyingNai == null) continue;
5198 LinkProperties lp = underlyingNai.linkProperties;
5199 for (String iface : lp.getAllInterfaceNames()) {
5200 if (!TextUtils.isEmpty(iface)) {
5201 interfaces.add(iface);
Benedict Wongb393d282019-06-12 17:46:15 +00005202 }
5203 }
Benedict Wongb393d282019-06-12 17:46:15 +00005204 }
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005205
5206 if (interfaces.isEmpty()) return null;
5207
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005208 // Must be non-null or NetworkStatsService will crash.
5209 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5210 // tun or ipsec interface is created.
junyulai62d35f72021-01-23 09:46:34 +08005211 // TODO: Remove this check.
junyulaibd7f3cd2021-01-23 01:09:11 +08005212 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittidb20f892020-11-17 15:58:21 +09005213
junyulai62d35f72021-01-23 09:46:34 +08005214 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5215 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tongae7e9fb2015-03-04 13:26:38 -08005216 }
5217
James Mattis1238af22020-12-23 16:37:26 -08005218 // TODO This needs to be the default network that applies to the NAI.
James Mattisf61f7be2021-01-31 17:06:19 -08005219 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5220 Network[] underlyingNetworks) {
5221 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005222 if (underlyingNetworks == null && defaultNetwork != null) {
5223 // null underlying networks means to track the default.
5224 underlyingNetworks = new Network[] { defaultNetwork };
5225 }
5226 return underlyingNetworks;
5227 }
5228
5229 // Returns true iff |network| is an underlying network of |nai|.
5230 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5231 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5232 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5233 if (!nai.supportsUnderlyingNetworks()) return false;
James Mattisf61f7be2021-01-31 17:06:19 -08005234 final Network[] underlying = underlyingNetworksOrDefault(
5235 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005236 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005237 }
5238
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005239 /**
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005240 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005241 *
Lorenzo Colitti220987b2020-11-09 10:32:56 +09005242 * When underlying networks change, such networks may have to update capabilities to reflect
5243 * things like the metered bit, their transports, and so on. The capabilities are calculated
5244 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005245 */
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005246 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti220987b2020-11-09 10:32:56 +09005247 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005248 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09005249 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09005250 updateCapabilitiesForNetwork(nai);
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09005251 }
5252 }
5253 }
5254
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005255 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5256 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5257 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5258 // a VPN is not up.
5259 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5260 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5261 for (UidRange range : blockedUidRanges) {
5262 if (range.contains(uid)) return true;
5263 }
5264 return false;
5265 }
5266
5267 @Override
5268 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucaslin5140e482021-03-22 11:51:27 +08005269 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005270 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5271 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5272 }
5273
5274 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5275 if (DBG) {
5276 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5277 + Arrays.toString(ranges));
5278 }
5279 // Cannot use a Set since the list of UID ranges might contain duplicates.
5280 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5281 for (int i = 0; i < ranges.length; i++) {
5282 if (requireVpn) {
5283 newVpnBlockedUidRanges.add(ranges[i]);
5284 } else {
5285 newVpnBlockedUidRanges.remove(ranges[i]);
5286 }
5287 }
5288
5289 try {
5290 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5291 } catch (RemoteException | ServiceSpecificException e) {
5292 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5293 + Arrays.toString(ranges) + "): netd command failed: " + e);
5294 }
5295
5296 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5297 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00005298 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5299 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09005300 }
5301
5302 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5303 }
5304
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07005305 @Override
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005306 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucaslin5140e482021-03-22 11:51:27 +08005307 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005308 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He729f0b42017-05-15 17:07:18 +01005309 }
5310
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005311 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5312 return mLockdownEnabled
5313 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5314 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Lee33c73e22016-01-05 18:03:46 +00005315 }
5316
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005317 private NetworkAgentInfo getLegacyLockdownNai() {
5318 if (!mLockdownEnabled) {
5319 return null;
Robin Lee33c73e22016-01-05 18:03:46 +00005320 }
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005321 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005322 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5323 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Lee33c73e22016-01-05 18:03:46 +00005324
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005325 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005326 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5327 // a local variable. There is no need to make a copy because its contents cannot change.
5328 final Network[] underlying = nai.declaredUnderlyingNetworks;
5329 if (underlying == null || underlying.length != 1) {
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005330 return null;
Pavel Grafov4753f402019-01-25 08:50:06 +00005331 }
Pavel Grafov4753f402019-01-25 08:50:06 +00005332
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005333 // The legacy lockdown VPN always uses the default network.
5334 // If the VPN's underlying network is no longer the current default network, it means that
5335 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005336 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5337 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005338 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colittia0473fc2021-02-12 10:14:01 +09005339 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005340 return null;
Pavel Grafov4753f402019-01-25 08:50:06 +00005341 }
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005342
5343 return nai;
5344 };
5345
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005346 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5347 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5348 // just a DetailedState object.
Lorenzo Colitti549e9ac2021-01-15 01:29:01 +09005349 private DetailedState getLegacyLockdownState(DetailedState origState) {
5350 if (origState != DetailedState.CONNECTED) {
5351 return origState;
5352 }
5353 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5354 ? DetailedState.CONNECTING
5355 : DetailedState.CONNECTED;
Pavel Grafov4753f402019-01-25 08:50:06 +00005356 }
5357
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09005358 private void filterForLegacyLockdown(NetworkInfo ni) {
5359 if (!mLockdownEnabled || !ni.isConnected()) return;
5360 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5361 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5362 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5363 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5364 // network, this time with a state of CONNECTED.
5365 //
5366 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5367 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5368 // is not too far off the truth, since an always-on VPN, when not connected, is always
5369 // trying to reconnect.
5370 if (getLegacyLockdownNai() == null) {
5371 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5372 }
5373 }
5374
Pavel Grafov4753f402019-01-25 08:50:06 +00005375 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07005376 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen82c7e422014-09-15 15:59:36 -04005377 String action) {
paulhud70b7dd2019-08-12 16:25:11 +08005378 enforceSettingsPermission();
Hugo Benichi37d5c3c2017-06-20 14:07:59 +09005379 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5380 return;
5381 }
Paul Jensen82c7e422014-09-15 15:59:36 -04005382 final long ident = Binder.clearCallingIdentity();
5383 try {
Lorenzo Colittieb166f42016-08-22 22:36:19 +09005384 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09005385 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittieb166f42016-08-22 22:36:19 +09005386 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen82c7e422014-09-15 15:59:36 -04005387 } finally {
5388 Binder.restoreCallingIdentity(ident);
5389 }
Wink Saville89c87b92013-08-29 08:55:16 -07005390 }
Wink Saville3ade4872013-08-29 14:57:08 -07005391
Yuhao Zheng15019892013-09-09 17:00:04 -07005392 @Override
5393 public void setAirplaneMode(boolean enable) {
Edward Savage-Jones3b9fe322019-11-26 13:18:08 +01005394 enforceAirplaneModePermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07005395 final long ident = Binder.clearCallingIdentity();
5396 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07005397 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichi7f919fe2017-04-21 15:07:12 +09005398 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng82579362013-09-11 09:36:41 -07005399 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5400 intent.putExtra("state", enable);
xinhe51e77032014-11-17 11:35:01 -08005401 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng15019892013-09-09 17:00:04 -07005402 } finally {
5403 Binder.restoreCallingIdentity(ident);
5404 }
5405 }
5406
James Mattisbd275dc2021-03-13 19:27:21 -08005407 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005408 mPermissionMonitor.onUserAdded(user);
James Mattis3bf8b7a2021-03-01 17:09:11 -08005409 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5410 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5411 }
Fyodor Kupolov188d3bd2015-09-02 13:27:21 -07005412 }
5413
James Mattisbd275dc2021-03-13 19:27:21 -08005414 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005415 mPermissionMonitor.onUserRemoved(user);
Chalard Jean6bb468c2021-03-09 21:09:20 +09005416 // If there was a network preference for this user, remove it.
5417 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5418 null /* listener */);
James Mattis3bf8b7a2021-03-01 17:09:11 -08005419 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5420 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5421 }
junyulaib56dc512020-08-28 13:44:33 +08005422 }
5423
James Mattisbd275dc2021-03-13 19:27:21 -08005424 private void onPackageChanged(@NonNull final String packageName) {
5425 // This is necessary in case a package is added or removed, but also when it's replaced to
5426 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5427 // as one in the preferences, then it should follow the same routing as that other package,
5428 // which means updating the rules is never to be needed in this case (whether it joins or
5429 // leaves a UID with a preference).
5430 if (isMappedInOemNetworkPreference(packageName)) {
5431 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5432 }
5433 }
5434
5435 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerccae0d32013-06-14 11:16:51 -07005436 @Override
5437 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti37d17e62021-02-15 09:36:55 +09005438 ensureRunningOnConnectivityServiceThread();
Chad Brubakerccae0d32013-06-14 11:16:51 -07005439 final String action = intent.getAction();
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005440 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaib56dc512020-08-28 13:44:33 +08005441
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005442 // User should be filled for below intents, check the existence.
5443 if (user == null) {
5444 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5445 return;
5446 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07005447
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005448 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005449 onUserAdded(user);
Fyodor Kupolov188d3bd2015-09-02 13:27:21 -07005450 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti0e9d2102021-02-16 15:42:21 +09005451 onUserRemoved(user);
Lorenzo Colitti0dd4b6f2021-02-04 17:32:07 +09005452 } else {
junyulaib56dc512020-08-28 13:44:33 +08005453 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerccae0d32013-06-14 11:16:51 -07005454 }
5455 }
5456 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07005457
James Mattisbd275dc2021-03-13 19:27:21 -08005458 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5459 @Override
5460 public void onReceive(Context context, Intent intent) {
5461 ensureRunningOnConnectivityServiceThread();
5462 switch (intent.getAction()) {
5463 case Intent.ACTION_PACKAGE_ADDED:
5464 case Intent.ACTION_PACKAGE_REMOVED:
5465 case Intent.ACTION_PACKAGE_REPLACED:
5466 onPackageChanged(intent.getData().getSchemeSpecificPart());
5467 break;
5468 default:
5469 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5470 }
5471 }
5472 };
5473
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005474 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005475 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt948aea52014-04-11 15:53:27 -07005476
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005477 private static class NetworkProviderInfo {
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005478 public final String name;
5479 public final Messenger messenger;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005480 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005481 public final int providerId;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005482
lifr1c0d9b22021-03-10 13:58:14 +08005483 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5484 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005485 this.name = name;
5486 this.messenger = messenger;
Lorenzo Colitti94c93142020-01-10 00:40:28 +09005487 this.providerId = providerId;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005488 mDeathRecipient = deathRecipient;
5489
Remi NGUYEN VAN773d9182021-02-04 18:04:43 +09005490 if (mDeathRecipient == null) {
5491 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005492 }
5493 }
5494
Lorenzo Colittia54a1aa2020-01-07 19:36:24 +09005495 void connect(Context context, Handler handler) {
Remi NGUYEN VAN773d9182021-02-04 18:04:43 +09005496 try {
5497 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5498 } catch (RemoteException e) {
5499 mDeathRecipient.binderDied();
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09005500 }
Lorenzo Colittia54a1aa2020-01-07 19:36:24 +09005501 }
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005502 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005503
James Mattis3f93a312020-11-12 15:53:42 -08005504 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5505 for (int i = 0; i < requests.size(); i++) {
5506 ensureNetworkRequestHasType(requests.get(i));
5507 }
5508 }
5509
Lorenzo Colitticef9c492016-07-05 01:22:13 +09005510 private void ensureNetworkRequestHasType(NetworkRequest request) {
5511 if (request.type == NetworkRequest.Type.NONE) {
5512 throw new IllegalArgumentException(
5513 "All NetworkRequests in ConnectivityService must have a type");
5514 }
5515 }
5516
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005517 /**
5518 * Tracks info about the requester.
James Mattis08131f32020-12-13 16:28:14 -08005519 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005520 */
James Mattisf8eb49a2020-11-15 15:04:40 -08005521 @VisibleForTesting
5522 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattis8af2d602020-12-20 11:09:58 -08005523 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5524 // single NetworkRequest in mRequests.
James Mattis7835f742020-11-03 15:54:33 -08005525 final List<NetworkRequest> mRequests;
James Mattis7835f742020-11-03 15:54:33 -08005526
James Mattis622428c2020-12-02 14:12:41 -08005527 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5528 void setSatisfier(
5529 @Nullable final NetworkAgentInfo satisfier,
5530 @Nullable final NetworkRequest activeRequest) {
5531 mSatisfier = satisfier;
5532 mActiveRequest = activeRequest;
5533 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005534
James Mattis1238af22020-12-23 16:37:26 -08005535 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09005536 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeane8cf3bf2019-11-05 15:07:09 +09005537 @Nullable
James Mattis622428c2020-12-02 14:12:41 -08005538 private NetworkAgentInfo mSatisfier;
5539 NetworkAgentInfo getSatisfier() {
5540 return mSatisfier;
5541 }
5542
5543 // The request in mRequests assigned to a network agent. This is null if none of the
5544 // requests in mRequests can be satisfied. This member has the constraint of only being
5545 // accessible on the handler thread.
5546 @Nullable
5547 private NetworkRequest mActiveRequest;
5548 NetworkRequest getActiveRequest() {
5549 return mActiveRequest;
5550 }
5551
Jeremy Joslin94c30992014-11-05 10:32:09 -08005552 final PendingIntent mPendingIntent;
Jeremy Joslinb9846d02014-12-03 17:15:28 -08005553 boolean mPendingIntentSent;
James Mattis6e6fabf2021-01-10 14:24:24 -08005554 @Nullable
5555 final Messenger mMessenger;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005556
5557 // Information about the caller that caused this object to be created.
James Mattis6e6fabf2021-01-10 14:24:24 -08005558 @Nullable
Jeremy Joslin94c30992014-11-05 10:32:09 -08005559 private final IBinder mBinder;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005560 final int mPid;
5561 final int mUid;
Roshan Pius7992afd2020-12-22 15:10:42 -08005562 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusc97d8062020-12-17 14:53:09 -08005563 @Nullable
5564 final String mCallingAttributionTag;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005565
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005566 // Counter keeping track of this NRI.
5567 final PerUidCounter mPerUidCounter;
5568
Lorenzo Colittif2514122021-03-12 22:50:57 +09005569 // Effective UID of this request. This is different from mUid when a privileged process
5570 // files a request on behalf of another UID. This UID is used to determine blocked status,
5571 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5572 // maximum limit of registered callbacks per UID.
5573 final int mAsUid;
5574
James Mattise494cbb2021-02-09 18:18:28 -08005575 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5576 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5577 // maintained for keying off of. This is only a concern when the original nri
5578 // mNetworkRequests changes which happens currently for apps that register callbacks to
5579 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5580 // that match the per-app default nri that currently tracks the calling app's uid so that
5581 // callbacks are fired at the appropriate time. When the callbacks fire,
5582 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5583 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5584 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5585 @NonNull
5586 private final NetworkRequest mNetworkRequestForCallback;
5587 NetworkRequest getNetworkRequestForCallback() {
5588 return mNetworkRequestForCallback;
5589 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005590
James Mattis1238af22020-12-23 16:37:26 -08005591 /**
5592 * Get the list of UIDs this nri applies to.
5593 */
5594 @NonNull
5595 private Set<UidRange> getUids() {
5596 // networkCapabilities.getUids() returns a defensive copy.
5597 // multilayer requests will all have the same uids so return the first one.
Chiachang Wangd5034c72021-02-22 18:36:38 +08005598 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5599 return (null == uids) ? new ArraySet<>() : uids;
James Mattis1238af22020-12-23 16:37:26 -08005600 }
5601
Lorenzo Colittif2514122021-03-12 22:50:57 +09005602 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5603 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5604 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
James Mattis6e6fabf2021-01-10 14:24:24 -08005605 }
5606
Lorenzo Colittif2514122021-03-12 22:50:57 +09005607 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattise494cbb2021-02-09 18:18:28 -08005608 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5609 @Nullable String callingAttributionTag) {
5610 ensureAllNetworkRequestsHaveType(r);
James Mattis7835f742020-11-03 15:54:33 -08005611 mRequests = initializeRequests(r);
James Mattise494cbb2021-02-09 18:18:28 -08005612 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005613 mPendingIntent = pi;
James Mattis6e6fabf2021-01-10 14:24:24 -08005614 mMessenger = null;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005615 mBinder = null;
5616 mPid = getCallingPid();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005617 mUid = mDeps.getCallingUid();
Lorenzo Colittif2514122021-03-12 22:50:57 +09005618 mAsUid = asUid;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005619 mPerUidCounter = getRequestCounter(this);
5620 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005621 /**
5622 * Location sensitive data not included in pending intent. Only included in
5623 * {@link NetworkCallback}.
5624 */
5625 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusc97d8062020-12-17 14:53:09 -08005626 mCallingAttributionTag = callingAttributionTag;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005627 }
5628
Lorenzo Colittif2514122021-03-12 22:50:57 +09005629 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius7992afd2020-12-22 15:10:42 -08005630 @Nullable final IBinder binder,
5631 @NetworkCallback.Flag int callbackFlags,
5632 @Nullable String callingAttributionTag) {
Lorenzo Colittif2514122021-03-12 22:50:57 +09005633 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5634 callingAttributionTag);
James Mattis6e6fabf2021-01-10 14:24:24 -08005635 }
5636
Lorenzo Colittif2514122021-03-12 22:50:57 +09005637 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattise494cbb2021-02-09 18:18:28 -08005638 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius7992afd2020-12-22 15:10:42 -08005639 @Nullable final IBinder binder,
5640 @NetworkCallback.Flag int callbackFlags,
5641 @Nullable String callingAttributionTag) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005642 super();
James Mattise494cbb2021-02-09 18:18:28 -08005643 ensureAllNetworkRequestsHaveType(r);
James Mattis7835f742020-11-03 15:54:33 -08005644 mRequests = initializeRequests(r);
James Mattise494cbb2021-02-09 18:18:28 -08005645 mNetworkRequestForCallback = requestForCallback;
James Mattis6e6fabf2021-01-10 14:24:24 -08005646 mMessenger = m;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005647 mBinder = binder;
5648 mPid = getCallingPid();
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005649 mUid = mDeps.getCallingUid();
Lorenzo Colittif2514122021-03-12 22:50:57 +09005650 mAsUid = asUid;
Jeremy Joslin94c30992014-11-05 10:32:09 -08005651 mPendingIntent = null;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005652 mPerUidCounter = getRequestCounter(this);
5653 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005654 mCallbackFlags = callbackFlags;
Roshan Piusc97d8062020-12-17 14:53:09 -08005655 mCallingAttributionTag = callingAttributionTag;
James Mattisfdd2d3b2021-03-31 13:57:52 -07005656 linkDeathRecipient();
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005657 }
5658
James Mattise494cbb2021-02-09 18:18:28 -08005659 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5660 @NonNull final List<NetworkRequest> r) {
5661 super();
5662 ensureAllNetworkRequestsHaveType(r);
5663 mRequests = initializeRequests(r);
5664 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeand67ab4d2021-03-05 19:18:14 +09005665 final NetworkAgentInfo satisfier = nri.getSatisfier();
5666 if (null != satisfier) {
5667 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5668 // The active request is necessary to figure out what callbacks to send, in
5669 // particular then a network updates its capabilities.
5670 // As this code creates a new NRI with a new set of requests, figure out which of
5671 // the list of requests should be the active request. It is always the first
5672 // request of the list that can be satisfied by the satisfier since the order of
5673 // requests is a priority order.
5674 // Note even in the presence of a satisfier there may not be an active request,
5675 // when the satisfier is the no-service network.
5676 NetworkRequest activeRequest = null;
5677 for (final NetworkRequest candidate : r) {
5678 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5679 activeRequest = candidate;
5680 break;
5681 }
5682 }
5683 setSatisfier(satisfier, activeRequest);
5684 }
James Mattise494cbb2021-02-09 18:18:28 -08005685 mMessenger = nri.mMessenger;
5686 mBinder = nri.mBinder;
5687 mPid = nri.mPid;
5688 mUid = nri.mUid;
Lorenzo Colittif2514122021-03-12 22:50:57 +09005689 mAsUid = nri.mAsUid;
James Mattise494cbb2021-02-09 18:18:28 -08005690 mPendingIntent = nri.mPendingIntent;
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005691 mPerUidCounter = getRequestCounter(this);
5692 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius7992afd2020-12-22 15:10:42 -08005693 mCallbackFlags = nri.mCallbackFlags;
James Mattise494cbb2021-02-09 18:18:28 -08005694 mCallingAttributionTag = nri.mCallingAttributionTag;
James Mattisfdd2d3b2021-03-31 13:57:52 -07005695 linkDeathRecipient();
James Mattise494cbb2021-02-09 18:18:28 -08005696 }
5697
Lorenzo Colittif2514122021-03-12 22:50:57 +09005698 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5699 this(asUid, Collections.singletonList(r));
James Mattis6e6fabf2021-01-10 14:24:24 -08005700 }
5701
Lorenzo Colittif2514122021-03-12 22:50:57 +09005702 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5703 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
Cody Kesting0ffbf922019-12-18 10:57:50 -08005704 }
5705
James Mattisf61f7be2021-01-31 17:06:19 -08005706 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5707 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5708 // false.
5709 boolean isBeingSatisfied() {
5710 return (null != mSatisfier && null != mActiveRequest);
5711 }
5712
James Mattise4e72bb2020-11-16 16:46:28 -08005713 boolean isMultilayerRequest() {
5714 return mRequests.size() > 1;
5715 }
5716
James Mattis6e6fabf2021-01-10 14:24:24 -08005717 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5718 // Creating a defensive copy to prevent the sender from modifying the list being
5719 // reflected in the return value of this method.
5720 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis7835f742020-11-03 15:54:33 -08005721 return Collections.unmodifiableList(tempRequests);
5722 }
5723
Chalard Jean70b2d9a2021-04-01 16:41:04 +09005724 void decrementRequestCount() {
5725 mPerUidCounter.decrementCount(mUid);
5726 }
5727
James Mattisfdd2d3b2021-03-31 13:57:52 -07005728 void linkDeathRecipient() {
5729 if (null != mBinder) {
5730 try {
5731 mBinder.linkToDeath(this, 0);
5732 } catch (RemoteException e) {
5733 binderDied();
5734 }
5735 }
5736 }
5737
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005738 void unlinkDeathRecipient() {
James Mattisfdd2d3b2021-03-31 13:57:52 -07005739 if (null != mBinder) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08005740 mBinder.unlinkToDeath(this, 0);
5741 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005742 }
5743
James Mattis3f93a312020-11-12 15:53:42 -08005744 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005745 public void binderDied() {
5746 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis3f93a312020-11-12 15:53:42 -08005747 mRequests + ", " + mBinder + ")");
James Mattisc449dde2020-11-20 16:08:10 -08005748 releaseNetworkRequests(mRequests);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005749 }
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005750
James Mattis3f93a312020-11-12 15:53:42 -08005751 @Override
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005752 public String toString() {
Lorenzo Colittif2514122021-03-12 22:50:57 +09005753 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5754 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattis1238af22020-12-23 16:37:26 -08005755 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colittif2514122021-03-12 22:50:57 +09005756 + " callbackRequest: "
Chalard Jeandc974072021-03-01 22:00:20 +09005757 + mNetworkRequestForCallback.requestId
James Mattis1238af22020-12-23 16:37:26 -08005758 + " " + mRequests
Roshan Pius7992afd2020-12-22 15:10:42 -08005759 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
Roshan Piusf75ffaa2021-03-11 21:16:44 -08005760 + " callback flags: " + mCallbackFlags;
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07005761 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005762 }
5763
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09005764 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5765 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5766 if (badCapability != null) {
5767 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensen1fcbf9c2015-06-16 15:11:58 -04005768 }
5769 }
5770
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09005771 // This checks that the passed capabilities either do not request a
5772 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean058cd312018-04-11 21:09:10 +09005773 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005774 int callerPid, int callerUid, String callerPackageName) {
Chalard Jeanbd958b32020-03-18 15:58:50 +09005775 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean058cd312018-04-11 21:09:10 +09005776 throw new SecurityException("Insufficient permissions to request a specific SSID");
5777 }
paulhua9a6e2a2019-03-22 16:35:06 +08005778
5779 if (nc.hasSignalStrength()
5780 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5781 throw new SecurityException(
5782 "Insufficient permissions to request a specific signal strength");
5783 }
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005784 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong4310e452021-03-24 14:01:51 -07005785
junyulai58153cc2021-04-14 23:33:31 +08005786 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong4310e452021-03-24 14:01:51 -07005787 enforceNetworkFactoryPermission();
5788 }
Chalard Jean058cd312018-04-11 21:09:10 +09005789 }
5790
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005791 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jean4ec33bf2018-06-04 13:33:12 +09005792 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005793 synchronized (nai) {
James Mattis622428c2020-12-02 14:12:41 -08005794 // mNetworkRequests may contain the same value multiple times in case of
5795 // multilayer requests. It won't matter in this case because the thresholds
5796 // will then be the same and be deduplicated as they enter the `thresholds` set.
5797 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattis9301a9a2020-11-18 16:23:25 -08005798 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5799 for (final NetworkRequest req : nri.mRequests) {
5800 if (req.networkCapabilities.hasSignalStrength()
5801 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5802 thresholds.add(req.networkCapabilities.getSignalStrength());
5803 }
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005804 }
5805 }
5806 }
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09005807 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005808 }
5809
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005810 private void updateSignalStrengthThresholds(
5811 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005812 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005813
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09005814 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005815 String detail;
5816 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5817 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5818 } else {
5819 detail = reason;
5820 }
5821 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005822 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09005823 }
5824
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09005825 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09005826 }
5827
Etan Cohenb184cba2017-04-03 17:42:34 -07005828 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5829 if (nc == null) {
5830 return;
5831 }
5832 NetworkSpecifier ns = nc.getNetworkSpecifier();
5833 if (ns == null) {
5834 return;
5835 }
lucaslin61ad5f32021-01-22 15:15:23 +08005836 if (ns instanceof MatchAllNetworkSpecifier) {
5837 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5838 }
Etan Cohenb184cba2017-04-03 17:42:34 -07005839 }
5840
lucaslin8cf57f52019-10-22 18:27:33 +08005841 private void ensureValid(NetworkCapabilities nc) {
5842 ensureValidNetworkSpecifier(nc);
5843 if (nc.isPrivateDnsBroken()) {
5844 throw new IllegalArgumentException("Can't request broken private DNS");
5845 }
5846 }
5847
Roshan Pius7992afd2020-12-22 15:10:42 -08005848 private boolean isTargetSdkAtleast(int version, int callingUid,
5849 @NonNull String callingPackageName) {
5850 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu66797212020-12-10 23:32:32 +08005851 final PackageManager pm =
5852 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien7fae6ea2020-03-27 18:12:39 +08005853 try {
Roshan Pius7992afd2020-12-22 15:10:42 -08005854 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien7fae6ea2020-03-27 18:12:39 +08005855 if (callingVersion < version) return false;
5856 } catch (PackageManager.NameNotFoundException e) { }
5857 return true;
5858 }
5859
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005860 @Override
Lorenzo Colittib199b962021-03-12 22:48:07 +09005861 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
junyulaid1a78162021-01-11 16:53:38 +08005862 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
Roshan Pius7992afd2020-12-22 15:10:42 -08005863 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaid1a78162021-01-11 16:53:38 +08005864 @Nullable String callingAttributionTag) {
markchieneddbe2b2020-03-18 21:16:15 +08005865 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius7992afd2020-12-22 15:10:42 -08005866 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5867 callingPackageName)) {
markchien7fae6ea2020-03-27 18:12:39 +08005868 throw new SecurityException("Insufficient permissions to specify legacy type");
5869 }
markchieneddbe2b2020-03-18 21:16:15 +08005870 }
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005871 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09005872 final int callingUid = mDeps.getCallingUid();
Lorenzo Colittib199b962021-03-12 22:48:07 +09005873 // Privileged callers can track the default network of another UID by passing in a UID.
5874 if (asUid != Process.INVALID_UID) {
5875 enforceSettingsPermission();
5876 } else {
5877 asUid = callingUid;
5878 }
junyulaid1a78162021-01-11 16:53:38 +08005879 final NetworkRequest.Type reqType;
5880 try {
5881 reqType = NetworkRequest.Type.values()[reqTypeInt];
5882 } catch (ArrayIndexOutOfBoundsException e) {
5883 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5884 }
5885 switch (reqType) {
5886 case TRACK_DEFAULT:
5887 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colittib199b962021-03-12 22:48:07 +09005888 // is unused and will be replaced by ones appropriate for the UID (usually, the
5889 // calling app). This allows callers to keep track of the default network.
James Mattise494cbb2021-02-09 18:18:28 -08005890 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittib199b962021-03-12 22:48:07 +09005891 defaultNc, asUid, callingUid, callingPackageName);
junyulaid1a78162021-01-11 16:53:38 +08005892 enforceAccessPermission();
5893 break;
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005894 case TRACK_SYSTEM_DEFAULT:
5895 enforceSettingsPermission();
5896 networkCapabilities = new NetworkCapabilities(defaultNc);
5897 break;
Junyu Lai23568a42021-01-19 11:10:56 +00005898 case BACKGROUND_REQUEST:
5899 enforceNetworkStackOrSettingsPermission();
5900 // Fall-through since other checks are the same with normal requests.
junyulaid1a78162021-01-11 16:53:38 +08005901 case REQUEST:
5902 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5903 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5904 callingAttributionTag);
5905 // TODO: this is incorrect. We mark the request as metered or not depending on
5906 // the state of the app when the request is filed, but we never change the
5907 // request if the app changes network state. http://b/29964605
5908 enforceMeteredApnPolicy(networkCapabilities);
5909 break;
junyulai8cae3c72021-03-12 20:05:08 +08005910 case LISTEN_FOR_BEST:
5911 enforceAccessPermission();
5912 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5913 break;
junyulaid1a78162021-01-11 16:53:38 +08005914 default:
5915 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Klinee0aed632016-03-16 15:31:39 +09005916 }
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09005917 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09005918 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005919 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005920
junyulai8cae3c72021-03-12 20:05:08 +08005921 // Enforce FOREGROUND if the caller does not have permission to use background network.
5922 if (reqType == LISTEN_FOR_BEST) {
5923 restrictBackgroundRequestForCaller(networkCapabilities);
5924 }
5925
5926 // Set the UID range for this request to the single UID of the requester, unless the
5927 // requester has the permission to specify other UIDs.
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09005928 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5929 // are no visible methods to set the UIDs, an app could use reflection to try and get
5930 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai8cae3c72021-03-12 20:05:08 +08005931 // Also set the requester UID and package name in the request.
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08005932 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5933 callingUid, callingPackageName);
Robert Greenwaltbf23e032014-07-27 10:56:49 -07005934
Etan Cohen3985c172017-02-05 10:42:27 -08005935 if (timeoutMs < 0) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005936 throw new IllegalArgumentException("Bad timeout specified");
5937 }
lucaslin8cf57f52019-10-22 18:27:33 +08005938 ensureValid(networkCapabilities);
Etan Cohend988de62015-11-18 10:56:15 -08005939
James Mattise494cbb2021-02-09 18:18:28 -08005940 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaid1a78162021-01-11 16:53:38 +08005941 nextNetworkRequestId(), reqType);
James Mattise494cbb2021-02-09 18:18:28 -08005942 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colittib199b962021-03-12 22:48:07 +09005943 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colittif2514122021-03-12 22:50:57 +09005944 callingAttributionTag);
Erik Kline47401fa2015-07-09 18:24:03 +09005945 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005946
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005947 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5948 // copied from the default request above. (This is necessary to ensure, for example, that
5949 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5950 // changes don't alter request matching.
5951 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5952 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colittid5e9f982021-02-10 11:59:07 +09005953 throw new IllegalStateException(
5954 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti80b48bc2021-01-29 20:14:04 +09005955 + networkCapabilities + " vs. " + defaultNc);
5956 }
5957
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005958 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07005959 if (timeoutMs > 0) {
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005960 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt09e5cff2014-06-11 16:05:07 -07005961 nri), timeoutMs);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07005962 }
5963 return networkRequest;
5964 }
5965
James Mattise494cbb2021-02-09 18:18:28 -08005966 /**
5967 * Return the nri to be used when registering a network request. Specifically, this is used with
5968 * requests registered to track the default request. If there is currently a per-app default
5969 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5970 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colittif2514122021-03-12 22:50:57 +09005971 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5972 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08005973 * @param nr the network request for the nri.
5974 * @param msgr the messenger for the nri.
5975 * @param binder the binder for the nri.
5976 * @param callingAttributionTag the calling attribution tag for the nri.
5977 * @return the nri to register.
5978 */
Lorenzo Colittif2514122021-03-12 22:50:57 +09005979 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattise494cbb2021-02-09 18:18:28 -08005980 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius7992afd2020-12-22 15:10:42 -08005981 @NetworkCallback.Flag int callbackFlags,
James Mattise494cbb2021-02-09 18:18:28 -08005982 @Nullable String callingAttributionTag) {
5983 final List<NetworkRequest> requests;
5984 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
5985 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09005986 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattise494cbb2021-02-09 18:18:28 -08005987 } else {
5988 requests = Collections.singletonList(nr);
5989 }
Roshan Pius7992afd2020-12-22 15:10:42 -08005990 return new NetworkRequestInfo(
Lorenzo Colittif2514122021-03-12 22:50:57 +09005991 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattise494cbb2021-02-09 18:18:28 -08005992 }
5993
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07005994 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
5995 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti98097292015-05-14 17:28:27 +09005996 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichic4899352016-07-19 15:59:27 +09005997 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin94c30992014-11-05 10:32:09 -08005998 } else {
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07005999 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006000 }
6001 }
6002
fenglu76564332015-03-20 11:29:56 -07006003 @Override
fenglu73169332015-04-21 17:12:05 -07006004 public boolean requestBandwidthUpdate(Network network) {
fenglu76564332015-03-20 11:29:56 -07006005 enforceAccessPermission();
6006 NetworkAgentInfo nai = null;
6007 if (network == null) {
6008 return false;
6009 }
6010 synchronized (mNetworkForNetId) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006011 nai = mNetworkForNetId.get(network.getNetId());
fenglu76564332015-03-20 11:29:56 -07006012 }
6013 if (nai != null) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006014 nai.onBandwidthUpdateRequested();
Nathan Harold6179b142018-07-30 13:38:01 -07006015 synchronized (mBandwidthRequests) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006016 final int uid = mDeps.getCallingUid();
Nathan Harold6179b142018-07-30 13:38:01 -07006017 Integer uidReqs = mBandwidthRequests.get(uid);
6018 if (uidReqs == null) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006019 uidReqs = 0;
Nathan Harold6179b142018-07-30 13:38:01 -07006020 }
6021 mBandwidthRequests.put(uid, ++uidReqs);
6022 }
fenglu76564332015-03-20 11:29:56 -07006023 return true;
6024 }
6025 return false;
6026 }
6027
Felipe Lemeff760142016-06-20 16:36:29 -07006028 private boolean isSystem(int uid) {
6029 return uid < Process.FIRST_APPLICATION_UID;
6030 }
fenglu76564332015-03-20 11:29:56 -07006031
Jeremy Joslin94c30992014-11-05 10:32:09 -08006032 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006033 final int uid = mDeps.getCallingUid();
Felipe Lemeff760142016-06-20 16:36:29 -07006034 if (isSystem(uid)) {
Hugo Benichi0a28d302017-02-11 17:04:43 +09006035 // Exemption for system uid.
Felipe Lemeff760142016-06-20 16:36:29 -07006036 return;
6037 }
Hugo Benichi0a28d302017-02-11 17:04:43 +09006038 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6039 // Policy already enforced.
6040 return;
6041 }
paulhu76cf0c52020-12-24 19:47:34 +08006042 final long ident = Binder.clearCallingIdentity();
6043 try {
6044 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6045 // If UID is restricted, don't allow them to bring up metered APNs.
6046 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6047 }
6048 } finally {
6049 Binder.restoreCallingIdentity(ident);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006050 }
6051 }
6052
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006053 @Override
6054 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07006055 PendingIntent operation, @NonNull String callingPackageName,
6056 @Nullable String callingAttributionTag) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006057 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006058 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin94c30992014-11-05 10:32:09 -08006059 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmannbbf050b2020-03-26 11:50:35 -07006060 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6061 callingAttributionTag);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006062 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6d71af12015-07-08 12:49:04 +09006063 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006064 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006065 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohenb184cba2017-04-03 17:42:34 -07006066 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006067 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6068 callingUid, callingPackageName);
Etan Cohendb38d9d2017-04-03 12:17:51 -07006069
Jeremy Joslin94c30992014-11-05 10:32:09 -08006070 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006071 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006072 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6073 callingAttributionTag);
Erik Kline47401fa2015-07-09 18:24:03 +09006074 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin94c30992014-11-05 10:32:09 -08006075 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6076 nri));
6077 return networkRequest;
6078 }
6079
Jeremy Joslinb9846d02014-12-03 17:15:28 -08006080 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6081 mHandler.sendMessageDelayed(
6082 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colittie0857092021-03-12 22:39:08 +09006083 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslinb9846d02014-12-03 17:15:28 -08006084 }
6085
Jeremy Joslin94c30992014-11-05 10:32:09 -08006086 @Override
6087 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006088 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin94c30992014-11-05 10:32:09 -08006089 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colittie0857092021-03-12 22:39:08 +09006090 mDeps.getCallingUid(), 0, operation));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006091 }
6092
Lorenzo Colitti15ff2fc2015-04-22 10:44:49 +09006093 // In order to implement the compatibility measure for pre-M apps that call
6094 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6095 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6096 // This ensures it has permission to do so.
6097 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6098 if (nc == null) {
6099 return false;
6100 }
6101 int[] transportTypes = nc.getTransportTypes();
6102 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6103 return false;
6104 }
6105 try {
6106 mContext.enforceCallingOrSelfPermission(
6107 android.Manifest.permission.ACCESS_WIFI_STATE,
6108 "ConnectivityService");
6109 } catch (SecurityException e) {
6110 return false;
6111 }
6112 return true;
6113 }
6114
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006115 @Override
6116 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius7992afd2020-12-22 15:10:42 -08006117 Messenger messenger, IBinder binder,
6118 @NetworkCallback.Flag int callbackFlags,
6119 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006120 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti15ff2fc2015-04-22 10:44:49 +09006121 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6122 enforceAccessPermission();
6123 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006124
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09006125 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006126 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006127 Binder.getCallingPid(), callingUid, callingPackageName);
6128 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeana43eede2018-03-20 19:13:57 +09006129 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6130 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6131 // onLost and onAvailable callbacks when networks move in and out of the background.
6132 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6133 // can't request networks.
6134 restrictBackgroundRequestForCaller(nc);
lucaslin8cf57f52019-10-22 18:27:33 +08006135 ensureValid(nc);
Etan Cohendb38d9d2017-04-03 12:17:51 -07006136
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09006137 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006138 NetworkRequest.Type.LISTEN);
Roshan Piusc97d8062020-12-17 14:53:09 -08006139 NetworkRequestInfo nri =
Lorenzo Colittif2514122021-03-12 22:50:57 +09006140 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius7992afd2020-12-22 15:10:42 -08006141 callingAttributionTag);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09006142 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006143
6144 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6145 return networkRequest;
6146 }
6147
6148 @Override
6149 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusc97d8062020-12-17 14:53:09 -08006150 PendingIntent operation, @NonNull String callingPackageName,
6151 @Nullable String callingAttributionTag) {
Daulet Zhanguzin08334a12020-03-26 12:30:39 +00006152 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006153 final int callingUid = mDeps.getCallingUid();
Paul Jensen9ceed862015-06-17 14:15:39 -04006154 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6155 enforceAccessPermission();
6156 }
lucaslin8cf57f52019-10-22 18:27:33 +08006157 ensureValid(networkCapabilities);
Chalard Jean058cd312018-04-11 21:09:10 +09006158 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006159 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09006160 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08006161 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeane3c1bfd2018-01-10 21:19:32 +09006162
6163 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittia4505ca2016-07-01 13:19:21 +09006164 NetworkRequest.Type.LISTEN);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006165 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6166 callingAttributionTag);
Lorenzo Colittid0a7a792016-04-08 23:09:09 +09006167 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen9ceed862015-06-17 14:15:39 -04006168
6169 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006170 }
6171
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006172 /** Returns the next Network provider ID. */
6173 public final int nextNetworkProviderId() {
6174 return mNextNetworkProviderId.getAndIncrement();
6175 }
6176
James Mattisc449dde2020-11-20 16:08:10 -08006177 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
James Mattis3f93a312020-11-12 15:53:42 -08006178 for (int i = 0; i < networkRequests.size(); i++) {
6179 releaseNetworkRequest(networkRequests.get(i));
6180 }
6181 }
6182
Erik Klineaec3f5e2016-07-07 16:50:58 +09006183 @Override
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006184 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitticef9c492016-07-05 01:22:13 +09006185 ensureNetworkRequestHasType(networkRequest);
Erik Klineaec3f5e2016-07-07 16:50:58 +09006186 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colittie0857092021-03-12 22:39:08 +09006187 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006188 }
6189
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006190 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6191 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006192 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6193 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6194 // as that will throw if a duplicate provider is registered.
Aaron Huang11e9a312020-10-30 22:04:25 +08006195 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006196 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006197 return;
6198 }
6199
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006200 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6201 mNetworkProviderInfos.put(npi.messenger, npi);
6202 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006203 }
6204
6205 @Override
6206 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006207 enforceNetworkFactoryOrSettingsPermission();
Aaron Huang6a16a412021-04-09 12:06:42 +08006208 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006209 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifr1c0d9b22021-03-10 13:58:14 +08006210 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006211 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6212 return npi.providerId;
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006213 }
6214
6215 @Override
6216 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006217 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006218 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07006219 }
6220
Chalard Jean1ef1d902021-01-05 08:40:09 +09006221 @Override
Chalard Jeanb004da52021-03-22 22:44:02 +09006222 public void offerNetwork(final int providerId,
Chalard Jean1ef1d902021-01-05 08:40:09 +09006223 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6224 @NonNull final INetworkOfferCallback callback) {
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006225 Objects.requireNonNull(score);
6226 Objects.requireNonNull(caps);
6227 Objects.requireNonNull(callback);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006228 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanb004da52021-03-22 22:44:02 +09006229 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006230 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6231 }
6232
6233 @Override
6234 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6235 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6236 }
6237
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006238 private void handleUnregisterNetworkProvider(Messenger messenger) {
6239 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6240 if (npi == null) {
6241 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalte20d3ec2014-05-16 15:49:14 -07006242 return;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006243 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09006244 // Unregister all the offers from this provider
6245 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6246 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jeanb004da52021-03-22 22:44:02 +09006247 if (noi.offer.providerId == npi.providerId) {
Chalard Jean1ef1d902021-01-05 08:40:09 +09006248 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6249 toRemove.add(noi);
6250 }
6251 }
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006252 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jean1ef1d902021-01-05 08:40:09 +09006253 handleUnregisterNetworkOffer(noi);
6254 }
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006255 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt948aea52014-04-11 15:53:27 -07006256 }
6257
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006258 @Override
James Mattis08131f32020-12-13 16:28:14 -08006259 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huange5c0ba32020-04-14 13:43:49 +08006260 if (request.hasTransport(TRANSPORT_TEST)) {
6261 enforceNetworkFactoryOrTestNetworksPermission();
6262 } else {
6263 enforceNetworkFactoryPermission();
6264 }
James Mattis08131f32020-12-13 16:28:14 -08006265 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6266 if (nri != null) {
6267 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6268 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6269 mHandler.post(() -> handleReleaseNetworkRequest(
6270 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6271 }
Lorenzo Colitti92e6c272020-01-08 00:04:09 +09006272 }
6273
Paul Jensenc2569432015-02-13 14:18:39 -05006274 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6275 @GuardedBy("mNetworkForNetId")
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006276 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensenc2569432015-02-13 14:18:39 -05006277 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006278 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensenc2569432015-02-13 14:18:39 -05006279 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006280 private final NetIdManager mNetIdManager;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07006281
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006282 // NetworkAgentInfo keyed off its connecting messenger
6283 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensenc2569432015-02-13 14:18:39 -05006284 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006285 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006286
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09006287 // UID ranges for users that are currently blocked by VPNs.
6288 // This array is accessed and iterated on multiple threads without holding locks, so its
6289 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6290 // (on the handler thread).
6291 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6292
Chalard Jean1ef1d902021-01-05 08:40:09 +09006293 // Must only be accessed on the handler thread
6294 @NonNull
6295 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6296
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09006297 @GuardedBy("mBlockedAppUids")
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006298 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colitti600e9a22016-01-22 04:04:57 +09006299
Chalard Jean9d968182021-02-25 21:46:34 +09006300 // Current OEM network preferences. This object must only be written to on the handler thread.
6301 // Since it is immutable and always non-null, other threads may read it if they only care
6302 // about seeing a consistent object but not that it is current.
James Mattis6e6fabf2021-01-10 14:24:24 -08006303 @NonNull
6304 private OemNetworkPreferences mOemNetworkPreferences =
6305 new OemNetworkPreferences.Builder().build();
Chalard Jean9d968182021-02-25 21:46:34 +09006306 // Current per-profile network preferences. This object follows the same threading rules as
6307 // the OEM network preferences above.
6308 @NonNull
6309 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
James Mattis6e6fabf2021-01-10 14:24:24 -08006310
James Mattis6e4405f2021-04-06 17:07:42 -07006311 // OemNetworkPreferences activity String log entries.
6312 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6313 @NonNull
6314 private final LocalLog mOemNetworkPreferencesLogs =
6315 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6316
James Mattisbd275dc2021-03-13 19:27:21 -08006317 /**
6318 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6319 * @param packageName the package name to check existence of a mapping for.
6320 * @return true if a mapping exists, false otherwise
6321 */
6322 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6323 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6324 }
6325
James Mattis8af2d602020-12-20 11:09:58 -08006326 // The always-on request for an Internet-capable network that apps without a specific default
6327 // fall back to.
James Mattis6e6fabf2021-01-10 14:24:24 -08006328 @VisibleForTesting
Chalard Jean4deee632019-11-05 14:40:23 +09006329 @NonNull
James Mattis6e6fabf2021-01-10 14:24:24 -08006330 final NetworkRequestInfo mDefaultRequest;
James Mattis8af2d602020-12-20 11:09:58 -08006331 // Collection of NetworkRequestInfo's used for default networks.
James Mattis6e6fabf2021-01-10 14:24:24 -08006332 @VisibleForTesting
James Mattis8af2d602020-12-20 11:09:58 -08006333 @NonNull
James Mattis6e6fabf2021-01-10 14:24:24 -08006334 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand2ee6ce2018-05-18 22:02:56 +09006335
James Mattis1238af22020-12-23 16:37:26 -08006336 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6337 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6338 }
6339
6340 /**
James Mattise494cbb2021-02-09 18:18:28 -08006341 * Return the default network request currently tracking the given uid.
6342 * @param uid the uid to check.
6343 * @return the NetworkRequestInfo tracking the given uid.
6344 */
6345 @NonNull
James Mattisbd275dc2021-03-13 19:27:21 -08006346 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
James Mattise494cbb2021-02-09 18:18:28 -08006347 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6348 if (nri == mDefaultRequest) {
6349 continue;
6350 }
6351 // Checking the first request is sufficient as only multilayer requests will have more
6352 // than one request and for multilayer, all requests will track the same uids.
6353 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6354 return nri;
6355 }
6356 }
6357 return mDefaultRequest;
6358 }
6359
6360 /**
6361 * Get a copy of the network requests of the default request that is currently tracking the
6362 * given uid.
Lorenzo Colittif2514122021-03-12 22:50:57 +09006363 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6364 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08006365 * @param requestorUid the uid to check the default for.
6366 * @param requestorPackageName the requestor's package name.
6367 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6368 */
6369 @NonNull
6370 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006371 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattise494cbb2021-02-09 18:18:28 -08006372 return copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006373 getDefaultRequestTrackingUid(asUid).mRequests,
6374 asUid, requestorUid, requestorPackageName);
James Mattise494cbb2021-02-09 18:18:28 -08006375 }
6376
6377 /**
6378 * Copy the given nri's NetworkRequest collection.
6379 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colittif2514122021-03-12 22:50:57 +09006380 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6381 * when a privileged caller is tracking the default network for another uid.
James Mattise494cbb2021-02-09 18:18:28 -08006382 * @param requestorUid the uid to set on the copied collection.
6383 * @param requestorPackageName the package name to set on the copied collection.
6384 * @return the copied NetworkRequest collection.
6385 */
6386 @NonNull
6387 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006388 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6389 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattise494cbb2021-02-09 18:18:28 -08006390 final List<NetworkRequest> requests = new ArrayList<>();
6391 for (final NetworkRequest nr : requestsToCopy) {
6392 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006393 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattise494cbb2021-02-09 18:18:28 -08006394 nr.legacyType, nextNetworkRequestId(), nr.type));
6395 }
6396 return requests;
6397 }
6398
6399 @NonNull
6400 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09006401 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6402 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colittic62368f2021-03-22 02:12:04 +09006403 // These capabilities are for a TRACK_DEFAULT callback, so:
6404 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6405 // mDefaultRequest and a per-UID default request.
6406 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colittif2514122021-03-12 22:50:57 +09006407 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colittic62368f2021-03-22 02:12:04 +09006408 // not do this in the case of a privileged application.
James Mattise494cbb2021-02-09 18:18:28 -08006409 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6410 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colittif2514122021-03-12 22:50:57 +09006411 netCap.setSingleUid(asUid);
James Mattise494cbb2021-02-09 18:18:28 -08006412 restrictRequestUidsForCallerAndSetRequestorInfo(
6413 netCap, requestorUid, requestorPackageName);
6414 return netCap;
6415 }
6416
6417 /**
6418 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6419 * @param nr the network request to check for equality against.
6420 * @return the nri if one exists, null otherwise.
6421 */
6422 @Nullable
6423 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6424 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6425 if (nri.getNetworkRequestForCallback().equals(nr)) {
6426 return nri;
6427 }
6428 }
6429 return null;
6430 }
6431
6432 /**
6433 * Check if an nri is currently being managed by per-app default networking.
6434 * @param nri the nri to check.
6435 * @return true if this nri is currently being managed by per-app default networking.
6436 */
6437 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6438 // nri.mRequests.get(0) is only different from the original request filed in
6439 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6440 // functionality therefore if these two don't match, it means this particular nri is
6441 // currently being managed by a per-app default.
6442 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6443 }
6444
6445 /**
James Mattis1238af22020-12-23 16:37:26 -08006446 * Determine if an nri is a managed default request that disallows default networking.
6447 * @param nri the request to evaluate
6448 * @return true if device-default networking is disallowed
6449 */
6450 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6451 // Check if this nri is a managed default that supports the default network at its
6452 // lowest priority request.
6453 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6454 final NetworkCapabilities lowestPriorityNetCap =
6455 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6456 return isPerAppDefaultRequest(nri)
6457 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6458 lowestPriorityNetCap));
6459 }
6460
Erik Kline74d68ef2015-04-30 12:58:40 +09006461 // Request used to optionally keep mobile data active even when higher
6462 // priority networks like Wi-Fi are active.
6463 private final NetworkRequest mDefaultMobileDataRequest;
6464
Leif Hendrik Wildena6521802018-05-02 12:05:24 -07006465 // Request used to optionally keep wifi data active even when higher
6466 // priority networks like ethernet are active.
6467 private final NetworkRequest mDefaultWifiRequest;
6468
Tomasz Wasilczyk2793ab92020-12-14 13:42:51 -08006469 // Request used to optionally keep vehicle internal network always active
6470 private final NetworkRequest mDefaultVehicleRequest;
6471
James Mattis1238af22020-12-23 16:37:26 -08006472 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6473 // network with no service. This NAI should never be matched against, nor should any public API
6474 // ever return the associated network. For this reason, this NAI is not in the list of available
6475 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6476 // default requests that don't support using the device default network which will ultimately
6477 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6478 @VisibleForTesting
6479 final NetworkAgentInfo mNoServiceNetwork;
6480
Chalard Jean1bc77a92021-02-04 13:12:59 +09006481 // The NetworkAgentInfo currently satisfying the default request, if any.
6482 private NetworkAgentInfo getDefaultNetwork() {
6483 return mDefaultRequest.mSatisfier;
Lorenzo Colitti8db934a2014-11-28 11:21:30 +09006484 }
6485
James Mattisf61f7be2021-01-31 17:06:19 -08006486 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6487 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6488 // Currently, all network requests will have the same uids therefore checking the first
6489 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wangd5034c72021-02-22 18:36:38 +08006490 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattisf61f7be2021-01-31 17:06:19 -08006491 if (null == uids) {
6492 continue;
6493 }
6494 for (final UidRange range : uids) {
6495 if (range.contains(uid)) {
6496 return nri.getSatisfier();
6497 }
6498 }
6499 }
6500 return getDefaultNetwork();
6501 }
6502
Varun Anand273f9002019-02-06 10:13:38 -08006503 @Nullable
6504 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6505 return nai != null ? nai.network : null;
6506 }
6507
6508 private void ensureRunningOnConnectivityServiceThread() {
6509 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6510 throw new IllegalStateException(
6511 "Not running on ConnectivityService thread: "
6512 + Thread.currentThread().getName());
6513 }
6514 }
6515
Chalard Jean8cc4e872019-04-10 23:07:55 +09006516 @VisibleForTesting
Chalard Jean1bc77a92021-02-04 13:12:59 +09006517 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6518 return nai == getDefaultNetwork();
Robert Greenwaltb264cd82014-08-06 21:32:18 -07006519 }
6520
Chalard Jean44689aa2018-05-02 21:14:54 +09006521 /**
6522 * Register a new agent with ConnectivityService to handle a network.
6523 *
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006524 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean44689aa2018-05-02 21:14:54 +09006525 * @param networkInfo the initial info associated with this network. It can be updated later :
6526 * see {@link #updateNetworkInfo}.
6527 * @param linkProperties the initial link properties of this network. They can be updated
6528 * later : see {@link #updateLinkProperties}.
6529 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean945f2482019-12-12 13:56:13 +09006530 * later : see {@link #updateCapabilities}.
Chalard Jeandd753522020-12-21 18:36:52 +09006531 * @param initialScore the initial score of the network. See
Chalard Jean44689aa2018-05-02 21:14:54 +09006532 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colitticf595362020-01-12 22:28:37 +09006533 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colitti94c93142020-01-10 00:40:28 +09006534 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeana973c7a2019-12-13 19:47:12 +09006535 * @return the network created for this agent.
Chalard Jean44689aa2018-05-02 21:14:54 +09006536 */
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006537 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean44689aa2018-05-02 21:14:54 +09006538 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeandd753522020-12-21 18:36:52 +09006539 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6540 int providerId) {
Lorenzo Colitti83d06562021-01-18 14:15:17 +09006541 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6542 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6543 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jeandd753522020-12-21 18:36:52 +09006544 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colitti83d06562021-01-18 14:15:17 +09006545 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006546 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6547 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006548 } else {
6549 enforceNetworkFactoryPermission();
6550 }
6551
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09006552 final int uid = mDeps.getCallingUid();
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006553 final long token = Binder.clearCallingIdentity();
6554 try {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006555 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeandd753522020-12-21 18:36:52 +09006556 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006557 } finally {
6558 Binder.restoreCallingIdentity(token);
6559 }
6560 }
6561
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006562 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006563 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeandd753522020-12-21 18:36:52 +09006564 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6565 int uid) {
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006566 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006567 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6568 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6569 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6570 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006571 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
Chalard Jeanb5b172f2020-03-09 21:25:37 +09006572 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006573
Rubin Xu57b437a2017-09-05 18:40:49 +01006574 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006575
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09006576 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006577 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VANe9741e42019-06-13 16:12:02 +09006578 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jeande419812020-03-04 17:45:08 +09006579 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jeane634b282021-03-05 23:07:53 +09006580 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6581 mQosCallbackTracker, mDeps);
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006582
6583 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006584 processCapabilitiesFromAgent(nai, nc);
Chalard Jean8ffefba2019-11-22 22:39:56 +09006585 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006586 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6587
Chalard Jeandf2478a2018-04-26 16:16:10 +09006588 final String extraInfo = networkInfo.getExtraInfo();
6589 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jeanbd958b32020-03-18 15:58:50 +09006590 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt721f2372014-08-27 14:34:02 -07006591 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti4b1cd162020-11-26 23:42:25 +09006592 mDeps.getNetworkStack().makeNetworkMonitor(
6593 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006594 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6595 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006596 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006597 // registration.
Chalard Jeana973c7a2019-12-13 19:47:12 +09006598 return nai.network;
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006599 }
6600
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006601 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6602 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006603 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006604 mNetworkAgentInfos.add(nai);
Paul Jensenc2569432015-02-13 14:18:39 -05006605 synchronized (mNetworkForNetId) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006606 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensenc2569432015-02-13 14:18:39 -05006607 }
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006608
6609 try {
6610 networkMonitor.start();
6611 } catch (RemoteException e) {
Chiachang Wang619a8a22019-04-24 21:44:05 +08006612 e.rethrowAsRuntimeException();
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09006613 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09006614 nai.notifyRegistered();
Erik Kline79371012018-03-04 21:01:01 +09006615 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline79371012018-03-04 21:01:01 +09006616 updateNetworkInfo(nai, networkInfo);
6617 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006618 }
6619
Chalard Jean1ef1d902021-01-05 08:40:09 +09006620 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6621 @NonNull public final NetworkOffer offer;
6622
6623 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6624 this.offer = offer;
6625 }
6626
6627 @Override
6628 public void binderDied() {
6629 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6630 }
6631 }
6632
Chalard Jean7618f1a2021-03-24 14:31:38 +09006633 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6634 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6635 if (npi.providerId == providerId) return true;
6636 }
6637 return false;
6638 }
6639
Chalard Jean1ef1d902021-01-05 08:40:09 +09006640 /**
6641 * Register or update a network offer.
6642 * @param newOffer The new offer. If the callback member is the same as an existing
6643 * offer, it is an update of that offer.
6644 */
6645 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6646 ensureRunningOnConnectivityServiceThread();
Chalard Jean7618f1a2021-03-24 14:31:38 +09006647 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6648 // This may actually happen if a provider updates its score or registers and then
6649 // immediately unregisters. The offer would still be in the handler queue, but the
6650 // provider would have been removed.
6651 if (DBG) log("Received offer from an unregistered provider");
6652 return;
6653 }
Chalard Jean1ef1d902021-01-05 08:40:09 +09006654 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6655 if (null != existingOffer) {
6656 handleUnregisterNetworkOffer(existingOffer);
6657 newOffer.migrateFrom(existingOffer.offer);
6658 }
6659 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6660 try {
Chalard Jeanb004da52021-03-22 22:44:02 +09006661 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006662 } catch (RemoteException e) {
6663 noi.binderDied();
6664 return;
6665 }
6666 mNetworkOffers.add(noi);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09006667 issueNetworkNeeds(noi);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006668 }
6669
6670 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6671 ensureRunningOnConnectivityServiceThread();
6672 mNetworkOffers.remove(noi);
Chalard Jeanb004da52021-03-22 22:44:02 +09006673 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jean1ef1d902021-01-05 08:40:09 +09006674 }
6675
6676 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6677 @NonNull final INetworkOfferCallback callback) {
6678 ensureRunningOnConnectivityServiceThread();
6679 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jeanf1364432021-04-08 17:37:36 +09006680 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jean1ef1d902021-01-05 08:40:09 +09006681 }
6682 return null;
6683 }
6684
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006685 /**
6686 * Called when receiving LinkProperties directly from a NetworkAgent.
6687 * Stores into |nai| any data coming from the agent that might also be written to the network's
6688 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6689 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti3c75ca82020-12-02 13:58:47 +09006690 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09006691 */
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006692 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6693 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colitti54fb93f2020-04-01 22:25:16 +09006694 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalom492febb2021-01-11 18:45:34 -08006695 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09006696 }
6697
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006698 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006699 @NonNull LinkProperties oldLp) {
Serik Beketayev284cb872020-12-07 22:43:07 -08006700 int netId = networkAgent.network.getNetId();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006701
Lorenzo Colittifff75392020-04-01 20:16:30 +09006702 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6703 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6704 // the LinkProperties for the network are accurate.
Lorenzo Colitti07f10202019-01-08 14:43:37 +09006705 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti667da282014-09-20 13:47:47 +09006706
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006707 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006708
6709 // update filtering rules, need to happen after the interface update so netd knows about the
6710 // new interface (the interface name -> index map becomes initialized)
6711 updateVpnFiltering(newLp, oldLp, networkAgent);
6712
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006713 updateMtu(newLp, oldLp);
6714 // TODO - figure out what to do for clat
6715// for (LinkProperties lp : newLp.getStackedLinks()) {
6716// updateMtu(lp, null);
6717// }
Chalard Jean1bc77a92021-02-04 13:12:59 +09006718 if (isDefaultNetwork(networkAgent)) {
lucaslin589964b2018-11-28 19:27:52 +08006719 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6720 }
Lorenzo Colittiaa4f1f62014-11-28 20:07:46 +09006721
Erik Kline3d4ed152016-04-05 13:30:49 +09006722 updateRoutes(newLp, oldLp, netId);
6723 updateDnses(newLp, oldLp, netId);
dalykf4977492018-03-05 12:42:22 -05006724 // Make sure LinkProperties represents the latest private DNS status.
6725 // This does not need to be done before updateDnses because the
6726 // LinkProperties are not the source of the private DNS configuration.
6727 // updateDnses will fetch the private DNS configuration from DnsManager.
6728 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colittiaa4f1f62014-11-28 20:07:46 +09006729
Chalard Jean1bc77a92021-02-04 13:12:59 +09006730 if (isDefaultNetwork(networkAgent)) {
Paul Jensen12131352014-12-10 15:12:18 -05006731 handleApplyDefaultProxy(newLp.getHttpProxy());
6732 } else {
Chalard Jean4ec33bf2018-06-04 13:33:12 +09006733 updateProxy(newLp, oldLp);
Paul Jensen12131352014-12-10 15:12:18 -05006734 }
Valentin Iftimea039e572019-09-24 13:32:13 +02006735
6736 updateWakeOnLan(newLp);
6737
Hai Shalom492febb2021-01-11 18:45:34 -08006738 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6739 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6740 // does, it needs to be merged here.
6741 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6742 networkAgent.capportApiData));
Remi NGUYEN VAN6cfa0142019-12-12 12:57:11 +09006743
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07006744 // TODO - move this check to cover the whole function
6745 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanf2f75592018-05-23 09:07:51 +09006746 synchronized (networkAgent) {
6747 networkAgent.linkProperties = newLp;
6748 }
Lorenzo Colitti714b7862019-02-19 13:21:56 +09006749 // Start or stop DNS64 detection and 464xlat according to network state.
6750 networkAgent.clatd.update();
Jeff Davidson9804c892016-01-20 11:35:38 -08006751 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VAN3b1d8b42020-05-10 16:11:11 +09006752 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6753 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin34cd3942018-11-28 12:51:55 +08006754 if (networkAgent.everConnected) {
6755 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6756 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07006757 }
Lorenzo Colittid1039d12015-06-15 14:29:22 +09006758
6759 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen7d854042014-05-13 11:44:01 -04006760 }
6761
Hai Shalom492febb2021-01-11 18:45:34 -08006762 /**
6763 * @param naData captive portal data from NetworkAgent
6764 * @param apiData captive portal data from capport API
6765 */
6766 @Nullable
6767 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6768 CaptivePortalData apiData) {
6769 if (naData == null || apiData == null) {
6770 return naData == null ? apiData : naData;
6771 }
6772 final CaptivePortalData.Builder captivePortalBuilder =
6773 new CaptivePortalData.Builder(naData);
6774
6775 if (apiData.isCaptive()) {
6776 captivePortalBuilder.setCaptive(true);
6777 }
6778 if (apiData.isSessionExtendable()) {
6779 captivePortalBuilder.setSessionExtendable(true);
6780 }
6781 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6782 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6783 // otherwise data would be inconsistent. Prefer the capport API info if present,
6784 // as it can generally be refreshed more often.
6785 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6786 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6787 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6788 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6789 // No source has time / bytes remaining information: surface the newest refresh time
6790 // for other fields
6791 captivePortalBuilder.setRefreshTime(
6792 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6793 }
6794
Hai Shalom7fcd18a2021-02-04 19:34:06 -08006795 // Prioritize the user portal URL from the network agent if the source is authenticated.
6796 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6797 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6798 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6799 apiData.getUserPortalUrlSource());
Hai Shalom492febb2021-01-11 18:45:34 -08006800 }
Hai Shalom7fcd18a2021-02-04 19:34:06 -08006801 // Prioritize the venue information URL from the network agent if the source is
6802 // authenticated.
6803 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6804 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6805 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6806 apiData.getVenueInfoUrlSource());
Hai Shalom492febb2021-01-11 18:45:34 -08006807 }
6808 return captivePortalBuilder.build();
6809 }
6810
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006811 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean73d9db72018-06-04 16:52:49 +09006812 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006813 // marks on unsupported interfaces is harmless.
6814 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6815 return;
6816 }
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006817
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09006818 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6819 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6820
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006821 // Mask/mark of zero will not detect anything interesting.
6822 // Don't install rules unless both values are nonzero.
6823 if (mark == 0 || mask == 0) {
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006824 return;
6825 }
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006826
6827 final String prefix = "iface:" + iface;
6828 try {
6829 if (add) {
Luke Huang358aa262018-09-27 19:33:11 +08006830 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006831 } else {
Luke Huang358aa262018-09-27 19:33:11 +08006832 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006833 }
6834 } catch (Exception e) {
6835 loge("Exception modifying wakeup packet monitoring: " + e);
6836 }
6837
Joel Scherpelzbce9c842017-05-22 13:47:41 +09006838 }
6839
Chalard Jeane5550312019-11-19 19:03:53 +09006840 private void updateInterfaces(final @Nullable LinkProperties newLp,
6841 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09006842 final @NonNull NetworkCapabilities caps) {
Chalard Jeane5550312019-11-19 19:03:53 +09006843 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu8cb82d22017-08-22 16:35:52 +01006844 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6845 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jeane5550312019-11-19 19:03:53 +09006846 if (!interfaceDiff.added.isEmpty()) {
Chalard Jeane5550312019-11-19 19:03:53 +09006847 for (final String iface : interfaceDiff.added) {
6848 try {
6849 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wanga93ddb22020-10-26 14:23:52 +08006850 mNetd.networkAddInterface(netId, iface);
Chalard Jeane5550312019-11-19 19:03:53 +09006851 wakeupModifyInterface(iface, caps, true);
Aaron Huange044c462020-10-27 03:36:19 +08006852 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6853 caps.getTransportTypes());
Chalard Jeane5550312019-11-19 19:03:53 +09006854 } catch (Exception e) {
lucaslin3967e5f2021-04-01 19:17:08 +08006855 logw("Exception adding interface: " + e);
Chalard Jeane5550312019-11-19 19:03:53 +09006856 }
Paul Jensen6b197532014-04-28 10:33:11 -04006857 }
6858 }
Chalard Jeane5550312019-11-19 19:03:53 +09006859 for (final String iface : interfaceDiff.removed) {
Paul Jensen6b197532014-04-28 10:33:11 -04006860 try {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006861 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelzd18b92c2017-06-08 15:35:21 +09006862 wakeupModifyInterface(iface, caps, false);
Chiachang Wanga93ddb22020-10-26 14:23:52 +08006863 mNetd.networkRemoveInterface(netId, iface);
Paul Jensen6b197532014-04-28 10:33:11 -04006864 } catch (Exception e) {
6865 loge("Exception removing interface: " + e);
6866 }
6867 }
6868 }
6869
Tyler Weara8978d42019-12-05 14:55:30 -08006870 // TODO: move to frameworks/libs/net.
6871 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6872 final String nextHop;
6873
6874 switch (route.getType()) {
6875 case RouteInfo.RTN_UNICAST:
6876 if (route.hasGateway()) {
6877 nextHop = route.getGateway().getHostAddress();
6878 } else {
6879 nextHop = INetd.NEXTHOP_NONE;
6880 }
6881 break;
6882 case RouteInfo.RTN_UNREACHABLE:
6883 nextHop = INetd.NEXTHOP_UNREACHABLE;
6884 break;
6885 case RouteInfo.RTN_THROW:
6886 nextHop = INetd.NEXTHOP_THROW;
6887 break;
6888 default:
6889 nextHop = INetd.NEXTHOP_NONE;
6890 break;
6891 }
6892
6893 final RouteInfoParcel rip = new RouteInfoParcel();
6894 rip.ifName = route.getInterface();
6895 rip.destination = route.getDestination().toString();
6896 rip.nextHop = nextHop;
6897 rip.mtu = route.getMtu();
6898
6899 return rip;
6900 }
6901
Paul Jensen1b79a592014-08-06 15:51:33 -04006902 /**
6903 * Have netd update routes from oldLp to newLp.
6904 * @return true if routes changed between oldLp and newLp
6905 */
6906 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weara8978d42019-12-05 14:55:30 -08006907 // compare the route diff to determine which routes have been updated
junyulai21c26da2020-03-23 20:49:43 +08006908 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
6909 new CompareOrUpdateResult<>(
6910 oldLp != null ? oldLp.getAllRoutes() : null,
6911 newLp != null ? newLp.getAllRoutes() : null,
6912 (r) -> r.getRouteKey());
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006913
6914 // add routes before removing old in case it helps with continuous connectivity
6915
Chalard Jean73d9db72018-06-04 16:52:49 +09006916 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006917 for (RouteInfo route : routeDiff.added) {
6918 if (route.hasGateway()) continue;
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006919 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006920 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006921 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006922 } catch (Exception e) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006923 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weara8978d42019-12-05 14:55:30 -08006924 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt721f2372014-08-27 14:34:02 -07006925 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006926 }
6927 }
6928 for (RouteInfo route : routeDiff.added) {
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09006929 if (!route.hasGateway()) continue;
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006930 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006931 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006932 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006933 } catch (Exception e) {
Robert Greenwalt721f2372014-08-27 14:34:02 -07006934 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weara8978d42019-12-05 14:55:30 -08006935 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt721f2372014-08-27 14:34:02 -07006936 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006937 }
6938 }
6939
6940 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09006941 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006942 try {
Tyler Weara8978d42019-12-05 14:55:30 -08006943 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006944 } catch (Exception e) {
Tyler Weara8978d42019-12-05 14:55:30 -08006945 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006946 }
6947 }
Tyler Weara8978d42019-12-05 14:55:30 -08006948
6949 for (RouteInfo route : routeDiff.updated) {
6950 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
6951 try {
6952 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
6953 } catch (Exception e) {
6954 loge("Exception in networkUpdateRouteParcel: " + e);
6955 }
6956 }
6957 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
6958 || !routeDiff.updated.isEmpty();
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006959 }
Erik Kline04270062015-06-17 13:19:54 +09006960
Erik Kline3d4ed152016-04-05 13:30:49 +09006961 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
6962 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
6963 return; // no updating necessary
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07006964 }
Erik Kline3d4ed152016-04-05 13:30:49 +09006965
Erik Klinec06d4f92018-01-11 21:07:29 +09006966 if (DBG) {
6967 final Collection<InetAddress> dnses = newLp.getDnsServers();
6968 log("Setting DNS servers for network " + netId + " to " + dnses);
6969 }
Erik Kline3d4ed152016-04-05 13:30:49 +09006970 try {
chenbruce2e6b79f2020-02-20 14:28:31 +08006971 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce2e6b79f2020-02-20 14:28:31 +08006972 mDnsManager.flushVmDnsCache();
Erik Kline3d4ed152016-04-05 13:30:49 +09006973 } catch (Exception e) {
Pierre Imai5b5fe392016-04-28 17:00:04 +09006974 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline3d4ed152016-04-05 13:30:49 +09006975 }
Erik Klinebd18f302017-04-07 15:29:29 +09006976 }
6977
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006978 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
6979 NetworkAgentInfo nai) {
6980 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
6981 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
6982 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
6983 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
6984
6985 if (!wasFiltering && !needsFiltering) {
6986 // Nothing to do.
6987 return;
6988 }
6989
6990 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
6991 // Nothing changed.
6992 return;
6993 }
6994
Chiachang Wangd5034c72021-02-22 18:36:38 +08006995 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb3347b2020-01-17 17:54:27 -08006996 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00006997 // TODO: this create a window of opportunity for apps to receive traffic between the time
6998 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey0d585432020-09-11 15:10:20 -06006999 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007000 // old rules are being removed.
7001 if (wasFiltering) {
7002 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7003 }
7004 if (needsFiltering) {
7005 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7006 }
7007 }
7008
Valentin Iftimea039e572019-09-24 13:32:13 +02007009 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09007010 if (mWolSupportedInterfaces == null) {
7011 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09007012 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09007013 }
Valentin Iftimea039e572019-09-24 13:32:13 +02007014 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7015 }
7016
Luke Huang089ebf12018-08-24 20:33:16 +08007017 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007018 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang089ebf12018-08-24 20:33:16 +08007019 return INetd.PERMISSION_SYSTEM;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007020 }
7021 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang089ebf12018-08-24 20:33:16 +08007022 return INetd.PERMISSION_NETWORK;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007023 }
Luke Huang089ebf12018-08-24 20:33:16 +08007024 return INetd.PERMISSION_NONE;
Lorenzo Colitti1034b7c2016-07-28 17:14:11 +09007025 }
7026
Chalard Jeana00029d2019-12-02 18:39:29 +09007027 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7028 @NonNull final NetworkCapabilities newNc) {
7029 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7030 final int newPermission = getNetworkPermission(newNc);
7031 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7032 try {
Serik Beketayev284cb872020-12-07 22:43:07 -08007033 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wang9695da32020-10-26 19:59:31 +08007034 } catch (RemoteException | ServiceSpecificException e) {
7035 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jeana00029d2019-12-02 18:39:29 +09007036 }
7037 }
7038 }
7039
Paul Jensen783c0e02015-06-16 14:27:36 -04007040 /**
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007041 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7042 * Stores into |nai| any data coming from the agent that might also be written to the network's
7043 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7044 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti3c75ca82020-12-02 13:58:47 +09007045 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007046 */
7047 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007048 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7049 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7050 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7051 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti39b4c5b2020-12-09 18:30:52 +09007052 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7053 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7054 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7055 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7056 }
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007057 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007058 }
7059
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007060 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007061 @VisibleForTesting
Lorenzo Colitti8750be02020-12-01 01:08:37 +09007062 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007063 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattisf61f7be2021-01-31 17:06:19 -08007064 underlyingNetworks = underlyingNetworksOrDefault(
7065 agentCaps.getOwnerUid(), underlyingNetworks);
lifrc33ea4d2021-03-04 14:08:08 +08007066 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007067 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7068 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007069 // metered if any underlying is metered, or originally declared metered by the agent.
7070 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007071 boolean roaming = false; // roaming if any underlying is roaming
7072 boolean congested = false; // congested if any underlying is congested
7073 boolean suspended = true; // suspended if all underlying are suspended
7074
7075 boolean hadUnderlyingNetworks = false;
7076 if (null != underlyingNetworks) {
7077 for (Network underlyingNetwork : underlyingNetworks) {
7078 final NetworkAgentInfo underlying =
7079 getNetworkAgentInfoForNetwork(underlyingNetwork);
7080 if (underlying == null) continue;
7081
7082 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7083 hadUnderlyingNetworks = true;
7084 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VANf51b0622020-12-01 17:47:12 +09007085 transportTypes |= 1L << underlyingType;
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007086 }
7087
7088 // Merge capabilities of this underlying network. For bandwidth, assume the
7089 // worst case.
7090 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7091 underlyingCaps.getLinkDownstreamBandwidthKbps());
7092 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7093 underlyingCaps.getLinkUpstreamBandwidthKbps());
7094 // If this underlying network is metered, the VPN is metered (it may cost money
7095 // to send packets on this network).
7096 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7097 // If this underlying network is roaming, the VPN is roaming (the billing structure
7098 // is different than the usual, local one).
7099 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7100 // If this underlying network is congested, the VPN is congested (the current
7101 // condition of the network affects the performance of this network).
7102 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7103 // If this network is not suspended, the VPN is not suspended (the VPN
7104 // is able to transfer some data).
7105 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7106 }
7107 }
7108 if (!hadUnderlyingNetworks) {
7109 // No idea what the underlying networks are; assume reasonable defaults
7110 metered = true;
7111 roaming = false;
7112 congested = false;
7113 suspended = false;
7114 }
7115
lifrc33ea4d2021-03-04 14:08:08 +08007116 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007117 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7118 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7119 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7120 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7121 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7122 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
Lorenzo Colitticd6d42b2020-11-24 21:45:25 +09007123 }
7124
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007125 /**
Lorenzo Colitti72664112018-01-16 00:52:07 +09007126 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7127 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7128 * and foreground status).
Paul Jensen783c0e02015-06-16 14:27:36 -04007129 */
Remi NGUYEN VANafd75602021-01-28 15:09:22 +09007130 @NonNull
Lorenzo Colitti72664112018-01-16 00:52:07 +09007131 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi2f90b2d2017-08-16 13:19:04 +09007132 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007133 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7134 // causing a connect/teardown loop.
Lorenzo Colitti94c93142020-01-10 00:40:28 +09007135 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007136 // avoid connect/teardown loops.
Lorenzo Colitti72664112018-01-16 00:52:07 +09007137 if (nai.everConnected &&
Lorenzo Colitti6f1b5162018-05-30 16:44:47 +09007138 !nai.isVPN() &&
Lorenzo Colitti72664112018-01-16 00:52:07 +09007139 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7140 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi2f90b2d2017-08-16 13:19:04 +09007141 // does not cause any request (that is not a listen) currently matching that agent to
7142 // stop being matched by the updated agent.
Lorenzo Colitti72664112018-01-16 00:52:07 +09007143 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi8c928882017-07-25 11:40:56 +09007144 if (!TextUtils.isEmpty(diff)) {
Aaron Huang11e9a312020-10-30 22:04:25 +08007145 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi8c928882017-07-25 11:40:56 +09007146 }
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007147 }
7148
Paul Jensen783c0e02015-06-16 14:27:36 -04007149 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007150 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007151 if (nai.lastValidated) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007152 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen783c0e02015-06-16 14:27:36 -04007153 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007154 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen783c0e02015-06-16 14:27:36 -04007155 }
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007156 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007157 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen783c0e02015-06-16 14:27:36 -04007158 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007159 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen783c0e02015-06-16 14:27:36 -04007160 }
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007161 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007162 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007163 } else {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007164 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007165 }
lucaslin25a50472019-03-12 13:08:03 +08007166 if (nai.partialConnectivity) {
7167 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7168 } else {
7169 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7170 }
lucaslin8cf57f52019-10-22 18:27:33 +08007171 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007172
Chalard Jeanc212ed12020-01-15 00:49:43 +09007173 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeanfa33a752020-01-14 22:46:36 +09007174 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7175 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanc212ed12020-01-15 00:49:43 +09007176 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeanfa33a752020-01-14 22:46:36 +09007177 }
7178
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007179 if (nai.supportsUnderlyingNetworks()) {
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007180 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7181 newNc);
Lorenzo Colitti220987b2020-11-09 10:32:56 +09007182 }
7183
Lorenzo Colitti72664112018-01-16 00:52:07 +09007184 return newNc;
7185 }
7186
Lorenzo Colitti246d1762021-01-11 22:27:57 +09007187 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7188 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7189 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7190 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7191 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7192 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7193 if (prevSuspended != suspended) {
7194 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7195 // onResumed have been removed.
7196 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7197 : ConnectivityManager.CALLBACK_RESUMED);
7198 }
7199 if (prevSuspended != suspended || prevRoaming != roaming) {
7200 // updateNetworkInfo will mix in the suspended info from the capabilities and
7201 // take appropriate action for the network having possibly changed state.
7202 updateNetworkInfo(nai, nai.networkInfo);
7203 }
7204 }
7205
Lorenzo Colitti72664112018-01-16 00:52:07 +09007206 /**
7207 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7208 *
7209 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7210 * capabilities we manage and store in {@code nai}, such as validated status and captive
7211 * portal status)
7212 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7213 * potentially triggers rematches.
7214 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7215 * change.)
7216 *
7217 * @param oldScore score of the network before any of the changes that prompted us
7218 * to call this function.
7219 * @param nai the network having its capabilities updated.
7220 * @param nc the new network capabilities.
7221 */
Chalard Jeana00029d2019-12-02 18:39:29 +09007222 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7223 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti72664112018-01-16 00:52:07 +09007224 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti72664112018-01-16 00:52:07 +09007225 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jeana00029d2019-12-02 18:39:29 +09007226 updateNetworkPermissions(nai, newNc);
Chalard Jean8ffefba2019-11-22 22:39:56 +09007227 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007228
Chalard Jeana39c91c2018-01-16 18:43:05 +09007229 updateUids(nai, prevNc, newNc);
Chalard Jean1fc55292021-03-31 23:19:05 +09007230 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeana39c91c2018-01-16 18:43:05 +09007231
Lorenzo Colitti72664112018-01-16 00:52:07 +09007232 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007233 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7234 // the change we're processing can't affect any requests, it can only affect the listens
7235 // on this network. We might have been called by rematchNetworkAndRequests when a
7236 // network changed foreground state.
Chalard Jeanb9c02722019-12-09 11:50:38 +09007237 processListenRequests(nai);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007238 } else {
7239 // If the requestable capabilities have changed or the score changed, we can't have been
7240 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jean60902092019-11-07 18:54:49 +09007241 rematchAllNetworksAndRequests();
Paul Jensen25eb5fd2015-06-25 15:30:08 -04007242 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt701a5c32014-06-23 11:40:00 -07007243 }
Lorenzo Colitti246d1762021-01-11 22:27:57 +09007244 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007245
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007246 final boolean oldMetered = prevNc.isMetered();
7247 final boolean newMetered = newNc.isMetered();
7248 final boolean meteredChanged = oldMetered != newMetered;
junyulai5ab727b2018-08-07 19:50:45 +08007249
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007250 if (meteredChanged) {
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00007251 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7252 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007253 }
junyulai5ab727b2018-08-07 19:50:45 +08007254
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007255 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7256 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai5ab727b2018-08-07 19:50:45 +08007257
Lorenzo Colitti131d7c12021-01-16 00:23:46 +09007258 // Report changes that are interesting for network statistics tracking.
7259 if (meteredChanged || roamingChanged) {
7260 notifyIfacesChangedForNetworkStats();
Jeff Sharkey1a1cba82017-10-27 17:22:59 -06007261 }
7262
Lorenzo Colitti01d37632020-12-02 00:48:09 +09007263 // This network might have been underlying another network. Propagate its capabilities.
7264 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce2e6b79f2020-02-20 14:28:31 +08007265
7266 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayev284cb872020-12-07 22:43:07 -08007267 mDnsManager.updateTransportsForNetwork(
7268 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce2e6b79f2020-02-20 14:28:31 +08007269 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007270 }
7271
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09007272 /** Convenience method to update the capabilities for a given network. */
7273 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7274 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7275 }
7276
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007277 /**
7278 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7279 * network.
7280 *
7281 * Ingress interface filtering enforces that all apps under the given network can only receive
7282 * packets from the network's interface (and loopback). This is important for VPNs because
7283 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7284 * non-VPN interfaces.
7285 *
7286 * As a result, this method should return true iff
7287 * 1. the network is an app VPN (not legacy VPN)
7288 * 2. the VPN does not allow bypass
7289 * 3. the VPN is fully-routed
7290 * 4. the VPN interface is non-null
7291 *
Chalard Jeanbb3e64f2019-09-26 18:03:47 +09007292 * @see INetd#firewallAddUidInterfaceRules
7293 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007294 */
7295 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7296 LinkProperties lp) {
7297 if (nc == null || lp == null) return false;
7298 return nai.isVPN()
Lorenzo Colitticf595362020-01-12 22:28:37 +09007299 && !nai.networkAgentConfig.allowBypass
Qingxi Libb3347b2020-01-17 17:54:27 -08007300 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007301 && lp.getInterfaceName() != null
lucaslin62bc2b02020-11-02 16:05:02 +08007302 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7303 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007304 }
7305
Chiachang Wang1f50ae52020-12-10 22:24:47 +08007306 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7307 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7308 int index = 0;
7309 for (UidRange range : ranges) {
7310 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7311 index++;
7312 }
7313 return stableRanges;
7314 }
7315
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09007316 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7317 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7318 for (int i = 0; i < ranges.length; i++) {
7319 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7320 }
7321 return stableRanges;
7322 }
7323
Ken Chenb8e4bc92020-12-24 12:59:10 +08007324 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7325 int[] exemptUids) {
7326 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7327 try {
7328 mNetd.socketDestroy(ranges, exemptUids);
7329 } catch (Exception e) {
7330 loge("Exception in socket destroy: ", e);
7331 }
7332 }
7333 }
7334
7335 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7336 int[] exemptUids = new int[2];
7337 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7338 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7339 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7340 exemptUids[0] = VPN_UID;
7341 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7342 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7343
7344 maybeCloseSockets(nai, ranges, exemptUids);
7345 try {
7346 if (add) {
7347 mNetd.networkAddUidRanges(nai.network.netId, ranges);
7348 } else {
7349 mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
7350 }
7351 } catch (Exception e) {
7352 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7353 " on netId " + nai.network.netId + ". " + e);
7354 }
7355 maybeCloseSockets(nai, ranges, exemptUids);
7356 }
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09007357
Chalard Jeana39c91c2018-01-16 18:43:05 +09007358 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7359 NetworkCapabilities newNc) {
Chiachang Wangd5034c72021-02-22 18:36:38 +08007360 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7361 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeana39c91c2018-01-16 18:43:05 +09007362 if (null == prevRanges) prevRanges = new ArraySet<>();
7363 if (null == newRanges) newRanges = new ArraySet<>();
7364 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7365
7366 prevRanges.removeAll(newRanges);
7367 newRanges.removeAll(prevRangesCopy);
7368
7369 try {
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007370 // When updating the VPN uid routing rules, add the new range first then remove the old
7371 // range. If old range were removed first, there would be a window between the old
7372 // range being removed and the new range being added, during which UIDs contained
7373 // in both ranges are not subject to any VPN routing rules. Adding new range before
7374 // removing old range works because, unlike the filtering rules below, it's possible to
7375 // add duplicate UID routing rules.
Ken Chenb8e4bc92020-12-24 12:59:10 +08007376 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7377 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7378 // [1-5] & [1-2],[4-5] == [3]
7379 // Then we can do:
7380 // maybeCloseSockets([3])
7381 // mNetd.networkAddUidRanges([1-2],[4-5])
7382 // mNetd.networkRemoveUidRanges([1-5])
7383 // maybeCloseSockets([3])
7384 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7385 // number of binder calls from 6 to 4.
Chalard Jeana39c91c2018-01-16 18:43:05 +09007386 if (!newRanges.isEmpty()) {
Ken Chenb8e4bc92020-12-24 12:59:10 +08007387 updateUidRanges(true, nai, newRanges);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007388 }
7389 if (!prevRanges.isEmpty()) {
Ken Chenb8e4bc92020-12-24 12:59:10 +08007390 updateUidRanges(false, nai, prevRanges);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007391 }
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007392 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7393 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7394 final String iface = nai.linkProperties.getInterfaceName();
7395 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jean7f06b342020-05-20 16:11:50 +09007396 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007397 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7398 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7399 // were added first and then newRanges got removed later, there would be only one uid
7400 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7401 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7402 // Note that this is in contrast with the (more robust) update of VPN routing rules
7403 // above, where the addition of new ranges happens before the removal of old ranges.
7404 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7405 // to be removed will never overlap with the new range to be added.
7406 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb3347b2020-01-17 17:54:27 -08007407 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007408 }
7409 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb3347b2020-01-17 17:54:27 -08007410 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007411 }
Chalard Jeana39c91c2018-01-16 18:43:05 +09007412 } catch (Exception e) {
7413 // Never crash!
Lorenzo Colittiee6a6302019-04-12 10:48:06 +00007414 loge("Exception in updateUids: ", e);
Chalard Jeana39c91c2018-01-16 18:43:05 +09007415 }
7416 }
7417
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007418 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti7ec341a2019-02-20 21:34:01 +09007419 ensureRunningOnConnectivityServiceThread();
7420
Serik Beketayev284cb872020-12-07 22:43:07 -08007421 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007422 // Ignore updates for disconnected networks
7423 return;
7424 }
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09007425 if (VDBG || DDBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007426 log("Update of LinkProperties for " + nai.toShortString()
7427 + "; created=" + nai.created
7428 + "; everConnected=" + nai.everConnected);
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007429 }
Lorenzo Colitti1b6f19d2020-04-16 01:52:40 +09007430 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7431 // modify its oldLp parameter.
lucaslin34cd3942018-11-28 12:51:55 +08007432 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi1dd94a22017-09-01 01:23:32 +00007433 }
7434
Jeremy Joslin94c30992014-11-05 10:32:09 -08007435 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7436 int notificationType) {
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007437 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin94c30992014-11-05 10:32:09 -08007438 Intent intent = new Intent();
Jeremy Joslin362093e2014-11-26 14:24:15 -08007439 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattis622428c2020-12-02 14:12:41 -08007440 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7441 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7442 // such an API is ever implemented, there is no doubt the right request to send in
7443 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7444 // be sent as a separate extra.
7445 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007446 nri.mPendingIntentSent = true;
Jeremy Joslin94c30992014-11-05 10:32:09 -08007447 sendIntent(nri.mPendingIntent, intent);
7448 }
7449 // else not handled
7450 }
7451
7452 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7453 mPendingIntentWakeLock.acquire();
7454 try {
7455 if (DBG) log("Sending " + pendingIntent);
7456 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7457 } catch (PendingIntent.CanceledException e) {
7458 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7459 mPendingIntentWakeLock.release();
7460 releasePendingNetworkRequest(pendingIntent);
7461 }
7462 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7463 }
7464
7465 @Override
7466 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7467 String resultData, Bundle resultExtras) {
7468 if (DBG) log("Finished sending " + pendingIntent);
7469 mPendingIntentWakeLock.release();
Jeremy Joslinb9846d02014-12-03 17:15:28 -08007470 // Release with a delay so the receiving client has an opportunity to put in its
7471 // own request.
7472 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin94c30992014-11-05 10:32:09 -08007473 }
7474
James Mattis757e0e82020-12-03 19:57:41 -08007475 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7476 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7477 final int arg1) {
James Mattis6e6fabf2021-01-10 14:24:24 -08007478 if (nri.mMessenger == null) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08007479 // Default request has no msgr. Also prevents callbacks from being invoked for
7480 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7481 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7482 return;
Hugo Benichi4802c802017-03-23 22:40:44 +09007483 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007484 Bundle bundle = new Bundle();
James Mattis757e0e82020-12-03 19:57:41 -08007485 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichi4802c802017-03-23 22:40:44 +09007486 // TODO: check if defensive copies of data is needed.
James Mattise494cbb2021-02-09 18:18:28 -08007487 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis757e0e82020-12-03 19:57:41 -08007488 putParcelable(bundle, nrForCallback);
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007489 Message msg = Message.obtain();
Hugo Benichi4802c802017-03-23 22:40:44 +09007490 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7491 putParcelable(bundle, networkAgent.network);
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007492 }
Roshan Pius7992afd2020-12-22 15:10:42 -08007493 final boolean includeLocationSensitiveInfo =
7494 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007495 switch (notificationType) {
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09007496 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Libf6bf082020-01-08 12:51:49 -08007497 final NetworkCapabilities nc =
7498 networkCapabilitiesRestrictedForCallerPermissions(
7499 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7500 putParcelable(
7501 bundle,
Roshan Pius423fff62020-12-28 09:01:49 -08007502 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius332e7a22021-03-21 17:55:29 +00007503 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius7992afd2020-12-22 15:10:42 -08007504 nrForCallback.getRequestorPackageName(),
Roshan Piusc97d8062020-12-17 14:53:09 -08007505 nri.mCallingAttributionTag));
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09007506 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7507 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulai5ab727b2018-08-07 19:50:45 +08007508 // For this notification, arg1 contains the blocked status.
7509 msg.arg1 = arg1;
Chalard Jeanb6a0c6d2018-01-30 22:41:41 +09007510 break;
7511 }
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007512 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007513 msg.arg1 = arg1;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007514 break;
7515 }
7516 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanb70f7cc2018-01-26 19:24:40 +09007517 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Libf6bf082020-01-08 12:51:49 -08007518 final NetworkCapabilities netCap =
7519 networkCapabilitiesRestrictedForCallerPermissions(
7520 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7521 putParcelable(
7522 bundle,
Roshan Pius423fff62020-12-28 09:01:49 -08007523 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius332e7a22021-03-21 17:55:29 +00007524 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius7992afd2020-12-22 15:10:42 -08007525 nrForCallback.getRequestorPackageName(),
Roshan Piusc97d8062020-12-17 14:53:09 -08007526 nri.mCallingAttributionTag));
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007527 break;
7528 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007529 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VANa36cf782019-12-17 16:45:42 +09007530 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7531 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007532 break;
7533 }
junyulai5ab727b2018-08-07 19:50:45 +08007534 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colittia37eaff2021-03-25 23:17:36 +09007535 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulai5ab727b2018-08-07 19:50:45 +08007536 msg.arg1 = arg1;
7537 break;
7538 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007539 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007540 msg.what = notificationType;
Robert Greenwalt78ac81a2014-09-30 16:50:07 -07007541 msg.setData(bundle);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007542 try {
Robert Greenwalt721f2372014-08-27 14:34:02 -07007543 if (VDBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09007544 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis757e0e82020-12-03 19:57:41 -08007545 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt721f2372014-08-27 14:34:02 -07007546 }
James Mattis6e6fabf2021-01-10 14:24:24 -08007547 nri.mMessenger.send(msg);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007548 } catch (RemoteException e) {
7549 // may occur naturally in the race of binder death.
James Mattis757e0e82020-12-03 19:57:41 -08007550 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07007551 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007552 }
7553
Hugo Benichi4802c802017-03-23 22:40:44 +09007554 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7555 bundle.putParcelable(t.getClass().getSimpleName(), t);
7556 }
7557
Paul Jensenab9bdd52014-09-30 15:37:41 -04007558 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09007559 if (nai.numRequestNetworkRequests() != 0) {
7560 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7561 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti74d34ec2021-01-29 20:18:03 +09007562 // Ignore listening and track default requests.
7563 if (!nr.isRequest()) continue;
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09007564 loge("Dead network still had at least " + nr);
7565 break;
7566 }
Paul Jensenab9bdd52014-09-30 15:37:41 -04007567 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007568 nai.disconnect();
Paul Jensenab9bdd52014-09-30 15:37:41 -04007569 }
7570
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007571 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7572 if (oldNetwork == null) {
7573 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7574 return;
7575 }
Chalard Jean373391b2019-12-10 21:07:02 +09007576 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007577
7578 // If we get here it means that the last linger timeout for this network expired. So there
7579 // must be no other active linger timers, and we must stop lingering.
junyulai2a4f0062021-02-03 20:15:30 +08007580 oldNetwork.clearInactivityState();
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007581
Lorenzo Colittib5b725d2016-09-09 18:48:56 +09007582 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007583 // Tear the network down.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007584 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti32237c72016-07-18 18:40:42 +09007585 } else {
junyulaif6d98ec2020-12-14 18:41:52 +08007586 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colitti00e0f5a2020-12-10 00:32:04 +09007587 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007588 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07007589 }
7590
James Mattis8af2d602020-12-20 11:09:58 -08007591 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7592 boolean isDefaultChanged = false;
7593 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7594 final NetworkReassignment.RequestReassignment reassignment =
7595 changes.getReassignment(defaultRequestInfo);
7596 if (null == reassignment) {
7597 continue;
7598 }
7599 // reassignment only contains those instances where the satisfying network changed.
7600 isDefaultChanged = true;
7601 // Notify system services of the new default.
7602 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7603 }
Chiachang Wang228b1c32018-09-28 22:42:48 +08007604
James Mattis8af2d602020-12-20 11:09:58 -08007605 if (isDefaultChanged) {
7606 // Hold a wakelock for a short time to help apps in migrating to a new default.
7607 scheduleReleaseNetworkTransitionWakelock();
7608 }
7609 }
7610
7611 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7612 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7613 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7614 if (DBG) {
7615 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7616 }
Chalard Jean337a8032019-12-03 20:45:30 +09007617
James Mattis1238af22020-12-23 16:37:26 -08007618 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7619 if (newDefaultNetwork != null) {
7620 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensen207feb72014-07-14 12:03:33 -04007621 }
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09007622
James Mattis1238af22020-12-23 16:37:26 -08007623 // Set an app level managed default and return since further processing only applies to the
7624 // default network.
7625 if (mDefaultRequest != nri) {
7626 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7627 return;
7628 }
7629
7630 makeDefaultNetwork(newDefaultNetwork);
7631
James Mattis8af2d602020-12-20 11:09:58 -08007632 if (oldDefaultNetwork != null) {
7633 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7634 }
7635 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattis8af2d602020-12-20 11:09:58 -08007636 handleApplyDefaultProxy(null != newDefaultNetwork
7637 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7638 updateTcpBufferSizes(null != newDefaultNetwork
7639 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09007640 notifyIfacesChangedForNetworkStats();
Paul Jensen207feb72014-07-14 12:03:33 -04007641 }
7642
James Mattis1238af22020-12-23 16:37:26 -08007643 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7644 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7645 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7646 try {
7647 if (VDBG) {
7648 log("Setting default network for " + nri
7649 + " using UIDs " + nri.getUids()
7650 + " with old network " + (oldDefaultNetwork != null
7651 ? oldDefaultNetwork.network().getNetId() : "null")
7652 + " and new network " + (newDefaultNetwork != null
7653 ? newDefaultNetwork.network().getNetId() : "null"));
7654 }
7655 if (nri.getUids().isEmpty()) {
7656 throw new IllegalStateException("makeDefaultForApps called without specifying"
7657 + " any applications to set as the default." + nri);
7658 }
7659 if (null != newDefaultNetwork) {
7660 mNetd.networkAddUidRanges(
7661 newDefaultNetwork.network.getNetId(),
7662 toUidRangeStableParcels(nri.getUids()));
7663 }
7664 if (null != oldDefaultNetwork) {
7665 mNetd.networkRemoveUidRanges(
7666 oldDefaultNetwork.network.getNetId(),
7667 toUidRangeStableParcels(nri.getUids()));
7668 }
7669 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09007670 loge("Exception setting app default network", e);
James Mattis1238af22020-12-23 16:37:26 -08007671 }
7672 }
7673
7674 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7675 try {
7676 if (null != newDefaultNetwork) {
7677 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7678 } else {
7679 mNetd.networkClearDefault();
7680 }
7681 } catch (RemoteException | ServiceSpecificException e) {
7682 loge("Exception setting default network :" + e);
7683 }
7684 }
7685
Chalard Jeanb9c02722019-12-09 11:50:38 +09007686 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007687 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007688 processNewlyLostListenRequests(nai);
Chalard Jeanb9c02722019-12-09 11:50:38 +09007689 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007690 processNewlySatisfiedListenRequests(nai);
7691 }
7692
7693 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattis622428c2020-12-02 14:12:41 -08007694 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7695 if (nri.isMultilayerRequest()) {
7696 continue;
7697 }
7698 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007699 if (!nr.isListen()) continue;
7700 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattis622428c2020-12-02 14:12:41 -08007701 nai.removeRequest(nr.requestId);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007702 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7703 }
7704 }
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007705 }
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007706
Chalard Jeanec70c4f2019-11-22 22:33:33 +09007707 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattis622428c2020-12-02 14:12:41 -08007708 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7709 if (nri.isMultilayerRequest()) {
7710 continue;
7711 }
7712 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007713 if (!nr.isListen()) continue;
7714 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7715 nai.addRequest(nr);
Erik Kline81fdc8a2017-02-15 19:59:17 +09007716 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti5d8b6bd2016-07-20 02:39:22 +09007717 }
7718 }
7719 }
7720
Chalard Jean63cb44d2019-12-02 15:34:05 +09007721 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean63cb44d2019-12-02 15:34:05 +09007722 private static class NetworkReassignment {
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007723 static class RequestReassignment {
James Mattis622428c2020-12-02 14:12:41 -08007724 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jean018dbe42021-03-01 22:16:08 +09007725 @Nullable public final NetworkRequest mOldNetworkRequest;
7726 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007727 @Nullable public final NetworkAgentInfo mOldNetwork;
7728 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattis622428c2020-12-02 14:12:41 -08007729 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jean018dbe42021-03-01 22:16:08 +09007730 @Nullable final NetworkRequest oldNetworkRequest,
7731 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007732 @Nullable final NetworkAgentInfo oldNetwork,
7733 @Nullable final NetworkAgentInfo newNetwork) {
James Mattis622428c2020-12-02 14:12:41 -08007734 mNetworkRequestInfo = networkRequestInfo;
7735 mOldNetworkRequest = oldNetworkRequest;
7736 mNewNetworkRequest = newNetworkRequest;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007737 mOldNetwork = oldNetwork;
7738 mNewNetwork = newNetwork;
7739 }
Chalard Jean373391b2019-12-10 21:07:02 +09007740
7741 public String toString() {
Chalard Jeanad0a6e62021-03-01 22:06:04 +09007742 final NetworkRequest requestToShow = null != mNewNetworkRequest
7743 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7744 return requestToShow.requestId + " : "
Serik Beketayev284cb872020-12-07 22:43:07 -08007745 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7746 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean373391b2019-12-10 21:07:02 +09007747 }
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007748 }
7749
Chalard Jean8049afd2019-12-10 21:25:24 +09007750 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean63cb44d2019-12-02 15:34:05 +09007751
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007752 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean8049afd2019-12-10 21:25:24 +09007753 return mReassignments;
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007754 }
7755
7756 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN53e02712021-04-07 19:40:31 +09007757 if (Build.isDebuggable()) {
Chalard Jean8049afd2019-12-10 21:25:24 +09007758 // The code is never supposed to add two reassignments of the same request. Make
7759 // sure this stays true, but without imposing this expensive check on all
7760 // reassignments on all user devices.
7761 for (final RequestReassignment existing : mReassignments) {
James Mattis622428c2020-12-02 14:12:41 -08007762 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean8049afd2019-12-10 21:25:24 +09007763 throw new IllegalStateException("Trying to reassign ["
7764 + reassignment + "] but already have ["
7765 + existing + "]");
7766 }
7767 }
Chalard Jean69369aa2019-12-03 22:16:26 +09007768 }
Chalard Jean8049afd2019-12-10 21:25:24 +09007769 mReassignments.add(reassignment);
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007770 }
7771
Chalard Jean3952fb12019-12-03 14:43:57 +09007772 // Will return null if this reassignment does not change the network assigned to
Chalard Jean337a8032019-12-03 20:45:30 +09007773 // the passed request.
7774 @Nullable
7775 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean3952fb12019-12-03 14:43:57 +09007776 for (final RequestReassignment event : getRequestReassignments()) {
James Mattis622428c2020-12-02 14:12:41 -08007777 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean3952fb12019-12-03 14:43:57 +09007778 }
7779 return null;
7780 }
Chalard Jean373391b2019-12-10 21:07:02 +09007781
7782 public String toString() {
7783 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7784 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jean88e5b872019-12-11 14:12:30 +09007785 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean373391b2019-12-10 21:07:02 +09007786 for (final RequestReassignment rr : getRequestReassignments()) {
7787 sj.add(rr.toString());
7788 }
7789 return sj.toString();
7790 }
7791
7792 public String debugString() {
7793 final StringBuilder sb = new StringBuilder();
7794 sb.append("NetworkReassignment :");
Chalard Jean88e5b872019-12-11 14:12:30 +09007795 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean373391b2019-12-10 21:07:02 +09007796 for (final RequestReassignment rr : getRequestReassignments()) {
7797 sb.append("\n ").append(rr);
7798 }
7799 return sb.append("\n").toString();
7800 }
Chalard Jean63cb44d2019-12-02 15:34:05 +09007801 }
7802
Chalard Jeanf57b9692019-12-04 13:32:31 +09007803 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean018dbe42021-03-01 22:16:08 +09007804 @Nullable final NetworkRequest previousRequest,
7805 @Nullable final NetworkRequest newRequest,
Chalard Jeanf57b9692019-12-04 13:32:31 +09007806 @Nullable final NetworkAgentInfo previousSatisfier,
7807 @Nullable final NetworkAgentInfo newSatisfier,
7808 final long now) {
James Mattis1238af22020-12-23 16:37:26 -08007809 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean373391b2019-12-10 21:07:02 +09007810 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jean018dbe42021-03-01 22:16:08 +09007811 if (null != previousRequest && null != previousSatisfier) {
Chalard Jeanf57b9692019-12-04 13:32:31 +09007812 if (VDBG || DDBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007813 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jeanf57b9692019-12-04 13:32:31 +09007814 }
James Mattis622428c2020-12-02 14:12:41 -08007815 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jeane634b282021-03-05 23:07:53 +09007816 previousSatisfier.lingerRequest(previousRequest.requestId, now);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007817 } else {
7818 if (VDBG || DDBG) log(" accepting network in place of null");
7819 }
junyulaif6d98ec2020-12-14 18:41:52 +08007820
7821 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7822 // and immediately satisfies a request then remove the timer. This will happen for
7823 // all networks except in the case of an underlying network for a VCN.
7824 if (newSatisfier.isNascent()) {
7825 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai2f4a5b32021-03-26 00:40:48 +08007826 newSatisfier.unsetInactive();
junyulaif6d98ec2020-12-14 18:41:52 +08007827 }
7828
Chalard Jeandc974072021-03-01 22:00:20 +09007829 // if newSatisfier is not null, then newRequest may not be null.
James Mattis622428c2020-12-02 14:12:41 -08007830 newSatisfier.unlingerRequest(newRequest.requestId);
7831 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang11e9a312020-10-30 22:04:25 +08007832 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattis622428c2020-12-02 14:12:41 -08007833 + newRequest);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007834 }
Chalard Jean018dbe42021-03-01 22:16:08 +09007835 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jeanf57b9692019-12-04 13:32:31 +09007836 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09007837 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattis622428c2020-12-02 14:12:41 -08007838 + " request " + previousRequest.requestId);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007839 }
James Mattis622428c2020-12-02 14:12:41 -08007840 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007841 }
James Mattis622428c2020-12-02 14:12:41 -08007842 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jeanf57b9692019-12-04 13:32:31 +09007843 }
7844
James Mattis622428c2020-12-02 14:12:41 -08007845 /**
7846 * This function is triggered when something can affect what network should satisfy what
7847 * request, and it computes the network reassignment from the passed collection of requests to
7848 * network match to the one that the system should now have. That data is encoded in an
7849 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
7850 * satisfier.
7851 *
7852 * After the reassignment is computed, it is applied to the state objects.
7853 *
7854 * @param networkRequests the nri objects to evaluate for possible network reassignment
7855 * @return NetworkReassignment listing of proposed network assignment changes
7856 */
Chalard Jean42909302019-12-10 18:56:30 +09007857 @NonNull
James Mattis622428c2020-12-02 14:12:41 -08007858 private NetworkReassignment computeNetworkReassignment(
7859 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean013fb142019-12-10 21:08:07 +09007860 final NetworkReassignment changes = new NetworkReassignment();
7861
Chalard Jean3d71e302021-04-07 17:06:19 +09007862 // Gather the list of all relevant agents.
Chalard Jean013fb142019-12-10 21:08:07 +09007863 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007864 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis622428c2020-12-02 14:12:41 -08007865 if (!nai.everConnected) {
7866 continue;
7867 }
Chalard Jean013fb142019-12-10 21:08:07 +09007868 nais.add(nai);
Chalard Jean013fb142019-12-10 21:08:07 +09007869 }
Chalard Jean013fb142019-12-10 21:08:07 +09007870
James Mattis622428c2020-12-02 14:12:41 -08007871 for (final NetworkRequestInfo nri : networkRequests) {
7872 // Non-multilayer listen requests can be ignored.
7873 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
7874 continue;
7875 }
7876 NetworkAgentInfo bestNetwork = null;
7877 NetworkRequest bestRequest = null;
7878 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeanb887f602021-03-29 17:03:59 +09007879 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattis622428c2020-12-02 14:12:41 -08007880 // Stop evaluating as the highest possible priority request is satisfied.
7881 if (null != bestNetwork) {
7882 bestRequest = req;
7883 break;
7884 }
7885 }
James Mattis1238af22020-12-23 16:37:26 -08007886 if (null == bestNetwork && isDefaultBlocked(nri)) {
7887 // Remove default networking if disallowed for managed default requests.
7888 bestNetwork = mNoServiceNetwork;
7889 }
7890 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean58d486c2019-12-10 22:16:53 +09007891 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean013fb142019-12-10 21:08:07 +09007892 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattis622428c2020-12-02 14:12:41 -08007893 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean013fb142019-12-10 21:08:07 +09007894 }
Chalard Jean42909302019-12-10 18:56:30 +09007895 }
7896 return changes;
7897 }
7898
James Mattis622428c2020-12-02 14:12:41 -08007899 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
7900 return new HashSet<>(mNetworkRequests.values());
7901 }
7902
Paul Jensen50f38772015-06-16 14:27:36 -04007903 /**
James Mattis622428c2020-12-02 14:12:41 -08007904 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensen50f38772015-06-16 14:27:36 -04007905 * being disconnected.
Paul Jensen50f38772015-06-16 14:27:36 -04007906 */
Chalard Jean60902092019-11-07 18:54:49 +09007907 private void rematchAllNetworksAndRequests() {
James Mattis622428c2020-12-02 14:12:41 -08007908 rematchNetworksAndRequests(getNrisFromGlobalRequests());
7909 }
7910
7911 /**
7912 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
7913 * being disconnected.
7914 */
7915 private void rematchNetworksAndRequests(
7916 @NonNull final Set<NetworkRequestInfo> networkRequests) {
7917 ensureRunningOnConnectivityServiceThread();
Chalard Jean013fb142019-12-10 21:08:07 +09007918 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09007919 final long now = SystemClock.elapsedRealtime();
James Mattis622428c2020-12-02 14:12:41 -08007920 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean373391b2019-12-10 21:07:02 +09007921 if (VDBG || DDBG) {
7922 log(changes.debugString());
7923 } else if (DBG) {
7924 log(changes.toString()); // Shorter form, only one line of log
7925 }
Chalard Jean32c20902019-12-10 22:01:31 +09007926 applyNetworkReassignment(changes, now);
Chalard Jean7b6a33b2021-01-12 10:58:56 +09007927 issueNetworkNeeds();
Chalard Jeand4a4a302019-12-10 19:01:29 +09007928 }
Chalard Jean208f81b2019-12-04 19:55:32 +09007929
Chalard Jeand4a4a302019-12-10 19:01:29 +09007930 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jean32c20902019-12-10 22:01:31 +09007931 final long now) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09007932 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jean88e5b872019-12-11 14:12:30 +09007933
7934 // Since most of the time there are only 0 or 1 background networks, it would probably
7935 // be more efficient to just use an ArrayList here. TODO : measure performance
7936 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
7937 for (final NetworkAgentInfo nai : nais) {
7938 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
7939 }
7940
Chalard Jeand4a4a302019-12-10 19:01:29 +09007941 // First, update the lists of satisfied requests in the network agents. This is necessary
7942 // because some code later depends on this state to be correct, most prominently computing
7943 // the linger status.
Chalard Jean208f81b2019-12-04 19:55:32 +09007944 for (final NetworkReassignment.RequestReassignment event :
7945 changes.getRequestReassignments()) {
James Mattis622428c2020-12-02 14:12:41 -08007946 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
7947 event.mOldNetworkRequest, event.mNewNetworkRequest,
7948 event.mOldNetwork, event.mNewNetwork,
7949 now);
Chalard Jeana03df692019-11-07 19:05:18 +09007950 }
Chalard Jeandc623312019-11-07 23:16:12 +09007951
James Mattis8af2d602020-12-20 11:09:58 -08007952 // Process default network changes if applicable.
7953 processDefaultNetworkChanges(changes);
Chalard Jean76b04162019-11-19 19:16:48 +09007954
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007955 // Notify requested networks are available after the default net is switched, but
7956 // before LegacyTypeTracker sends legacy broadcasts
7957 for (final NetworkReassignment.RequestReassignment event :
7958 changes.getRequestReassignments()) {
7959 if (null != event.mNewNetwork) {
James Mattis622428c2020-12-02 14:12:41 -08007960 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jeanc1da9302019-12-03 15:55:14 +09007961 } else {
James Mattis622428c2020-12-02 14:12:41 -08007962 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jeanc1da9302019-12-03 15:55:14 +09007963 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeanbf56ab52019-12-02 18:59:27 +09007964 }
7965 }
7966
junyulaif6d98ec2020-12-14 18:41:52 +08007967 // Update the inactivity state before processing listen callbacks, because the background
7968 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean1a1d2782019-12-04 20:01:46 +09007969 // just yet though, because they have to be sent after the listens are processed to keep
7970 // backward compatibility.
junyulaif6d98ec2020-12-14 18:41:52 +08007971 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean41bae5c2019-11-19 20:01:10 +09007972 for (final NetworkAgentInfo nai : nais) {
junyulaif6d98ec2020-12-14 18:41:52 +08007973 // Rematching may have altered the inactivity state of some networks, so update all
7974 // inactivity timers. updateInactivityState reads the state from the network agent
7975 // and does nothing if the state has not changed : the source of truth is controlled
7976 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
7977 // have been called while rematching the individual networks above.
junyulai2a4f0062021-02-03 20:15:30 +08007978 if (updateInactivityState(nai, now)) {
junyulaif6d98ec2020-12-14 18:41:52 +08007979 inactiveNetworks.add(nai);
Chalard Jeand915e362019-12-04 18:49:18 +09007980 }
7981 }
7982
Chalard Jean88e5b872019-12-11 14:12:30 +09007983 for (final NetworkAgentInfo nai : nais) {
7984 if (!nai.everConnected) continue;
7985 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007986 // Process listen requests and update capabilities if the background state has
7987 // changed for this network. For consistency with previous behavior, send onLost
7988 // callbacks before onAvailable.
Chalard Jean88e5b872019-12-11 14:12:30 +09007989 processNewlyLostListenRequests(nai);
7990 if (oldBackground != nai.isBackgroundNetwork()) {
7991 applyBackgroundChangeForRematch(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007992 }
Chalard Jean88e5b872019-12-11 14:12:30 +09007993 processNewlySatisfiedListenRequests(nai);
Chalard Jean1a1d2782019-12-04 20:01:46 +09007994 }
7995
junyulaif6d98ec2020-12-14 18:41:52 +08007996 for (final NetworkAgentInfo nai : inactiveNetworks) {
7997 // For nascent networks, if connecting with no foreground request, skip broadcasting
7998 // LOSING for backward compatibility. This is typical when mobile data connected while
7999 // wifi connected with mobile data always-on enabled.
8000 if (nai.isNascent()) continue;
Chalard Jeand915e362019-12-04 18:49:18 +09008001 notifyNetworkLosing(nai, now);
Chalard Jeandc623312019-11-07 23:16:12 +09008002 }
8003
James Mattis8af2d602020-12-20 11:09:58 -08008004 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jean4005aeb2019-11-19 19:23:38 +09008005
Chalard Jeandc623312019-11-07 23:16:12 +09008006 // Tear down all unneeded networks.
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008007 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jeana03df692019-11-07 19:05:18 +09008008 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2a4f0062021-02-03 20:15:30 +08008009 if (nai.getInactivityExpiry() > 0) {
Chalard Jeana03df692019-11-07 19:05:18 +09008010 // This network has active linger timers and no requests, but is not
8011 // lingering. Linger it.
8012 //
8013 // One way (the only way?) this can happen if this network is unvalidated
8014 // and became unneeded due to another network improving its score to the
8015 // point where this network will no longer be able to satisfy any requests
8016 // even if it validates.
junyulai2a4f0062021-02-03 20:15:30 +08008017 if (updateInactivityState(nai, now)) {
Chalard Jeand915e362019-12-04 18:49:18 +09008018 notifyNetworkLosing(nai, now);
8019 }
Chalard Jeana03df692019-11-07 19:05:18 +09008020 } else {
Chalard Jean373391b2019-12-10 21:07:02 +09008021 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jeana03df692019-11-07 19:05:18 +09008022 teardownUnneededNetwork(nai);
8023 }
8024 }
Paul Jensen19d1d362014-09-11 11:00:39 -04008025 }
8026 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008027
Chalard Jeana00029d2019-12-02 18:39:29 +09008028 /**
8029 * Apply a change in background state resulting from rematching networks with requests.
8030 *
8031 * During rematch, a network may change background states by starting to satisfy or stopping
8032 * to satisfy a foreground request. Listens don't count for this. When a network changes
8033 * background states, its capabilities need to be updated and callbacks fired for the
8034 * capability change.
8035 *
8036 * @param nai The network that changed background states
8037 */
8038 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8039 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8040 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8041 updateNetworkPermissions(nai, newNc);
8042 nai.getAndSetNetworkCapabilities(newNc);
8043 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8044 }
8045
Chalard Jean4005aeb2019-11-19 19:23:38 +09008046 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattis8af2d602020-12-20 11:09:58 -08008047 @NonNull final NetworkReassignment changes,
Chalard Jean42909302019-12-10 18:56:30 +09008048 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean1bc77a92021-02-04 13:12:59 +09008049 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8050 changes.getReassignment(mDefaultRequest);
8051 final NetworkAgentInfo oldDefaultNetwork =
8052 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8053 final NetworkAgentInfo newDefaultNetwork =
8054 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattis8af2d602020-12-20 11:09:58 -08008055
Chalard Jean1bc77a92021-02-04 13:12:59 +09008056 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jean76b04162019-11-19 19:16:48 +09008057 // Maintain the illusion : since the legacy API only understands one network at a time,
8058 // if the default network changed, apps should see a disconnected broadcast for the
8059 // old default network before they see a connected broadcast for the new one.
Chalard Jean1bc77a92021-02-04 13:12:59 +09008060 if (oldDefaultNetwork != null) {
8061 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8062 oldDefaultNetwork, true);
Chalard Jean76b04162019-11-19 19:16:48 +09008063 }
Chalard Jean1bc77a92021-02-04 13:12:59 +09008064 if (newDefaultNetwork != null) {
Chalard Jean76b04162019-11-19 19:16:48 +09008065 // The new default network can be newly null if and only if the old default
8066 // network doesn't satisfy the default request any more because it lost a
8067 // capability.
Chalard Jean1bc77a92021-02-04 13:12:59 +09008068 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattis8af2d602020-12-20 11:09:58 -08008069 mLegacyTypeTracker.add(
Chalard Jean1bc77a92021-02-04 13:12:59 +09008070 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jean76b04162019-11-19 19:16:48 +09008071 }
8072 }
8073
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008074 // Now that all the callbacks have been sent, send the legacy network broadcasts
8075 // as needed. This is necessary so that legacy requests correctly bind dns
8076 // requests to this network. The legacy users are listening for this broadcast
8077 // and will generally do a dns request so they can ensureRouteToHost and if
8078 // they do that before the callbacks happen they'll use the default network.
8079 //
8080 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8081 // callbacks, but if apps can receive the broadcast before the callback, they still might
8082 // have an inconsistent view of networking.
8083 //
8084 // This *does* introduce a race where if the user uses the new api
8085 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8086 // they may get old info. Reverse this after the old startUsing api is removed.
8087 // This is on top of the multiple intent sequencing referenced in the todo above.
8088 for (NetworkAgentInfo nai : nais) {
Chalard Jean88e5b872019-12-11 14:12:30 +09008089 if (nai.everConnected) {
8090 addNetworkToLegacyTypeTracker(nai);
8091 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008092 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008093 }
8094
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008095 private void issueNetworkNeeds() {
8096 ensureRunningOnConnectivityServiceThread();
8097 for (final NetworkOfferInfo noi : mNetworkOffers) {
8098 issueNetworkNeeds(noi);
8099 }
8100 }
8101
8102 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8103 ensureRunningOnConnectivityServiceThread();
8104 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8105 informOffer(nri, noi.offer, mNetworkRanker);
8106 }
8107 }
8108
8109 /**
8110 * Inform a NetworkOffer about any new situation of a request.
8111 *
8112 * This function handles updates to offers. A number of events may happen that require
8113 * updating the registrant for this offer about the situation :
8114 * • The offer itself was updated. This may lead the offer to no longer being able
8115 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8116 * or conversely being strengthened enough to beat the satisfier (and therefore
8117 * start being needed)
8118 * • The network satisfying a request changed (including cases where the request
8119 * starts or stops being satisfied). The new network may be a stronger or weaker
8120 * match than the old one, possibly affecting whether the offer is needed.
8121 * • The network satisfying a request updated their score. This may lead the offer
8122 * to no longer be able to beat it if the current satisfier got better, or
8123 * conversely start being a good choice if the current satisfier got weaker.
8124 *
8125 * @param nri The request
8126 * @param offer The offer. This may be an updated offer.
8127 */
8128 private static void informOffer(@NonNull NetworkRequestInfo nri,
8129 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8130 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8131 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008132
8133 // Multi-layer requests have a currently active request, the one being satisfied.
8134 // Since the system will try to bring up a better network than is currently satisfying
8135 // the request, NetworkProviders need to be told the offers matching the requests *above*
8136 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8137 // not needed, and the offer is needed for the active request iff the offer can beat
8138 // the satisfier.
8139 // For non-multilayer requests, the logic above gracefully degenerates to only the
8140 // last case.
8141 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8142 // providers that the offer is needed for this request, until the active request is found.
8143 // In a second phase, deal with the currently active request. In a third phase, inform
8144 // the providers that offer is unneeded for the remaining requests.
8145
8146 // First phase : inform providers of all requests above the active request.
8147 int i;
8148 for (i = 0; nri.mRequests.size() > i; ++i) {
8149 final NetworkRequest request = nri.mRequests.get(i);
8150 if (activeRequest == request) break; // Found the active request : go to phase 2
8151 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8152 // Since this request is higher-priority than the one currently satisfied, if the
8153 // offer can satisfy it, the provider should try and bring up the network for sure ;
8154 // no need to even ask the ranker – an offer that can satisfy is always better than
8155 // no network. Hence tell the provider so unless it already knew.
8156 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8157 offer.onNetworkNeeded(request);
8158 }
8159 }
8160
8161 // Second phase : deal with the active request (if any)
8162 if (null != activeRequest && activeRequest.isRequest()) {
8163 final boolean oldNeeded = offer.neededFor(activeRequest);
8164 // An offer is needed if it is currently served by this provider or if this offer
8165 // can beat the current satisfier.
8166 final boolean currentlyServing = satisfier != null
8167 && satisfier.factorySerialNumber == offer.providerId;
8168 final boolean newNeeded = (currentlyServing
8169 || (activeRequest.canBeSatisfiedBy(offer.caps)
Chalard Jeanb887f602021-03-29 17:03:59 +09008170 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
Chalard Jean7b6a33b2021-01-12 10:58:56 +09008171 if (newNeeded != oldNeeded) {
8172 if (newNeeded) {
8173 offer.onNetworkNeeded(activeRequest);
8174 } else {
8175 // The offer used to be able to beat the satisfier. Now it can't.
8176 offer.onNetworkUnneeded(activeRequest);
8177 }
8178 }
8179 }
8180
8181 // Third phase : inform the providers that the offer isn't needed for any request
8182 // below the active one.
8183 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8184 final NetworkRequest request = nri.mRequests.get(i);
8185 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8186 // Since this request is lower-priority than the one currently satisfied, if the
8187 // offer can satisfy it, the provider should not try and bring up the network.
8188 // Hence tell the provider so unless it already knew.
8189 if (offer.neededFor(request)) {
8190 offer.onNetworkUnneeded(request);
8191 }
8192 }
8193 }
8194
Chalard Jean9fdd38a2019-11-07 23:07:32 +09008195 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8196 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8197 NetworkRequest nr = nai.requestAt(i);
8198 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8199 // legacy type tracker filters out repeat adds
8200 mLegacyTypeTracker.add(nr.legacyType, nai);
8201 }
8202 }
8203
8204 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean1bc77a92021-02-04 13:12:59 +09008205 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean9fdd38a2019-11-07 23:07:32 +09008206 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8207 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8208 if (nai.isVPN()) {
8209 mLegacyTypeTracker.add(TYPE_VPN, nai);
8210 }
8211 }
8212
Lorenzo Colittiaf3f8552014-12-17 11:26:49 +09008213 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen5877e732014-09-05 12:06:44 -04008214 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colitti80a0b532014-12-17 11:14:42 +09008215 if (!nai.everValidated) return;
Chalard Jean1bc77a92021-02-04 13:12:59 +09008216 // For now only update icons for the default connection.
Paul Jensen5877e732014-09-05 12:06:44 -04008217 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean1bc77a92021-02-04 13:12:59 +09008218 if (!isDefaultNetwork(nai)) return;
Paul Jensen5877e732014-09-05 12:06:44 -04008219
Lorenzo Colittiaf3f8552014-12-17 11:26:49 +09008220 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen5877e732014-09-05 12:06:44 -04008221 // Don't repeat publish.
8222 if (newInetCondition == mDefaultInetConditionPublished) return;
8223
8224 mDefaultInetConditionPublished = newInetCondition;
8225 sendInetConditionBroadcast(nai.networkInfo);
8226 }
8227
Chalard Jeanfa33a752020-01-14 22:46:36 +09008228 @NonNull
8229 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8230 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanc212ed12020-01-15 00:49:43 +09008231 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeanfa33a752020-01-14 22:46:36 +09008232 final boolean suspended =
8233 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8234 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8235 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8236 // state. This is because the network could have been suspended before connecting,
8237 // or it could be disconnecting while being suspended, and in both these cases
8238 // the state should not be overridden. Note that the only detailed state that
8239 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8240 // worry about multiple different substates of CONNECTED.
8241 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8242 info.getExtraInfo());
Chiachang Wang59f5d112020-02-12 17:01:59 +08008243 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8244 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8245 // network agent is created, then goes to suspended, then goes out of suspended without
8246 // ever setting connected. Check if network agent is ever connected to update the state.
8247 newInfo.setDetailedState(nai.everConnected
8248 ? NetworkInfo.DetailedState.CONNECTED
8249 : NetworkInfo.DetailedState.CONNECTING,
8250 info.getReason(),
8251 info.getExtraInfo());
Chalard Jeanfa33a752020-01-14 22:46:36 +09008252 }
Chalard Jeanc212ed12020-01-15 00:49:43 +09008253 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeanfa33a752020-01-14 22:46:36 +09008254 return newInfo;
8255 }
8256
8257 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8258 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8259
Erik Kline81fdc8a2017-02-15 19:59:17 +09008260 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt701a5c32014-06-23 11:40:00 -07008261 NetworkInfo oldInfo = null;
8262 synchronized (networkAgent) {
8263 oldInfo = networkAgent.networkInfo;
8264 networkAgent.networkInfo = newInfo;
8265 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008266
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008267 if (DBG) {
Chalard Jean373391b2019-12-10 21:07:02 +09008268 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8269 + oldInfo.getState() + " to " + state);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008270 }
Robert Greenwalt54d534f2014-05-13 21:41:06 -07008271
Robin Leebc024e52016-05-01 23:00:00 +01008272 if (!networkAgent.created
8273 && (state == NetworkInfo.State.CONNECTED
8274 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti32237c72016-07-18 18:40:42 +09008275
8276 // A network that has just connected has zero requests and is thus a foreground network.
8277 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8278
Luke Huang135c5262019-04-09 18:41:49 +08008279 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti01d37632020-12-02 00:48:09 +09008280 if (networkAgent.supportsUnderlyingNetworks()) {
8281 // Initialize the network's capabilities to their starting values according to the
8282 // underlying networks. This ensures that the capabilities are correct before
8283 // anything happens to the network.
8284 updateCapabilitiesForNetwork(networkAgent);
Chalard Jean8c5e4582020-05-07 12:07:03 +09008285 }
Paul Jensen956fa9f2014-08-04 12:21:19 -04008286 networkAgent.created = true;
Chiachang Wang85d72bd2021-03-24 18:39:17 +08008287 networkAgent.onNetworkCreated();
Robin Leebc024e52016-05-01 23:00:00 +01008288 }
8289
8290 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8291 networkAgent.everConnected = true;
8292
lucaslinb2d10842019-04-03 17:09:28 +08008293 // NetworkCapabilities need to be set before sending the private DNS config to
8294 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean8ffefba2019-11-22 22:39:56 +09008295 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8296
Erik Kline076bd3d2018-03-21 07:18:33 -07008297 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin34cd3942018-11-28 12:51:55 +08008298 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8299 null);
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008300
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09008301 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8302 // command must be sent after updating LinkProperties to maximize chances of
8303 // NetworkMonitor seeing the correct LinkProperties when starting.
8304 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colitticf595362020-01-12 22:28:37 +09008305 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti260d9982019-05-31 15:41:29 +09008306 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN1becbe72018-12-27 16:43:56 +09008307 }
Lorenzo Colitti260d9982019-05-31 15:41:29 +09008308 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VAN3b1d8b42020-05-10 16:11:11 +09008309 new LinkProperties(networkAgent.linkProperties,
8310 true /* parcelSensitiveFields */),
8311 networkAgent.networkCapabilities);
Lorenzo Colitti36fbebe2015-04-03 16:38:52 +09008312 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008313
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09008314 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8315 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8316 // capabilities, so it only needs to be done once on initial connect, not every time the
8317 // network's capabilities change. Note that we do this before rematching the network,
8318 // so we could decide to tear it down immediately afterwards. That's fine though - on
8319 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8320 // doing.
Lorenzo Colitti71ec67d2015-09-15 15:56:01 +09008321 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti87f93fe2015-07-06 23:50:27 +09008322
junyulaif6d98ec2020-12-14 18:41:52 +08008323 // Before first rematching networks, put an inactivity timer without any request, this
8324 // allows {@code updateInactivityState} to update the state accordingly and prevent
8325 // tearing down for any {@code unneeded} evaluation in this period.
8326 // Note that the timer will not be rescheduled since the expiry time is
8327 // fixed after connection regardless of the network satisfying other requests or not.
8328 // But it will be removed as soon as the network satisfies a request for the first time.
8329 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8330 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai2f4a5b32021-03-26 00:40:48 +08008331 networkAgent.setInactive();
junyulaif6d98ec2020-12-14 18:41:52 +08008332
Paul Jensen19d1d362014-09-11 11:00:39 -04008333 // Consider network even though it is not yet validated.
Chalard Jean60902092019-11-07 18:54:49 +09008334 rematchAllNetworksAndRequests();
Lorenzo Colitti97399ae2015-04-09 14:35:26 +09008335
8336 // This has to happen after matching the requests, because callbacks are just requests.
8337 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008338 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008339 networkAgent.disconnect();
Paul Jensena8a49e02014-05-07 15:27:40 -04008340 if (networkAgent.isVPN()) {
Chalard Jeana39c91c2018-01-16 18:43:05 +09008341 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensena8a49e02014-05-07 15:27:40 -04008342 }
Chalard Jeanefaf6532018-05-11 20:19:20 +09008343 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu0eafa0b2018-12-05 16:19:47 +00008344 if (networkAgent.isVPN()) {
8345 // As the active or bound network changes for apps, broadcast the default proxy, as
8346 // apps may need to update their proxy data. This is called after disconnecting from
8347 // VPN to make sure we do not broadcast the old proxy data.
8348 // TODO(b/122649188): send the broadcast only to VPN users.
8349 mProxyTracker.sendProxyBroadcast();
8350 }
Yintang Gu4bb19242019-06-18 14:24:32 +08008351 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8352 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008353 mLegacyTypeTracker.update(networkAgent);
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008354 }
8355 }
8356
Chalard Jeandd753522020-12-21 18:36:52 +09008357 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jeande419812020-03-04 17:45:08 +09008358 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8359 nai.setScore(score);
Chalard Jean60902092019-11-07 18:54:49 +09008360 rematchAllNetworksAndRequests();
Robert Greenwaltcf82b832014-05-27 13:20:24 -07008361 }
8362
Erik Kline81fdc8a2017-02-15 19:59:17 +09008363 // Notify only this one new request of the current state. Transfer all the
8364 // current state by calling NetworkCapabilities and LinkProperties callbacks
8365 // so that callers can be guaranteed to have as close to atomicity in state
8366 // transfer as can be supported by this current API.
8367 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen88087222016-10-27 15:05:50 -07008368 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline81fdc8a2017-02-15 19:59:17 +09008369 if (nri.mPendingIntent != null) {
8370 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8371 // Attempt no subsequent state pushes where intents are involved.
8372 return;
Jeremy Joslin94c30992014-11-05 10:32:09 -08008373 }
Erik Kline81fdc8a2017-02-15 19:59:17 +09008374
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008375 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulai5ab727b2018-08-07 19:50:45 +08008376 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008377 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8378 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8379 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulai5ab727b2018-08-07 19:50:45 +08008380 }
8381
Chalard Jeand915e362019-12-04 18:49:18 +09008382 // Notify the requests on this NAI that the network is now lingered.
8383 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2a4f0062021-02-03 20:15:30 +08008384 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jeand915e362019-12-04 18:49:18 +09008385 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8386 }
8387
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008388 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8389 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8390 return vpnBlocked
8391 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8392 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8393 }
8394
8395 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8396 if (blockedReasons == BLOCKED_REASON_NONE) {
8397 mUidBlockedReasons.delete(uid);
8398 } else {
8399 mUidBlockedReasons.put(uid, blockedReasons);
8400 }
8401 }
8402
junyulai5ab727b2018-08-07 19:50:45 +08008403 /**
8404 * Notify of the blocked state apps with a registered callback matching a given NAI.
8405 *
8406 * Unlike other callbacks, blocked status is different between each individual uid. So for
8407 * any given nai, all requests need to be considered according to the uid who filed it.
8408 *
8409 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008410 * @param oldMetered True if the previous network capabilities were metered.
8411 * @param newMetered True if the current network capabilities are metered.
8412 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8413 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulai5ab727b2018-08-07 19:50:45 +08008414 */
8415 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008416 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8417 List<UidRange> newBlockedUidRanges) {
junyulai5ab727b2018-08-07 19:50:45 +08008418
8419 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8420 NetworkRequest nr = nai.requestAt(i);
8421 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008422
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008423 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8424 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8425 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colittif2514122021-03-12 22:50:57 +09008426 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008427 : oldVpnBlocked;
8428
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008429 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8430 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8431 if (oldBlockedState != newBlockedState) {
junyulai5ab727b2018-08-07 19:50:45 +08008432 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008433 newBlockedState);
junyulai5ab727b2018-08-07 19:50:45 +08008434 }
8435 }
8436 }
8437
8438 /**
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008439 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulai5ab727b2018-08-07 19:50:45 +08008440 * @param uid The uid for which the rules changed.
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008441 * @param blockedReasons The reasons for why an uid is blocked.
junyulai5ab727b2018-08-07 19:50:45 +08008442 */
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008443 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008444 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai5ab727b2018-08-07 19:50:45 +08008445 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colittie8ce2052020-12-12 00:51:11 +09008446 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shankacb5fd4a2021-03-02 06:33:46 +00008447
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008448 final int oldBlockedState = getBlockedState(
8449 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8450 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8451 if (oldBlockedState == newBlockedState) {
junyulaiec82da12019-04-08 16:58:22 +08008452 continue;
junyulai5ab727b2018-08-07 19:50:45 +08008453 }
junyulai5ab727b2018-08-07 19:50:45 +08008454 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8455 NetworkRequest nr = nai.requestAt(i);
8456 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colittif2514122021-03-12 22:50:57 +09008457 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti60104f52021-03-18 00:54:57 +09008458 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8459 newBlockedState);
junyulai5ab727b2018-08-07 19:50:45 +08008460 }
8461 }
8462 }
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07008463 }
8464
Chalard Jean8cc4e872019-04-10 23:07:55 +09008465 @VisibleForTesting
8466 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittid55162b2014-07-31 23:20:17 +09008467 // The NetworkInfo we actually send out has no bearing on the real
8468 // state of affairs. For example, if the default connection is mobile,
8469 // and a request for HIPRI has just gone away, we need to pretend that
8470 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8471 // the state to DISCONNECTED, even though the network is of type MOBILE
8472 // and is still connected.
8473 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8474 info.setType(type);
Lorenzo Colitti386f9a32021-03-10 00:18:59 +09008475 filterForLegacyLockdown(info);
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008476 if (state != DetailedState.DISCONNECTED) {
8477 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klinee2d50122014-12-08 16:25:20 +09008478 sendConnectedBroadcast(info);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008479 } else {
Robert Greenwalt41c19a02015-06-24 13:23:42 -07008480 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt5a367872014-06-02 15:32:02 -07008481 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8482 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8483 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8484 if (info.isFailover()) {
8485 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8486 nai.networkInfo.setFailover(false);
8487 }
8488 if (info.getReason() != null) {
8489 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8490 }
8491 if (info.getExtraInfo() != null) {
8492 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8493 }
8494 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean1bc77a92021-02-04 13:12:59 +09008495 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattisf61f7be2021-01-31 17:06:19 -08008496 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt5a367872014-06-02 15:32:02 -07008497 if (newDefaultAgent != null) {
8498 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8499 newDefaultAgent.networkInfo);
8500 } else {
8501 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8502 }
8503 }
8504 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8505 mDefaultInetConditionPublished);
Erik Klinee2d50122014-12-08 16:25:20 +09008506 sendStickyBroadcast(intent);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008507 if (newDefaultAgent != null) {
Erik Klinee2d50122014-12-08 16:25:20 +09008508 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt5a367872014-06-02 15:32:02 -07008509 }
8510 }
8511 }
8512
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008513 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamac510b272018-10-16 12:50:33 +09008514 if (VDBG || DDBG) {
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09008515 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean373391b2019-12-10 21:07:02 +09008516 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi94f0bfc2017-03-22 17:07:57 +09008517 }
Lorenzo Colittie0d1a032016-07-01 01:37:11 +09008518 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8519 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt2bebbfb2014-03-26 16:47:06 -07008520 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8521 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin94c30992014-11-05 10:32:09 -08008522 if (nri.mPendingIntent == null) {
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008523 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin94c30992014-11-05 10:32:09 -08008524 } else {
8525 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8526 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008527 }
Robert Greenwaltdb6fac52014-04-18 15:25:25 -07008528 }
Robert Greenwalt54d534f2014-05-13 21:41:06 -07008529
Lorenzo Colitti70c70fa2016-07-01 01:53:25 +09008530 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8531 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8532 }
8533
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008534 /**
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008535 * Returns the list of all interfaces that could be used by network traffic that does not
8536 * explicitly specify a network. This includes the default network, but also all VPNs that are
8537 * currently connected.
8538 *
8539 * Must be called on the handler thread.
8540 */
junyulaic9a235a2021-01-26 15:29:15 +08008541 @NonNull
8542 private ArrayList<Network> getDefaultNetworks() {
Varun Anand5e980f42019-02-07 14:13:13 -08008543 ensureRunningOnConnectivityServiceThread();
James Mattis8af2d602020-12-20 11:09:58 -08008544 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattisf61f7be2021-01-31 17:06:19 -08008545 final Set<Integer> activeNetIds = new ArraySet<>();
8546 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8547 if (nri.isBeingSatisfied()) {
8548 activeNetIds.add(nri.getSatisfier().network().netId);
8549 }
8550 }
Remi NGUYEN VAN96be83b2020-12-23 12:45:08 +09008551 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisf61f7be2021-01-31 17:06:19 -08008552 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008553 defaultNetworks.add(nai.network);
8554 }
8555 }
junyulaic9a235a2021-01-26 15:29:15 +08008556 return defaultNetworks;
Lorenzo Colittia9dcce52018-01-19 00:50:48 +09008557 }
8558
8559 /**
Lorenzo Colittif8a48e12019-06-24 13:50:45 +09008560 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8561 * active iface's tracked properties has changed.
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008562 */
Jeff Davidson9804c892016-01-20 11:35:38 -08008563 private void notifyIfacesChangedForNetworkStats() {
Varun Anand5e980f42019-02-07 14:13:13 -08008564 ensureRunningOnConnectivityServiceThread();
8565 String activeIface = null;
8566 LinkProperties activeLinkProperties = getActiveLinkProperties();
8567 if (activeLinkProperties != null) {
8568 activeIface = activeLinkProperties.getInterfaceName();
8569 }
Benedict Wongb98e0692019-06-12 17:46:31 +00008570
junyulai62d35f72021-01-23 09:46:34 +08008571 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008572 try {
junyulai527859f2021-01-22 22:46:01 +08008573 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai92aff0d2021-03-05 14:46:25 +08008574 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulai527859f2021-01-22 22:46:01 +08008575 snapshots.add(snapshot);
8576 }
junyulaic9a235a2021-01-26 15:29:15 +08008577 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8578 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkey7c503b12014-12-08 14:50:12 -08008579 } catch (Exception ignored) {
8580 }
8581 }
8582
Sreeram Ramachandran1892fa52014-07-27 14:18:26 -07008583 @Override
Udam Saini53b71ee2016-01-04 12:16:14 -08008584 public String getCaptivePortalServerUrl() {
paulhud70b7dd2019-08-12 16:25:11 +08008585 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN46bcf552021-03-08 22:05:03 +09008586 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN9de89162021-03-19 17:41:48 +09008587 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgren741013d2018-12-07 11:08:04 +01008588
8589 if (!TextUtils.isEmpty(settingUrl)) {
8590 return settingUrl;
8591 }
8592
8593 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08008594 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgren741013d2018-12-07 11:08:04 +01008595 if (!TextUtils.isEmpty(settingUrl)) {
8596 return settingUrl;
8597 }
8598
8599 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Saini53b71ee2016-01-04 12:16:14 -08008600 }
8601
8602 @Override
junyulai9f872232019-01-16 20:23:34 +08008603 public void startNattKeepalive(Network network, int intervalSeconds,
8604 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008605 enforceKeepalivePermission();
8606 mKeepaliveTracker.startNattKeepalive(
junyulai61143782019-03-04 22:45:36 +08008607 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai9f872232019-01-16 20:23:34 +08008608 intervalSeconds, cb,
junyulai21c06d02019-01-03 18:50:15 +08008609 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008610 }
8611
8612 @Override
Chiachang Wang979f46a2021-01-19 15:35:03 +08008613 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai9f872232019-01-16 20:23:34 +08008614 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai48a59382019-01-15 11:32:44 +08008615 String dstAddr) {
Josh Gaobd97cc82020-06-16 15:58:11 -07008616 try {
Chiachang Wang979f46a2021-01-19 15:35:03 +08008617 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gaobd97cc82020-06-16 15:58:11 -07008618 mKeepaliveTracker.startNattKeepalive(
8619 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8620 intervalSeconds, cb,
8621 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8622 } finally {
8623 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8624 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang979f46a2021-01-19 15:35:03 +08008625 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8626 IoUtils.closeQuietly(pfd);
Josh Gaobd97cc82020-06-16 15:58:11 -07008627 }
8628 }
junyulai48a59382019-01-15 11:32:44 +08008629 }
8630
8631 @Override
Chiachang Wang979f46a2021-01-19 15:35:03 +08008632 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai9f872232019-01-16 20:23:34 +08008633 ISocketKeepaliveCallback cb) {
Josh Gaobd97cc82020-06-16 15:58:11 -07008634 try {
8635 enforceKeepalivePermission();
Chiachang Wang979f46a2021-01-19 15:35:03 +08008636 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gaobd97cc82020-06-16 15:58:11 -07008637 mKeepaliveTracker.startTcpKeepalive(
8638 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8639 } finally {
8640 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8641 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang979f46a2021-01-19 15:35:03 +08008642 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8643 IoUtils.closeQuietly(pfd);
Josh Gaobd97cc82020-06-16 15:58:11 -07008644 }
8645 }
junyulaic7ea1242019-01-08 20:04:33 +08008646 }
8647
8648 @Override
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008649 public void stopKeepalive(Network network, int slot) {
8650 mHandler.sendMessage(mHandler.obtainMessage(
junyulai21c06d02019-01-03 18:50:15 +08008651 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colittid1039d12015-06-15 14:29:22 +09008652 }
8653
8654 @Override
Stuart Scottca888bf2015-04-02 18:00:02 -07008655 public void factoryReset() {
paulhud70b7dd2019-08-12 16:25:11 +08008656 enforceSettingsPermission();
Stuart Scott493cca02015-04-20 14:07:45 -07008657
8658 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
8659 return;
8660 }
8661
lucaslin86086772020-12-17 04:14:35 +08008662 final long token = Binder.clearCallingIdentity();
8663 try {
Heemin Seogd5085f32019-06-12 09:21:44 -07008664 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8665 ipMemoryStore.factoryReset();
lucaslin86086772020-12-17 04:14:35 +08008666 } finally {
8667 Binder.restoreCallingIdentity(token);
8668 }
Xiao Ma51410062019-04-10 19:01:52 +09008669
Stuart Scottca888bf2015-04-02 18:00:02 -07008670 // Turn airplane mode off
8671 setAirplaneMode(false);
8672
Xiao Ma00ed6182019-06-12 16:31:14 +09008673 // restore private DNS settings to default mode (opportunistic)
8674 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_PRIVATE_DNS)) {
lucaslin30779882021-04-23 21:03:39 +08008675 ConnectivitySettingsManager.setPrivateDnsMode(mContext, PRIVATE_DNS_MODE_OPPORTUNISTIC);
Xiao Ma00ed6182019-06-12 16:31:14 +09008676 }
8677
Lorenzo Colitti477bf5c2016-09-15 14:02:29 +09008678 Settings.Global.putString(mContext.getContentResolver(),
paulhu1510c9c2021-03-17 17:19:09 +08008679 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottca888bf2015-04-02 18:00:02 -07008680 }
Paul Jensen8c23d5f2015-07-01 14:16:32 -04008681
Ricky Waid53cf002018-01-23 04:09:45 +00008682 @Override
8683 public byte[] getNetworkWatchlistConfigHash() {
8684 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8685 if (nwm == null) {
8686 loge("Unable to get NetworkWatchlistManager");
8687 return null;
8688 }
8689 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8690 return nwm.getWatchlistConfigHash();
8691 }
8692
Hugo Benichi3bdc8352016-05-31 16:28:06 +09008693 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiad9dc5b2017-11-11 08:06:43 +09008694 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayev284cb872020-12-07 22:43:07 -08008695 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Kline2e815d32016-04-14 17:30:59 +09008696 }
Hugo Benichi7f919fe2017-04-21 15:07:12 +09008697
8698 private static boolean toBool(int encodedBoolean) {
8699 return encodedBoolean != 0; // Only 0 means false.
8700 }
8701
8702 private static int encodeBool(boolean b) {
8703 return b ? 1 : 0;
8704 }
mswest46c6a5bcf2018-03-12 10:34:34 -07008705
8706 @Override
Chiachang Wang0efaff82020-10-12 15:20:07 +08008707 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8708 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8709 @NonNull String[] args) {
8710 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8711 err.getFileDescriptor(), args);
mswest46c6a5bcf2018-03-12 10:34:34 -07008712 }
8713
Chiachang Wang0efaff82020-10-12 15:20:07 +08008714 private class ShellCmd extends BasicShellCommandHandler {
mswest46c6a5bcf2018-03-12 10:34:34 -07008715 @Override
8716 public int onCommand(String cmd) {
8717 if (cmd == null) {
8718 return handleDefaultCommands(cmd);
8719 }
8720 final PrintWriter pw = getOutPrintWriter();
8721 try {
8722 switch (cmd) {
8723 case "airplane-mode":
8724 final String action = getNextArg();
8725 if ("enable".equals(action)) {
8726 setAirplaneMode(true);
8727 return 0;
8728 } else if ("disable".equals(action)) {
8729 setAirplaneMode(false);
8730 return 0;
8731 } else if (action == null) {
8732 final ContentResolver cr = mContext.getContentResolver();
8733 final int enabled = Settings.Global.getInt(cr,
8734 Settings.Global.AIRPLANE_MODE_ON);
8735 pw.println(enabled == 0 ? "disabled" : "enabled");
8736 return 0;
8737 } else {
8738 onHelp();
8739 return -1;
8740 }
8741 default:
8742 return handleDefaultCommands(cmd);
8743 }
8744 } catch (Exception e) {
8745 pw.println(e);
8746 }
8747 return -1;
8748 }
8749
8750 @Override
8751 public void onHelp() {
8752 PrintWriter pw = getOutPrintWriter();
8753 pw.println("Connectivity service commands:");
8754 pw.println(" help");
8755 pw.println(" Print this help text.");
8756 pw.println(" airplane-mode [enable|disable]");
8757 pw.println(" Turn airplane mode on or off.");
8758 pw.println(" airplane-mode");
8759 pw.println(" Get airplane mode.");
8760 }
8761 }
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008762
Remi NGUYEN VAN52950ed2021-03-06 00:11:24 +09008763 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittibd015f42021-02-04 00:18:27 +09008764 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8765 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8766 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang2e98f6c2021-04-20 15:41:24 +08008767 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008768 }
8769
8770 /**
8771 * @param connectionInfo the connection to resolve.
8772 * @return {@code uid} if the connection is found and the app has permission to observe it
8773 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8774 * connection is not found.
8775 */
8776 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008777 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8778 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8779 }
8780
Lorenzo Colittidbcd5d62021-02-04 01:47:38 +09008781 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008782 connectionInfo.local, connectionInfo.remote);
8783
Lorenzo Colittibd015f42021-02-04 00:18:27 +09008784 if (uid == INVALID_UID) return uid; // Not found.
8785
8786 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8787 // VPN, if any, that applies to the UID that owns the connection.
8788 if (checkNetworkStackPermission()) return uid;
8789
8790 final NetworkAgentInfo vpn = getVpnForUid(uid);
8791 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colittie0857092021-03-12 22:39:08 +09008792 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoepe7205d62018-07-23 10:57:53 -07008793 return INVALID_UID;
8794 }
8795
8796 return uid;
8797 }
Pavel Grafov23d65702018-12-14 13:51:07 +00008798
Benedict Wong7f6071d2018-11-09 14:45:34 -08008799 /**
8800 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8801 *
8802 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8803 */
8804 @Override
8805 public IBinder startOrGetTestNetworkService() {
8806 synchronized (mTNSLock) {
8807 TestNetworkService.enforceTestNetworkPermissions(mContext);
8808
8809 if (mTNS == null) {
lucaslind5d3dc12021-02-24 13:49:42 +08008810 mTNS = new TestNetworkService(mContext);
Benedict Wong7f6071d2018-11-09 14:45:34 -08008811 }
8812
8813 return mTNS;
8814 }
8815 }
Cody Kesting9c69dd42019-12-17 12:55:28 -08008816
Cody Kesting0ffbf922019-12-18 10:57:50 -08008817 /**
8818 * Handler used for managing all Connectivity Diagnostics related functions.
8819 *
8820 * @see android.net.ConnectivityDiagnosticsManager
8821 *
8822 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8823 */
8824 @VisibleForTesting
8825 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kestinga58c07c2020-01-07 11:18:54 -08008826 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8827
Cody Kesting0ffbf922019-12-18 10:57:50 -08008828 /**
8829 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8830 * android.net.ConnectivityDiagnosticsManager}.
8831 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8832 * NetworkRequestInfo to be registered
8833 */
8834 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8835
8836 /**
8837 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
8838 * android.net.ConnectivityDiagnosticsManager}.
8839 * obj = the IConnectivityDiagnosticsCallback to be unregistered
8840 * arg1 = the uid of the caller
8841 */
8842 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
8843
Cody Kestingd292a332020-01-05 14:06:39 -08008844 /**
8845 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
8846 * after processing {@link #EVENT_NETWORK_TESTED} events.
8847 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
8848 * NetworkMonitor.
8849 * data = PersistableBundle of extras passed from NetworkMonitor.
8850 *
8851 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
8852 */
8853 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
8854
Cody Kesting1d326382020-01-06 16:55:35 -08008855 /**
8856 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
8857 * been detected on the network.
8858 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
8859 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
8860 * arg2 = NetID.
8861 * data = PersistableBundle of extras passed from NetworkMonitor.
8862 */
8863 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
8864
Cody Kestinga58c07c2020-01-07 11:18:54 -08008865 /**
8866 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
8867 * the platform. This event will invoke {@link
8868 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
8869 * callbacks.
8870 * obj = Network that was reported on
8871 * arg1 = boolint for the quality reported
8872 */
8873 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
8874
Cody Kesting0ffbf922019-12-18 10:57:50 -08008875 private ConnectivityDiagnosticsHandler(Looper looper) {
8876 super(looper);
8877 }
8878
8879 @Override
8880 public void handleMessage(Message msg) {
8881 switch (msg.what) {
8882 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8883 handleRegisterConnectivityDiagnosticsCallback(
8884 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
8885 break;
8886 }
8887 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8888 handleUnregisterConnectivityDiagnosticsCallback(
8889 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
8890 break;
8891 }
Cody Kestingd292a332020-01-05 14:06:39 -08008892 case EVENT_NETWORK_TESTED: {
8893 final ConnectivityReportEvent reportEvent =
8894 (ConnectivityReportEvent) msg.obj;
8895
Aaron Huang0d1be642021-01-21 15:47:41 +08008896 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kestingd292a332020-01-05 14:06:39 -08008897 break;
8898 }
Cody Kesting1d326382020-01-06 16:55:35 -08008899 case EVENT_DATA_STALL_SUSPECTED: {
8900 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang0d1be642021-01-21 15:47:41 +08008901 final Pair<Long, PersistableBundle> arg =
8902 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kesting1d326382020-01-06 16:55:35 -08008903 if (nai == null) break;
8904
Aaron Huang0d1be642021-01-21 15:47:41 +08008905 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kesting1d326382020-01-06 16:55:35 -08008906 break;
8907 }
Cody Kestinga58c07c2020-01-07 11:18:54 -08008908 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
8909 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
8910 break;
8911 }
8912 default: {
8913 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
8914 }
Cody Kesting0ffbf922019-12-18 10:57:50 -08008915 }
8916 }
8917 }
8918
8919 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
8920 @VisibleForTesting
8921 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
8922 @NonNull private final IConnectivityDiagnosticsCallback mCb;
8923 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kestingd292a332020-01-05 14:06:39 -08008924 @NonNull private final String mCallingPackageName;
Cody Kesting0ffbf922019-12-18 10:57:50 -08008925
8926 @VisibleForTesting
8927 ConnectivityDiagnosticsCallbackInfo(
Cody Kestingd292a332020-01-05 14:06:39 -08008928 @NonNull IConnectivityDiagnosticsCallback cb,
8929 @NonNull NetworkRequestInfo nri,
8930 @NonNull String callingPackageName) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08008931 mCb = cb;
8932 mRequestInfo = nri;
Cody Kestingd292a332020-01-05 14:06:39 -08008933 mCallingPackageName = callingPackageName;
Cody Kesting0ffbf922019-12-18 10:57:50 -08008934 }
8935
8936 @Override
8937 public void binderDied() {
8938 log("ConnectivityDiagnosticsCallback IBinder died.");
8939 unregisterConnectivityDiagnosticsCallback(mCb);
8940 }
8941 }
8942
Cody Kestingd292a332020-01-05 14:06:39 -08008943 /**
8944 * Class used for sending information from {@link
8945 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
8946 */
8947 private static class NetworkTestedResults {
8948 private final int mNetId;
8949 private final int mTestResult;
8950 private final long mTimestampMillis;
8951 @Nullable private final String mRedirectUrl;
8952
8953 private NetworkTestedResults(
8954 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
8955 mNetId = netId;
8956 mTestResult = testResult;
8957 mTimestampMillis = timestampMillis;
8958 mRedirectUrl = redirectUrl;
8959 }
8960 }
8961
8962 /**
8963 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
8964 * ConnectivityDiagnosticsHandler}.
8965 */
8966 private static class ConnectivityReportEvent {
8967 private final long mTimestampMillis;
8968 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang0d1be642021-01-21 15:47:41 +08008969 private final PersistableBundle mExtras;
Cody Kestingd292a332020-01-05 14:06:39 -08008970
Aaron Huang0d1be642021-01-21 15:47:41 +08008971 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
8972 PersistableBundle p) {
Cody Kestingd292a332020-01-05 14:06:39 -08008973 mTimestampMillis = timestampMillis;
8974 mNai = nai;
Aaron Huang0d1be642021-01-21 15:47:41 +08008975 mExtras = p;
Cody Kestingd292a332020-01-05 14:06:39 -08008976 }
8977 }
8978
Cody Kesting0ffbf922019-12-18 10:57:50 -08008979 private void handleRegisterConnectivityDiagnosticsCallback(
8980 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
8981 ensureRunningOnConnectivityServiceThread();
8982
8983 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting0c55a302020-03-05 10:46:02 -08008984 final IBinder iCb = cb.asBinder();
Cody Kesting0ffbf922019-12-18 10:57:50 -08008985 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
8986
James Mattis65d0d1c2020-11-24 17:40:49 -08008987 // Connectivity Diagnostics are meant to be used with a single network request. It would be
8988 // confusing for these networks to change when an NRI is satisfied in another layer.
8989 if (nri.isMultilayerRequest()) {
8990 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
8991 + "network requests.");
8992 }
8993
Cody Kesting0ffbf922019-12-18 10:57:50 -08008994 // This means that the client registered the same callback multiple times. Do
8995 // not override the previous entry, and exit silently.
Cody Kesting0c55a302020-03-05 10:46:02 -08008996 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08008997 if (VDBG) log("Diagnostics callback is already registered");
8998
8999 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9000 // incremented when the NetworkRequestInfo is created as part of
9001 // enforceRequestCountLimit().
Chalard Jean70b2d9a2021-04-01 16:41:04 +09009002 nri.decrementRequestCount();
Cody Kesting0ffbf922019-12-18 10:57:50 -08009003 return;
9004 }
9005
Cody Kesting0c55a302020-03-05 10:46:02 -08009006 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009007
9008 try {
Cody Kesting0c55a302020-03-05 10:46:02 -08009009 iCb.linkToDeath(cbInfo, 0);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009010 } catch (RemoteException e) {
9011 cbInfo.binderDied();
Cody Kesting905b4752020-02-12 14:50:58 -08009012 return;
9013 }
9014
9015 // Once registered, provide ConnectivityReports for matching Networks
9016 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9017 synchronized (mNetworkForNetId) {
9018 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9019 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis65d0d1c2020-11-24 17:40:49 -08009020 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9021 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kesting905b4752020-02-12 14:50:58 -08009022 matchingNetworks.add(nai);
9023 }
9024 }
9025 }
9026 for (final NetworkAgentInfo nai : matchingNetworks) {
9027 final ConnectivityReport report = nai.getConnectivityReport();
9028 if (report == null) {
9029 continue;
9030 }
9031 if (!checkConnectivityDiagnosticsPermissions(
9032 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9033 continue;
9034 }
9035
9036 try {
9037 cb.onConnectivityReportAvailable(report);
9038 } catch (RemoteException e) {
9039 // Exception while sending the ConnectivityReport. Move on to the next network.
9040 }
Cody Kesting0ffbf922019-12-18 10:57:50 -08009041 }
9042 }
9043
9044 private void handleUnregisterConnectivityDiagnosticsCallback(
9045 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9046 ensureRunningOnConnectivityServiceThread();
Cody Kesting0c55a302020-03-05 10:46:02 -08009047 final IBinder iCb = cb.asBinder();
Cody Kesting0ffbf922019-12-18 10:57:50 -08009048
Cody Kesting970e7792020-03-30 12:43:49 -07009049 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9050 mConnectivityDiagnosticsCallbacks.remove(iCb);
9051 if (cbInfo == null) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08009052 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9053 return;
9054 }
9055
Cody Kesting970e7792020-03-30 12:43:49 -07009056 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting0ffbf922019-12-18 10:57:50 -08009057
Cody Kesting054451e2020-12-02 12:16:56 -08009058 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9059 // (if the Binder died)
9060 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9061 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting0ffbf922019-12-18 10:57:50 -08009062 return;
9063 }
9064
Cody Kestingfc14fbe2020-03-04 13:35:20 -08009065 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9066 // incremented when the NetworkRequestInfo is created as part of
9067 // enforceRequestCountLimit().
Chalard Jean70b2d9a2021-04-01 16:41:04 +09009068 nri.decrementRequestCount();
Cody Kestingfc14fbe2020-03-04 13:35:20 -08009069
Cody Kesting0c55a302020-03-05 10:46:02 -08009070 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009071 }
9072
Cody Kestingd292a332020-01-05 14:06:39 -08009073 private void handleNetworkTestedWithExtras(
9074 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9075 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting2abe6112020-02-11 10:03:26 -08009076 final NetworkCapabilities networkCapabilities =
Cody Kesting70897532020-03-05 22:13:31 -08009077 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingd292a332020-01-05 14:06:39 -08009078 final ConnectivityReport report =
9079 new ConnectivityReport(
9080 reportEvent.mNai.network,
9081 reportEvent.mTimestampMillis,
9082 nai.linkProperties,
Cody Kesting2abe6112020-02-11 10:03:26 -08009083 networkCapabilities,
Cody Kestingd292a332020-01-05 14:06:39 -08009084 extras);
Cody Kesting905b4752020-02-12 14:50:58 -08009085 nai.setConnectivityReport(report);
Cody Kestingd292a332020-01-05 14:06:39 -08009086 final List<IConnectivityDiagnosticsCallback> results =
9087 getMatchingPermissionedCallbacks(nai);
9088 for (final IConnectivityDiagnosticsCallback cb : results) {
9089 try {
Cody Kestinge4d2df52020-03-05 15:19:48 -08009090 cb.onConnectivityReportAvailable(report);
Cody Kestingd292a332020-01-05 14:06:39 -08009091 } catch (RemoteException ex) {
9092 loge("Error invoking onConnectivityReport", ex);
9093 }
9094 }
9095 }
9096
Cody Kesting1d326382020-01-06 16:55:35 -08009097 private void handleDataStallSuspected(
9098 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9099 @NonNull PersistableBundle extras) {
Cody Kesting2abe6112020-02-11 10:03:26 -08009100 final NetworkCapabilities networkCapabilities =
Cody Kesting70897532020-03-05 22:13:31 -08009101 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting1d326382020-01-06 16:55:35 -08009102 final DataStallReport report =
Cody Kesting4a773072020-02-04 21:52:09 -08009103 new DataStallReport(
9104 nai.network,
9105 timestampMillis,
9106 detectionMethod,
9107 nai.linkProperties,
Cody Kesting2abe6112020-02-11 10:03:26 -08009108 networkCapabilities,
Cody Kesting4a773072020-02-04 21:52:09 -08009109 extras);
Cody Kesting1d326382020-01-06 16:55:35 -08009110 final List<IConnectivityDiagnosticsCallback> results =
9111 getMatchingPermissionedCallbacks(nai);
9112 for (final IConnectivityDiagnosticsCallback cb : results) {
9113 try {
9114 cb.onDataStallSuspected(report);
9115 } catch (RemoteException ex) {
9116 loge("Error invoking onDataStallSuspected", ex);
9117 }
9118 }
9119 }
9120
Cody Kestinga58c07c2020-01-07 11:18:54 -08009121 private void handleNetworkConnectivityReported(
9122 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9123 final List<IConnectivityDiagnosticsCallback> results =
9124 getMatchingPermissionedCallbacks(nai);
9125 for (final IConnectivityDiagnosticsCallback cb : results) {
9126 try {
9127 cb.onNetworkConnectivityReported(nai.network, connectivity);
9128 } catch (RemoteException ex) {
9129 loge("Error invoking onNetworkConnectivityReported", ex);
9130 }
9131 }
9132 }
9133
Cody Kesting70897532020-03-05 22:13:31 -08009134 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colittib8756a82021-05-10 00:49:14 +09009135 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9136 NetworkCapabilities.REDACT_ALL);
Cody Kesting70897532020-03-05 22:13:31 -08009137 sanitized.setUids(null);
9138 sanitized.setAdministratorUids(new int[0]);
9139 sanitized.setOwnerUid(Process.INVALID_UID);
9140 return sanitized;
Cody Kesting2abe6112020-02-11 10:03:26 -08009141 }
9142
Cody Kestingd292a332020-01-05 14:06:39 -08009143 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9144 @NonNull NetworkAgentInfo nai) {
9145 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting0c55a302020-03-05 10:46:02 -08009146 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kestingd292a332020-01-05 14:06:39 -08009147 mConnectivityDiagnosticsCallbacks.entrySet()) {
9148 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9149 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
James Mattis65d0d1c2020-11-24 17:40:49 -08009150 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9151 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingd292a332020-01-05 14:06:39 -08009152 if (checkConnectivityDiagnosticsPermissions(
9153 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
Cody Kesting0c55a302020-03-05 10:46:02 -08009154 results.add(entry.getValue().mCb);
Cody Kestingd292a332020-01-05 14:06:39 -08009155 }
9156 }
9157 }
9158 return results;
9159 }
9160
Cody Kesting9f4273a2021-05-20 22:57:07 +00009161 private boolean hasLocationPermission(String packageName, int uid) {
9162 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9163 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9164 // call in a try-catch.
9165 try {
9166 if (!mLocationPermissionChecker.checkLocationPermission(
9167 packageName, null /* featureId */, uid, null /* message */)) {
9168 return false;
9169 }
9170 } catch (SecurityException e) {
9171 return false;
9172 }
9173
9174 return true;
9175 }
9176
9177 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9178 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
9179 if (virtual.supportsUnderlyingNetworks()
9180 && virtual.networkCapabilities.getOwnerUid() == uid
9181 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9182 return true;
9183 }
9184 }
9185
9186 return false;
9187 }
9188
Cody Kestingd292a332020-01-05 14:06:39 -08009189 @VisibleForTesting
9190 boolean checkConnectivityDiagnosticsPermissions(
9191 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9192 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9193 return true;
9194 }
9195
Cody Kesting9f4273a2021-05-20 22:57:07 +00009196 // Administrator UIDs also contains the Owner UID
9197 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9198 if (!CollectionUtils.contains(administratorUids, callbackUid)
9199 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kestingd292a332020-01-05 14:06:39 -08009200 return false;
9201 }
9202
Cody Kesting9f4273a2021-05-20 22:57:07 +00009203 return hasLocationPermission(callbackPackageName, callbackUid);
Cody Kestingd292a332020-01-05 14:06:39 -08009204 }
9205
Cody Kesting9c69dd42019-12-17 12:55:28 -08009206 @Override
9207 public void registerConnectivityDiagnosticsCallback(
Cody Kestingd292a332020-01-05 14:06:39 -08009208 @NonNull IConnectivityDiagnosticsCallback callback,
9209 @NonNull NetworkRequest request,
9210 @NonNull String callingPackageName) {
Cody Kesting0ffbf922019-12-18 10:57:50 -08009211 if (request.legacyType != TYPE_NONE) {
9212 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9213 + " Please use NetworkCapabilities instead.");
9214 }
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009215 final int callingUid = mDeps.getCallingUid();
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08009216 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009217
9218 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9219 // and administrator uids to be safe.
9220 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius1cbb1ae2020-01-16 12:17:17 -08009221 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009222
9223 final NetworkRequest requestWithId =
9224 new NetworkRequest(
9225 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9226
9227 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9228 //
9229 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9230 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9231 // callback's binder death.
Lorenzo Colittif2514122021-03-12 22:50:57 +09009232 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009233 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kestingd292a332020-01-05 14:06:39 -08009234 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting0ffbf922019-12-18 10:57:50 -08009235
9236 mConnectivityDiagnosticsHandler.sendMessage(
9237 mConnectivityDiagnosticsHandler.obtainMessage(
9238 ConnectivityDiagnosticsHandler
9239 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9240 cbInfo));
Cody Kesting9c69dd42019-12-17 12:55:28 -08009241 }
9242
9243 @Override
9244 public void unregisterConnectivityDiagnosticsCallback(
9245 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huang6a16a412021-04-09 12:06:42 +08009246 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting0ffbf922019-12-18 10:57:50 -08009247 mConnectivityDiagnosticsHandler.sendMessage(
9248 mConnectivityDiagnosticsHandler.obtainMessage(
9249 ConnectivityDiagnosticsHandler
9250 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009251 mDeps.getCallingUid(),
Cody Kesting0ffbf922019-12-18 10:57:50 -08009252 0,
9253 callback));
Cody Kesting9c69dd42019-12-17 12:55:28 -08009254 }
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009255
9256 @Override
9257 public void simulateDataStall(int detectionMethod, long timestampMillis,
9258 @NonNull Network network, @NonNull PersistableBundle extras) {
9259 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9260 android.Manifest.permission.NETWORK_STACK);
9261 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9262 if (!nc.hasTransport(TRANSPORT_TEST)) {
9263 throw new SecurityException("Data Stall simluation is only possible for test networks");
9264 }
9265
9266 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittieb862ae2020-12-15 11:02:22 +09009267 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009268 throw new SecurityException("Data Stall simulation is only possible for network "
9269 + "creators");
9270 }
9271
Cody Kesting51691052020-05-21 12:08:21 -07009272 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9273 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9274 // Data Stall information as a DataStallReportParcelable and passing to
9275 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9276 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kesting43a47ef2020-05-15 10:36:01 -07009277 final DataStallReportParcelable p = new DataStallReportParcelable();
9278 p.timestampMillis = timestampMillis;
9279 p.detectionMethod = detectionMethod;
9280
9281 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9282 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9283 }
9284 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9285 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9286 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9287 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9288 }
9289
Serik Beketayev284cb872020-12-07 22:43:07 -08009290 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingb5c7abd2020-04-15 12:33:28 -07009291 }
lucaslin6d502ed2021-01-21 02:02:55 +08009292
lucaslindb201da2021-02-23 01:12:55 +08009293 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9294 @Override
lucasline17f3472021-02-25 15:10:29 +08009295 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslindb201da2021-02-23 01:12:55 +08009296 long timestampNs, int uid) {
lucasline17f3472021-02-25 15:10:29 +08009297 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslindb201da2021-02-23 01:12:55 +08009298 }
lucaslin357f5862021-01-21 19:48:09 +08009299
9300 @Override
9301 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucasline17f3472021-02-25 15:10:29 +08009302 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin357f5862021-01-21 19:48:09 +08009303 nai.clatd.interfaceLinkStateChanged(iface, up);
9304 }
9305 }
9306
9307 @Override
9308 public void onInterfaceRemoved(String iface) {
lucasline17f3472021-02-25 15:10:29 +08009309 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin357f5862021-01-21 19:48:09 +08009310 nai.clatd.interfaceRemoved(iface);
9311 }
lucaslindb201da2021-02-23 01:12:55 +08009312 }
9313 }
9314
lucaslin6d502ed2021-01-21 02:02:55 +08009315 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9316
9317 /**
9318 * Class used for updating network activity tracking with netd and notify network activity
9319 * changes.
9320 */
9321 private static final class LegacyNetworkActivityTracker {
lucaslin32028e02021-01-21 02:03:17 +08009322 private static final int NO_UID = -1;
lucaslin6d502ed2021-01-21 02:02:55 +08009323 private final Context mContext;
lucaslina5e9bdb2021-01-21 02:04:15 +08009324 private final INetd mNetd;
lucaslina5e9bdb2021-01-21 02:04:15 +08009325 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9326 new RemoteCallbackList<>();
9327 // Indicate the current system default network activity is active or not.
9328 @GuardedBy("mActiveIdleTimers")
9329 private boolean mNetworkActive;
9330 @GuardedBy("mActiveIdleTimers")
9331 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9332 private final Handler mHandler;
lucaslin6d502ed2021-01-21 02:02:55 +08009333
lucaslina5e9bdb2021-01-21 02:04:15 +08009334 private class IdleTimerParams {
9335 public final int timeout;
9336 public final int transportType;
9337
9338 IdleTimerParams(int timeout, int transport) {
9339 this.timeout = timeout;
9340 this.transportType = transport;
9341 }
9342 }
9343
9344 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslinea5378c2021-02-20 18:59:47 +08009345 @NonNull INetd netd) {
lucaslin6d502ed2021-01-21 02:02:55 +08009346 mContext = context;
lucaslina5e9bdb2021-01-21 02:04:15 +08009347 mNetd = netd;
9348 mHandler = handler;
lucaslin6d502ed2021-01-21 02:02:55 +08009349 }
9350
lucaslindb201da2021-02-23 01:12:55 +08009351 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9352 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9353 synchronized (mActiveIdleTimers) {
9354 mNetworkActive = active;
9355 // If there are no idle timers, it means that system is not monitoring
9356 // activity, so the system default network for those default network
9357 // unspecified apps is always considered active.
9358 //
9359 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9360 // any network activity change event. Whenever this event is received,
9361 // the mActiveIdleTimers should be always not empty. The legacy behavior
9362 // is no-op. Remove to refer to mNetworkActive only.
9363 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9364 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9365 }
9366 }
9367 }
lucaslin6d502ed2021-01-21 02:02:55 +08009368
lucaslina5e9bdb2021-01-21 02:04:15 +08009369 // The network activity should only be updated from ConnectivityService handler thread
9370 // when mActiveIdleTimers lock is held.
9371 @GuardedBy("mActiveIdleTimers")
9372 private void reportNetworkActive() {
9373 final int length = mNetworkActivityListeners.beginBroadcast();
9374 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9375 try {
9376 for (int i = 0; i < length; i++) {
9377 try {
9378 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9379 } catch (RemoteException | RuntimeException e) {
9380 loge("Fail to send network activie to listener " + e);
9381 }
9382 }
9383 } finally {
9384 mNetworkActivityListeners.finishBroadcast();
9385 }
9386 }
9387
9388 @GuardedBy("mActiveIdleTimers")
9389 public void handleReportNetworkActivity() {
9390 synchronized (mActiveIdleTimers) {
9391 reportNetworkActive();
9392 }
9393 }
9394
lucaslin6d502ed2021-01-21 02:02:55 +08009395 // This is deprecated and only to support legacy use cases.
9396 private int transportTypeToLegacyType(int type) {
9397 switch (type) {
9398 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009399 return TYPE_MOBILE;
lucaslin6d502ed2021-01-21 02:02:55 +08009400 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009401 return TYPE_WIFI;
lucaslin6d502ed2021-01-21 02:02:55 +08009402 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009403 return TYPE_BLUETOOTH;
lucaslin6d502ed2021-01-21 02:02:55 +08009404 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN9f992282021-03-09 13:35:25 +09009405 return TYPE_ETHERNET;
lucaslin6d502ed2021-01-21 02:02:55 +08009406 default:
9407 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9408 }
9409 return ConnectivityManager.TYPE_NONE;
9410 }
9411
9412 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9413 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9414 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9415 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9416 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9417 final long ident = Binder.clearCallingIdentity();
9418 try {
9419 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9420 RECEIVE_DATA_ACTIVITY_CHANGE,
9421 null /* resultReceiver */,
9422 null /* scheduler */,
9423 0 /* initialCode */,
9424 null /* initialData */,
9425 null /* initialExtra */);
9426 } finally {
9427 Binder.restoreCallingIdentity(ident);
9428 }
9429 }
9430
9431 /**
9432 * Setup data activity tracking for the given network.
9433 *
9434 * Every {@code setupDataActivityTracking} should be paired with a
9435 * {@link #removeDataActivityTracking} for cleanup.
9436 */
9437 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9438 final String iface = networkAgent.linkProperties.getInterfaceName();
9439
9440 final int timeout;
9441 final int type;
9442
9443 if (networkAgent.networkCapabilities.hasTransport(
9444 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9445 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08009446 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin6d502ed2021-01-21 02:02:55 +08009447 10);
9448 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9449 } else if (networkAgent.networkCapabilities.hasTransport(
9450 NetworkCapabilities.TRANSPORT_WIFI)) {
9451 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu79260c22021-03-17 20:30:33 +08009452 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin6d502ed2021-01-21 02:02:55 +08009453 15);
9454 type = NetworkCapabilities.TRANSPORT_WIFI;
9455 } else {
9456 return; // do not track any other networks
9457 }
9458
lucaslin32028e02021-01-21 02:03:17 +08009459 updateRadioPowerState(true /* isActive */, type);
9460
lucaslin6d502ed2021-01-21 02:02:55 +08009461 if (timeout > 0 && iface != null) {
9462 try {
lucaslina5e9bdb2021-01-21 02:04:15 +08009463 synchronized (mActiveIdleTimers) {
9464 // Networks start up.
9465 mNetworkActive = true;
9466 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9467 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9468 reportNetworkActive();
9469 }
lucaslin6d502ed2021-01-21 02:02:55 +08009470 } catch (Exception e) {
9471 // You shall not crash!
9472 loge("Exception in setupDataActivityTracking " + e);
9473 }
9474 }
9475 }
9476
9477 /**
9478 * Remove data activity tracking when network disconnects.
9479 */
9480 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9481 final String iface = networkAgent.linkProperties.getInterfaceName();
9482 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9483
lucaslin32028e02021-01-21 02:03:17 +08009484 if (iface == null) return;
9485
9486 final int type;
9487 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9488 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9489 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9490 type = NetworkCapabilities.TRANSPORT_WIFI;
9491 } else {
9492 return; // do not track any other networks
9493 }
9494
9495 try {
9496 updateRadioPowerState(false /* isActive */, type);
lucaslina5e9bdb2021-01-21 02:04:15 +08009497 synchronized (mActiveIdleTimers) {
9498 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9499 // The call fails silently if no idle timer setup for this interface
9500 mNetd.idletimerRemoveInterface(iface, params.timeout,
9501 Integer.toString(params.transportType));
lucaslin6d502ed2021-01-21 02:02:55 +08009502 }
lucaslin32028e02021-01-21 02:03:17 +08009503 } catch (Exception e) {
9504 // You shall not crash!
9505 loge("Exception in removeDataActivityTracking " + e);
lucaslin6d502ed2021-01-21 02:02:55 +08009506 }
9507 }
9508
9509 /**
9510 * Update data activity tracking when network state is updated.
9511 */
9512 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9513 NetworkAgentInfo oldNetwork) {
9514 if (newNetwork != null) {
9515 setupDataActivityTracking(newNetwork);
9516 }
9517 if (oldNetwork != null) {
9518 removeDataActivityTracking(oldNetwork);
9519 }
9520 }
lucaslin32028e02021-01-21 02:03:17 +08009521
9522 private void updateRadioPowerState(boolean isActive, int transportType) {
9523 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9524 switch (transportType) {
9525 case NetworkCapabilities.TRANSPORT_CELLULAR:
9526 bs.reportMobileRadioPowerState(isActive, NO_UID);
9527 break;
9528 case NetworkCapabilities.TRANSPORT_WIFI:
9529 bs.reportWifiRadioPowerState(isActive, NO_UID);
9530 break;
9531 default:
9532 logw("Untracked transport type:" + transportType);
9533 }
9534 }
lucaslina5e9bdb2021-01-21 02:04:15 +08009535
9536 public boolean isDefaultNetworkActive() {
9537 synchronized (mActiveIdleTimers) {
9538 // If there are no idle timers, it means that system is not monitoring activity,
9539 // so the default network is always considered active.
9540 //
9541 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9542 // tracking is disabled (negative idle timer value configured), or no active default
9543 // network. In the latter case, this reports active but it should report inactive.
9544 return mNetworkActive || mActiveIdleTimers.isEmpty();
9545 }
9546 }
9547
9548 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9549 mNetworkActivityListeners.register(l);
9550 }
9551
9552 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9553 mNetworkActivityListeners.unregister(l);
9554 }
lucaslin3756fcc2021-01-21 02:04:35 +08009555
9556 public void dump(IndentingPrintWriter pw) {
9557 synchronized (mActiveIdleTimers) {
9558 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9559 pw.println("Idle timers:");
9560 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9561 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9562 final IdleTimerParams params = ent.getValue();
9563 pw.print(" timeout="); pw.print(params.timeout);
9564 pw.print(" type="); pw.println(params.transportType);
9565 }
9566 }
9567 }
lucaslin6d502ed2021-01-21 02:02:55 +08009568 }
James Mattised87a672021-01-01 14:13:35 -08009569
Daniel Bright60f02ed2020-06-15 16:10:01 -07009570 /**
9571 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9572 *
9573 * @param socketInfo the socket information
9574 * @param callback the callback to register
9575 */
9576 @Override
9577 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9578 @NonNull final IQosCallback callback) {
9579 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9580 if (nai == null || nai.networkCapabilities == null) {
9581 try {
9582 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9583 } catch (final RemoteException ex) {
9584 loge("registerQosCallbackInternal: RemoteException", ex);
9585 }
9586 return;
9587 }
9588 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9589 }
9590
9591 /**
9592 * Register a {@link IQosCallback} with base {@link QosFilter}.
9593 *
9594 * @param filter the filter to register
9595 * @param callback the callback to register
9596 * @param nai the agent information related to the filter's network
9597 */
9598 @VisibleForTesting
9599 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9600 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9601 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9602 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9603
9604 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9605 enforceConnectivityRestrictedNetworksPermission();
9606 }
9607 mQosCallbackTracker.registerCallback(callback, filter, nai);
9608 }
9609
9610 /**
9611 * Unregisters the given callback.
9612 *
9613 * @param callback the callback to unregister
9614 */
9615 @Override
9616 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huang6a16a412021-04-09 12:06:42 +08009617 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Bright60f02ed2020-06-15 16:10:01 -07009618 mQosCallbackTracker.unregisterCallback(callback);
9619 }
James Mattised87a672021-01-01 14:13:35 -08009620
Chalard Jean9d968182021-02-25 21:46:34 +09009621 // Network preference per-profile and OEM network preferences can't be set at the same
9622 // time, because it is unclear what should happen if both preferences are active for
9623 // one given UID. To make it possible, the stack would have to clarify what would happen
9624 // in case both are active at the same time. The implementation may have to be adjusted
9625 // to implement the resulting rules. For example, a priority could be defined between them,
9626 // where the OEM preference would be considered less or more important than the enterprise
9627 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9628 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9629 // are set at the right level. Other solutions are possible, e.g. merging of the
9630 // preferences for the relevant UIDs.
9631 private static void throwConcurrentPreferenceException() {
9632 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9633 + "set OemNetworkPreference at the same time");
James Mattis6e6fabf2021-01-10 14:24:24 -08009634 }
9635
9636 /**
Chalard Jean03433052021-02-25 17:23:40 +09009637 * Request that a user profile is put by default on a network matching a given preference.
9638 *
9639 * See the documentation for the individual preferences for a description of the supported
9640 * behaviors.
9641 *
9642 * @param profile the profile concerned.
9643 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9644 * constants.
9645 * @param listener an optional listener to listen for completion of the operation.
9646 */
9647 @Override
9648 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9649 @ConnectivityManager.ProfileNetworkPreference final int preference,
9650 @Nullable final IOnCompleteListener listener) {
Chalard Jean9d968182021-02-25 21:46:34 +09009651 Objects.requireNonNull(profile);
9652 PermissionUtils.enforceNetworkStackPermission(mContext);
9653 if (DBG) {
9654 log("setProfileNetworkPreference " + profile + " to " + preference);
9655 }
9656 if (profile.getIdentifier() < 0) {
9657 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9658 + "UserHandle.CURRENT not supported)");
9659 }
Chalard Jean0a04bdb2021-04-02 19:24:44 +09009660 final UserManager um = mContext.getSystemService(UserManager.class);
9661 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jean9d968182021-02-25 21:46:34 +09009662 throw new IllegalArgumentException("Profile must be a managed profile");
9663 }
9664 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9665 // handler thread. However it is an immutable object, so reading the reference is
9666 // safe - it's just possible the value is slightly outdated. For the final check,
9667 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9668 // lot easier to understand, so opportunistically check it.
9669 if (!mOemNetworkPreferences.isEmpty()) {
9670 throwConcurrentPreferenceException();
9671 }
9672 final NetworkCapabilities nc;
9673 switch (preference) {
9674 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9675 nc = null;
9676 break;
9677 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9678 final UidRange uids = UidRange.createForUser(profile);
9679 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9680 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9681 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9682 break;
9683 default:
9684 throw new IllegalArgumentException(
9685 "Invalid preference in setProfileNetworkPreference");
9686 }
9687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9688 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9689 }
9690
9691 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9692 @Nullable final NetworkCapabilities nc) {
9693 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9694 ensureRequestableCapabilities(nc);
9695 }
9696
9697 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9698 @NonNull final ProfileNetworkPreferences prefs) {
9699 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9700 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9701 // The NRI for a user should be comprised of two layers:
9702 // - The request for the capabilities
9703 // - The request for the default network, for fallback. Create an image of it to
9704 // have the correct UIDs in it (also a request can only be part of one NRI, because
9705 // of lookups in 1:1 associations like mNetworkRequests).
9706 // Note that denying a fallback can be implemented simply by not adding the second
9707 // request.
9708 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9709 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
James Mattis6402e582021-04-20 17:26:30 -07009710 nrs.add(createDefaultInternetRequestForTransport(
9711 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Chiachang Wangd5034c72021-02-22 18:36:38 +08009712 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
Lorenzo Colittif2514122021-03-12 22:50:57 +09009713 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
Chalard Jean9d968182021-02-25 21:46:34 +09009714 result.add(nri);
9715 }
9716 return result;
9717 }
9718
9719 private void handleSetProfileNetworkPreference(
9720 @NonNull final ProfileNetworkPreferences.Preference preference,
9721 @Nullable final IOnCompleteListener listener) {
9722 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9723 // particular because it's not clear what preference should win in case both apply
9724 // to the same app.
9725 // The binder call has already checked this, but as mOemNetworkPreferences is only
9726 // touched on the handler thread, it's theoretically not impossible that it has changed
9727 // since.
9728 if (!mOemNetworkPreferences.isEmpty()) {
Chalard Jean6bb468c2021-03-09 21:09:20 +09009729 // This may happen on a device with an OEM preference set when a user is removed.
9730 // In this case, it's safe to ignore. In particular this happens in the tests.
9731 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
Chalard Jean9d968182021-02-25 21:46:34 +09009732 return;
9733 }
9734
9735 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9736
9737 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
James Mattisfff0b7c2021-03-28 17:41:09 -07009738 mSystemNetworkRequestCounter.transact(
9739 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9740 () -> {
9741 final ArraySet<NetworkRequestInfo> nris =
9742 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9743 replaceDefaultNetworkRequestsForPreference(nris);
9744 });
Chalard Jean9d968182021-02-25 21:46:34 +09009745 // Finally, rematch.
9746 rematchAllNetworksAndRequests();
9747
9748 if (null != listener) {
9749 try {
9750 listener.onComplete();
9751 } catch (RemoteException e) {
9752 loge("Listener for setProfileNetworkPreference has died");
9753 }
9754 }
9755 }
9756
James Mattis6e6fabf2021-01-10 14:24:24 -08009757 private void enforceAutomotiveDevice() {
9758 final boolean isAutomotiveDevice =
9759 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9760 if (!isAutomotiveDevice) {
9761 throw new UnsupportedOperationException(
9762 "setOemNetworkPreference() is only available on automotive devices.");
9763 }
9764 }
9765
9766 /**
9767 * Used by automotive devices to set the network preferences used to direct traffic at an
9768 * application level as per the given OemNetworkPreferences. An example use-case would be an
9769 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9770 * vehicle via a particular network.
9771 *
9772 * Calling this will overwrite the existing preference.
9773 *
James Mattis7a253542021-01-26 16:23:52 -08009774 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jeancc9ad152021-03-03 16:37:13 +09009775 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis6e6fabf2021-01-10 14:24:24 -08009776 * to communicate completion of setOemNetworkPreference();
James Mattis6e6fabf2021-01-10 14:24:24 -08009777 */
James Mattised87a672021-01-01 14:13:35 -08009778 @Override
James Mattis6e6fabf2021-01-10 14:24:24 -08009779 public void setOemNetworkPreference(
9780 @NonNull final OemNetworkPreferences preference,
Chalard Jeancc9ad152021-03-03 16:37:13 +09009781 @Nullable final IOnCompleteListener listener) {
James Mattis981865c2021-01-26 14:05:36 -08009782
James Mattis6e6fabf2021-01-10 14:24:24 -08009783 enforceAutomotiveDevice();
James Mattis7a253542021-01-26 16:23:52 -08009784 enforceOemNetworkPreferencesPermission();
James Mattis6e6fabf2021-01-10 14:24:24 -08009785
Chalard Jean9d968182021-02-25 21:46:34 +09009786 if (!mProfileNetworkPreferences.isEmpty()) {
9787 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9788 // handler thread. However it is an immutable object, so reading the reference is
9789 // safe - it's just possible the value is slightly outdated. For the final check,
9790 // see #handleSetOemPreference. But if this can be caught here it is a
9791 // lot easier to understand, so opportunistically check it.
9792 throwConcurrentPreferenceException();
9793 }
9794
James Mattis6e6fabf2021-01-10 14:24:24 -08009795 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9796 validateOemNetworkPreferences(preference);
9797 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9798 new Pair<>(preference, listener)));
9799 }
9800
9801 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9802 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9803 : preference.getNetworkPreferences().values()) {
9804 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9805 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9806 throw new IllegalArgumentException(msg);
9807 }
9808 }
9809 }
9810
9811 private void handleSetOemNetworkPreference(
9812 @NonNull final OemNetworkPreferences preference,
Chalard Jeancc9ad152021-03-03 16:37:13 +09009813 @Nullable final IOnCompleteListener listener) {
James Mattis6e6fabf2021-01-10 14:24:24 -08009814 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9815 if (DBG) {
9816 log("set OEM network preferences :" + preference.toString());
9817 }
Chalard Jean9d968182021-02-25 21:46:34 +09009818 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9819 // particular because it's not clear what preference should win in case both apply
9820 // to the same app.
9821 // The binder call has already checked this, but as mOemNetworkPreferences is only
9822 // touched on the handler thread, it's theoretically not impossible that it has changed
9823 // since.
9824 if (!mProfileNetworkPreferences.isEmpty()) {
9825 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9826 return;
9827 }
9828
James Mattis6e4405f2021-04-06 17:07:42 -07009829 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
James Mattisfff0b7c2021-03-28 17:41:09 -07009830 final int uniquePreferenceCount = new ArraySet<>(
9831 preference.getNetworkPreferences().values()).size();
9832 mSystemNetworkRequestCounter.transact(
9833 mDeps.getCallingUid(), uniquePreferenceCount,
9834 () -> {
9835 final ArraySet<NetworkRequestInfo> nris =
9836 new OemNetworkRequestFactory()
9837 .createNrisFromOemNetworkPreferences(preference);
9838 replaceDefaultNetworkRequestsForPreference(nris);
9839 });
James Mattis6e6fabf2021-01-10 14:24:24 -08009840 mOemNetworkPreferences = preference;
James Mattis6e6fabf2021-01-10 14:24:24 -08009841
9842 if (null != listener) {
Chalard Jeandc974072021-03-01 22:00:20 +09009843 try {
9844 listener.onComplete();
9845 } catch (RemoteException e) {
James Mattis3bf8b7a2021-03-01 17:09:11 -08009846 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jeandc974072021-03-01 22:00:20 +09009847 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009848 }
9849 }
9850
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009851 private void replaceDefaultNetworkRequestsForPreference(
James Mattise494cbb2021-02-09 18:18:28 -08009852 @NonNull final Set<NetworkRequestInfo> nris) {
James Mattis15c1b212021-02-20 14:40:51 -08009853 // Pass in a defensive copy as this collection will be updated on remove.
9854 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
James Mattise494cbb2021-02-09 18:18:28 -08009855 addPerAppDefaultNetworkRequests(nris);
James Mattis6e6fabf2021-01-10 14:24:24 -08009856 }
9857
James Mattise494cbb2021-02-09 18:18:28 -08009858 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9859 ensureRunningOnConnectivityServiceThread();
9860 mDefaultNetworkRequests.addAll(nris);
9861 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9862 getPerAppCallbackRequestsToUpdate();
James Mattise494cbb2021-02-09 18:18:28 -08009863 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
James Mattisfff0b7c2021-03-28 17:41:09 -07009864 mSystemNetworkRequestCounter.transact(
9865 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9866 () -> {
9867 nrisToRegister.addAll(
9868 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9869 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9870 handleRegisterNetworkRequests(nrisToRegister);
9871 });
James Mattise494cbb2021-02-09 18:18:28 -08009872 }
9873
9874 /**
9875 * All current requests that are tracking the default network need to be assessed as to whether
9876 * or not the current set of per-application default requests will be changing their default
9877 * network. If so, those requests will need to be updated so that they will send callbacks for
9878 * default network changes at the appropriate time. Additionally, those requests tracking the
9879 * default that were previously updated by this flow will need to be reassessed.
9880 * @return the nris which will need to be updated.
9881 */
9882 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9883 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9884 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9885 // same nri in the map's values for each of its NetworkRequest objects.
9886 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis6e6fabf2021-01-10 14:24:24 -08009887 for (final NetworkRequestInfo nri : nris) {
James Mattise494cbb2021-02-09 18:18:28 -08009888 // Include this nri if it is currently being tracked.
9889 if (isPerAppTrackedNri(nri)) {
9890 defaultCallbackRequests.add(nri);
9891 continue;
9892 }
9893 // We only track callbacks for requests tracking the default.
9894 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9895 continue;
9896 }
9897 // Include this nri if it will be tracked by the new per-app default requests.
9898 final boolean isNriGoingToBeTracked =
Lorenzo Colittif2514122021-03-12 22:50:57 +09009899 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattise494cbb2021-02-09 18:18:28 -08009900 if (isNriGoingToBeTracked) {
9901 defaultCallbackRequests.add(nri);
James Mattis6e6fabf2021-01-10 14:24:24 -08009902 }
9903 }
James Mattise494cbb2021-02-09 18:18:28 -08009904 return defaultCallbackRequests;
James Mattis6e6fabf2021-01-10 14:24:24 -08009905 }
9906
James Mattise494cbb2021-02-09 18:18:28 -08009907 /**
9908 * Create nris for those network requests that are currently tracking the default network that
9909 * are being controlled by a per-application default.
9910 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
9911 * foundation when creating the nri. Important items include the calling uid's original
9912 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
9913 * requests are assumed to have already been validated as needing to be updated.
9914 * @return the Set of nris to use when registering network requests.
9915 */
9916 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
9917 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
9918 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
9919 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
9920 final NetworkRequestInfo trackingNri =
Lorenzo Colittif2514122021-03-12 22:50:57 +09009921 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattise494cbb2021-02-09 18:18:28 -08009922
9923 // If this nri is not being tracked, the change it back to an untracked nri.
9924 if (trackingNri == mDefaultRequest) {
9925 callbackRequestsToRegister.add(new NetworkRequestInfo(
9926 callbackRequest,
9927 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
9928 continue;
9929 }
9930
Lorenzo Colittif2514122021-03-12 22:50:57 +09009931 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattise494cbb2021-02-09 18:18:28 -08009932 callbackRequestsToRegister.add(new NetworkRequestInfo(
9933 callbackRequest,
9934 copyNetworkRequestsForUid(
Lorenzo Colittif2514122021-03-12 22:50:57 +09009935 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colittib199b962021-03-12 22:48:07 +09009936 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattise494cbb2021-02-09 18:18:28 -08009937 }
9938 return callbackRequestsToRegister;
James Mattis6e6fabf2021-01-10 14:24:24 -08009939 }
9940
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009941 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
9942 @NonNull final Set<UidRange> uids) {
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009943 for (final NetworkRequest req : requests) {
Chiachang Wangd5034c72021-02-22 18:36:38 +08009944 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean9a3a0ea2021-03-01 14:06:28 +09009945 }
9946 }
9947
James Mattis6e6fabf2021-01-10 14:24:24 -08009948 /**
9949 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
9950 */
9951 @VisibleForTesting
9952 final class OemNetworkRequestFactory {
James Mattise494cbb2021-02-09 18:18:28 -08009953 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis6e6fabf2021-01-10 14:24:24 -08009954 @NonNull final OemNetworkPreferences preference) {
James Mattise494cbb2021-02-09 18:18:28 -08009955 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis6e6fabf2021-01-10 14:24:24 -08009956 final SparseArray<Set<Integer>> uids =
9957 createUidsFromOemNetworkPreferences(preference);
9958 for (int i = 0; i < uids.size(); i++) {
9959 final int key = uids.keyAt(i);
9960 final Set<Integer> value = uids.valueAt(i);
9961 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
9962 // No need to add an nri without any requests.
9963 if (0 == nri.mRequests.size()) {
9964 continue;
9965 }
9966 nris.add(nri);
9967 }
9968
9969 return nris;
9970 }
9971
9972 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
9973 @NonNull final OemNetworkPreferences preference) {
9974 final SparseArray<Set<Integer>> uids = new SparseArray<>();
9975 final PackageManager pm = mContext.getPackageManager();
James Mattis3bf8b7a2021-03-01 17:09:11 -08009976 final List<UserHandle> users =
9977 mContext.getSystemService(UserManager.class).getUserHandles(true);
9978 if (null == users || users.size() == 0) {
9979 if (VDBG || DDBG) {
9980 log("No users currently available for setting the OEM network preference.");
9981 }
9982 return uids;
9983 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009984 for (final Map.Entry<String, Integer> entry :
9985 preference.getNetworkPreferences().entrySet()) {
9986 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
9987 try {
9988 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
9989 if (!uids.contains(pref)) {
9990 uids.put(pref, new ArraySet<>());
9991 }
James Mattis3bf8b7a2021-03-01 17:09:11 -08009992 for (final UserHandle ui : users) {
9993 // Add the rules for all users as this policy is device wide.
Chiachang Wang97565cf2021-04-08 11:10:51 +08009994 uids.get(pref).add(ui.getUid(uid));
James Mattis3bf8b7a2021-03-01 17:09:11 -08009995 }
James Mattis6e6fabf2021-01-10 14:24:24 -08009996 } catch (PackageManager.NameNotFoundException e) {
9997 // Although this may seem like an error scenario, it is ok that uninstalled
9998 // packages are sent on a network preference as the system will watch for
9999 // package installations associated with this network preference and update
10000 // accordingly. This is done so as to minimize race conditions on app install.
James Mattis6e6fabf2021-01-10 14:24:24 -080010001 continue;
10002 }
10003 }
10004 return uids;
10005 }
10006
10007 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10008 @OemNetworkPreferences.OemNetworkPreference final int preference,
10009 @NonNull final Set<Integer> uids) {
10010 final List<NetworkRequest> requests = new ArrayList<>();
10011 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10012 switch (preference) {
10013 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10014 requests.add(createUnmeteredNetworkRequest());
10015 requests.add(createOemPaidNetworkRequest());
James Mattis6402e582021-04-20 17:26:30 -070010016 requests.add(createDefaultInternetRequestForTransport(
10017 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis6e6fabf2021-01-10 14:24:24 -080010018 break;
10019 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10020 requests.add(createUnmeteredNetworkRequest());
10021 requests.add(createOemPaidNetworkRequest());
10022 break;
10023 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10024 requests.add(createOemPaidNetworkRequest());
10025 break;
10026 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10027 requests.add(createOemPrivateNetworkRequest());
10028 break;
10029 default:
10030 // This should never happen.
10031 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10032 + " called with invalid preference of " + preference);
10033 }
10034
Chalard Jean9a3a0ea2021-03-01 14:06:28 +090010035 final ArraySet ranges = new ArraySet<Integer>();
10036 for (final int uid : uids) {
10037 ranges.add(new UidRange(uid, uid));
10038 }
10039 setNetworkRequestUids(requests, ranges);
Lorenzo Colittif2514122021-03-12 22:50:57 +090010040 return new NetworkRequestInfo(Process.myUid(), requests);
James Mattis6e6fabf2021-01-10 14:24:24 -080010041 }
10042
10043 private NetworkRequest createUnmeteredNetworkRequest() {
10044 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10045 .addCapability(NET_CAPABILITY_NOT_METERED)
10046 .addCapability(NET_CAPABILITY_VALIDATED);
10047 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10048 }
10049
10050 private NetworkRequest createOemPaidNetworkRequest() {
10051 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10052 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10053 .addCapability(NET_CAPABILITY_OEM_PAID)
10054 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10055 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10056 }
10057
10058 private NetworkRequest createOemPrivateNetworkRequest() {
10059 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10060 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10061 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10062 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10063 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10064 }
10065
10066 private NetworkCapabilities createDefaultPerAppNetCap() {
10067 final NetworkCapabilities netCap = new NetworkCapabilities();
10068 netCap.addCapability(NET_CAPABILITY_INTERNET);
10069 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10070 return netCap;
10071 }
James Mattised87a672021-01-01 14:13:35 -080010072 }
Nathan Harold6179b142018-07-30 13:38:01 -070010073}