blob: aa1648f9e7ec2affeb26d5dc2ca1dea1ff5b7e2e [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;
Haoyu Baib5da5752012-06-20 14:29:57 -070018import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090019import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
20import static android.content.pm.PackageManager.FEATURE_WATCH;
21import static android.content.pm.PackageManager.FEATURE_WIFI;
22import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090023import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090024import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
25import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
27import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090032import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
33import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000034import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070035import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090036import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090037import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090038import static android.net.ConnectivityManager.TYPE_MOBILE;
39import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
40import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
41import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
42import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
43import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
44import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
46import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070048import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090049import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070050import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090051import static android.net.ConnectivityManager.TYPE_WIFI;
52import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070053import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070054import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080055import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080056import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080057import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
58import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040059import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090060import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090061import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090062import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090063import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090064import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
65import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060066import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080070import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
71import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080072import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Roshan Pius98f59ec2021-02-23 08:47:39 -080074import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
75import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
76import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090077import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090078import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060079import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai1b1c8742021-03-12 20:05:08 +080080import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +090081import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070082import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080083import static android.os.Process.VPN_UID;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070084import static android.system.OsConstants.IPPROTO_TCP;
85import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060086
Cody Kesting83bb5fa2020-01-05 14:06:39 -080087import static java.util.Map.Entry;
88
Chalard Jean5b639762020-03-09 21:25:37 +090089import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +000090import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -080091import android.annotation.Nullable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080092import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -080093import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -070094import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +080095import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070096import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +080097import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -080098import android.content.ContentResolver;
99import android.content.Context;
100import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700101import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800102import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700103import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900104import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900105import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700106import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800107import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800108import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800109import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900110import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800111import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900112import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900113import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800114import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900115import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800116import android.net.DnsResolverServiceManager;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900117import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800118import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800120import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800121import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800122import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900123import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900124import android.net.INetworkMonitor;
125import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900126import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900127import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700128import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800129import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900130import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900131import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900132import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800133import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100134import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800135import android.net.NativeNetworkConfig;
136import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800137import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700138import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700139import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900140import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700141import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800142import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700143import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900144import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900145import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000146import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900147import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700148import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900149import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700150import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900151import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700152import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800153import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900154import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700155import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000156import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800157import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900158import android.net.PrivateDnsConfigParcel;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400159import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700160import android.net.QosCallbackException;
161import android.net.QosFilter;
162import android.net.QosSocketFilter;
163import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700164import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800165import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800166import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800167import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900168import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400169import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800170import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800171import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400172import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800173import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900174import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900175import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900176import android.net.metrics.NetworkEvent;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700177import android.net.netlink.InetDiagMessage;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900178import android.net.networkstack.ModuleNetworkStackClient;
179import android.net.networkstack.NetworkStackClientBase;
paulhu7c0a2e62021-01-08 00:51:49 +0800180import android.net.resolv.aidl.DnsHealthEventParcel;
181import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
182import android.net.resolv.aidl.Nat64PrefixEventParcel;
183import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900184import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900185import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800186import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800187import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800188import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700189import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800190import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700191import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700192import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800193import android.os.Looper;
194import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700195import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700196import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900197import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800198import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700199import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700200import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800201import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700202import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900203import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900204import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700205import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700206import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400207import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800208import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900209import android.sysprop.NetworkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -0700210import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700211import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800212import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900213import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000214import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600215import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900216import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700217import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700218import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900220import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400221import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400222import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700223import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900224import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800225import com.android.modules.utils.BasicShellCommandHandler;
lucaslin66f44212021-02-23 01:12:55 +0800226import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900227import com.android.net.module.util.CollectionUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900228import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
229import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900230import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800231import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800232import com.android.net.module.util.PermissionUtils;
Chalard Jean7284daa2019-05-30 14:58:29 +0900233import com.android.server.connectivity.AutodestructReference;
Erik Kline32120082017-12-13 19:40:49 +0900234import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500235import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900236import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900237import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100238import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700239import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700240import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600241import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900242import com.android.server.connectivity.NetworkNotificationManager;
243import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900244import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900245import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700246import com.android.server.connectivity.PermissionMonitor;
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900247import com.android.server.connectivity.ProfileNetworkPreferences;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900248import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700249import com.android.server.connectivity.QosCallbackTracker;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600250
Josh Gao461a1222020-06-16 15:58:11 -0700251import libcore.io.IoUtils;
252
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253import java.io.FileDescriptor;
254import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700255import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700256import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900257import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700258import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700259import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700260import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700261import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800262import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900263import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800264import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700265import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700266import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700267import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700268import java.util.Map;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700269import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900270import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600271import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900272import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600273import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900274import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800275
276/**
277 * @hide
278 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800279public class ConnectivityService extends IConnectivityManager.Stub
280 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900281 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800282
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900283 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900284 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900285 private static final String NETWORK_ARG = "networks";
286 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900287
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900288 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900289 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
290 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800291
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900292 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700293
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100294 /**
295 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
296 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800297 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100298 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
299 * (preferably via runtime resource overlays).
300 */
301 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
302 "http://connectivitycheck.gstatic.com/generate_204";
303
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700304 // TODO: create better separation between radio types and network types
305
Robert Greenwalt2034b912009-08-12 16:08:25 -0700306 // how long to wait before switching back to a radio's default network
307 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
308 // system property that can override the above value
309 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
310 "android.telephony.apn-restore";
311
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900312 // How long to wait before putting up a "This network doesn't have an Internet connection,
313 // connect anyway?" dialog after the user selects a network that doesn't validate.
314 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
315
junyulai0ac374f2020-12-14 18:41:52 +0800316 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900317 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
318 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800319 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700320
321 // The maximum number of network request allowed per uid before an exception is thrown.
322 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
323
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900324 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700325 @VisibleForTesting
326 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900327
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900328 @VisibleForTesting
329 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800330 @VisibleForTesting
331 protected int mNascentDelayMs;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900332
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800333 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800334 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800335 private final int mReleasePendingIntentDelayMs;
336
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900337 private MockableSystemProperties mSystemProperties;
338
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000339 @VisibleForTesting
340 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700341
Daniel Brightf9e945b2020-06-15 16:10:01 -0700342 private final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700343 @VisibleForTesting
344 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700345
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900346 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700347
junyulaif2c67e42018-08-07 19:50:45 +0800348 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000349 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
350 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800351 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000352 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800353
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900354 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900355 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000356 // The Context is created for UserHandle.ALL.
357 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900358 private final Dependencies mDeps;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700359 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700360 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800361
Chenbo Feng15416292018-11-08 17:36:21 -0800362 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800363 protected IDnsResolver mDnsResolver;
364 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800365 protected INetd mNetd;
junyulaie7c7d2a2021-01-26 15:29:15 +0800366 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800367 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800368 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700369
Benedict Wong493e04b2018-11-09 14:45:34 -0800370 /**
371 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
372 * instances.
373 */
374 @GuardedBy("mTNSLock")
375 private TestNetworkService mTNS;
376
377 private final Object mTNSLock = new Object();
378
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700379 private String mCurrentTcpBufferSizes;
380
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900381 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800382 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900383
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500384 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400385 // Tear down networks that have no chance (e.g. even if validated) of becoming
386 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500387 // all networks have been rematched against all NetworkRequests.
388 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400389 // Don't reap networks. This should be passed when some networks have not yet been
390 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500391 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900392 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500393
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900394 private enum UnneededFor {
395 LINGER, // Determine whether this network is unneeded and should be lingered.
396 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
397 }
398
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700399 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700400 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700401 * from one net to another. Clear happens when we get a new
402 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
403 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700404 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700405 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700406
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700407 /**
408 * used internally to reload global proxy settings
409 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700410 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700411
Robert Greenwalt34848c02011-03-25 13:09:25 -0700412 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400413 * PAC manager has received new port.
414 */
415 private static final int EVENT_PROXY_HAS_CHANGED = 16;
416
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700417 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900418 * used internally when registering NetworkProviders
419 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700420 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900421 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700422
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700423 /**
424 * used internally when registering NetworkAgents
425 * obj = Messenger
426 */
427 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
428
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700429 /**
430 * used to add a network request
431 * includes a NetworkRequestInfo
432 */
433 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
434
435 /**
436 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900437 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700438 * cancel it.
439 * includes a NetworkRequestInfo
440 */
441 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
442
443 /**
444 * used to add a network listener - no request
445 * includes a NetworkRequestInfo
446 */
447 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
448
449 /**
450 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400451 * arg1 = UID of caller
452 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700453 */
454 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
455
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700456 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900457 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700458 * obj = Messenger
459 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900460 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700461
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700462 /**
463 * used internally to expire a wakelock when transitioning
464 * from one net to another. Expire happens when we fail to find
465 * a new network (typically after 1 minute) -
466 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
467 * a replacement network.
468 */
469 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
470
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700471 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800472 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400473 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800474 */
475 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
476
477 /**
478 * used to remove a pending intent and its associated network request.
479 * arg1 = UID of caller
480 * obj = PendingIntent
481 */
482 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
483
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900484 /**
485 * used to specify whether a network should be used even if unvalidated.
486 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
487 * arg2 = whether to remember this choice in the future (1 or 0)
488 * obj = network
489 */
490 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
491
492 /**
493 * used to ask the user to confirm a connection to an unvalidated network.
494 * obj = network
495 */
496 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700497
Erik Kline05f2b402015-04-30 12:58:40 +0900498 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700499 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900500 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700501 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900502
Paul Jensenc8873fc2015-06-17 14:15:39 -0400503 /**
504 * used to add a network listener with a pending intent
505 * obj = NetworkRequestInfo
506 */
507 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
508
Hugo Benichid6b510a2017-04-06 17:22:18 +0900509 /**
510 * used to specify whether a network should not be penalized when it becomes unvalidated.
511 */
512 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
513
514 /**
515 * used to trigger revalidation of a network.
516 */
517 private static final int EVENT_REVALIDATE_NETWORK = 36;
518
Erik Kline31b4a9e2018-01-11 21:07:29 +0900519 // Handle changes in Private DNS settings.
520 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
521
dalyk1720e542018-03-05 12:42:22 -0500522 // Handle private DNS validation status updates.
523 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
524
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900525 /**
526 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
527 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800528 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
529 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
530 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900531 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900532 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900533
534 /**
535 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
536 * config was resolved.
537 * obj = PrivateDnsConfig
538 * arg2 = netid
539 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900540 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900541
542 /**
543 * Request ConnectivityService display provisioning notification.
544 * arg1 = Whether to make the notification visible.
545 * arg2 = NetID.
546 * obj = Intent to be launched when notification selected by user, null if !arg1.
547 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900548 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900549
550 /**
lucaslin2240ef62019-03-12 13:08:03 +0800551 * Used to specify whether a network should be used even if connectivity is partial.
552 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
553 * false)
554 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
555 * obj = network
556 */
lucaslin444d43a2020-02-20 16:56:59 +0800557 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800558
559 /**
lucasline117e2e2019-10-22 18:27:33 +0800560 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
561 * Both of the arguments are bitmasks, and the value of bits come from
562 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
563 * arg1 = A bitmask to describe which probes are completed.
564 * arg2 = A bitmask to describe which probes are successful.
565 */
lucaslin444d43a2020-02-20 16:56:59 +0800566 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800567
568 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900569 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
570 * arg1 = unused
571 * arg2 = netId
572 * obj = captive portal data
573 */
lucaslin444d43a2020-02-20 16:56:59 +0800574 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900575
576 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900577 * Used by setRequireVpnForUids.
578 * arg1 = whether the specified UID ranges are required to use a VPN.
579 * obj = Array of UidRange objects.
580 */
581 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
582
583 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900584 * Used internally when setting the default networks for OemNetworkPreferences.
585 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800586 */
587 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
588
589 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800590 * Used to indicate the system default network becomes active.
591 */
592 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
593
594 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900595 * Used internally when setting a network preference for a user profile.
596 * obj = Pair<ProfileNetworkPreference, Listener>
597 */
598 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
599
600 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000601 * Event to specify that reasons for why an uid is blocked changed.
602 * arg1 = uid
603 * arg2 = blockedReasons
604 */
605 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
606
607 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900608 * Event to register a new network offer
609 * obj = NetworkOffer
610 */
611 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
612
613 /**
614 * Event to unregister an existing network offer
615 * obj = INetworkOfferCallback
616 */
617 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
618
619 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900620 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
621 * should be shown.
622 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900623 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900624
625 /**
626 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
627 * should be hidden.
628 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900629 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900630
Hugo Benichi47011212017-03-30 10:46:05 +0900631 private static String eventName(int what) {
632 return sMagicDecoderRing.get(what, Integer.toString(what));
633 }
634
paulhua10d8212020-11-10 15:32:56 +0800635 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900636 final DnsResolverServiceManager dsm = context.getSystemService(
637 DnsResolverServiceManager.class);
638 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800639 }
640
Cody Kesting73708bf2019-12-18 10:57:50 -0800641 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900642 @VisibleForTesting
643 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700644 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700645 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700646 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700647 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800648 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
649 @VisibleForTesting
650 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
651
Erik Kline32120082017-12-13 19:40:49 +0900652 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900653 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700654
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400655 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800656 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400657
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700658 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800659 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700660
Chalard Jean5d70ba42018-06-07 16:44:04 +0900661 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
662 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000663 @VisibleForTesting
664 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400665
Erik Kline05f2b402015-04-30 12:58:40 +0900666 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700667
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400668 private UserManager mUserManager;
669
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700670 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900671 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700672
Valentin Iftime9fa35092019-09-24 13:32:13 +0200673 private Set<String> mWolSupportedInterfaces;
674
Roshan Pius08c94fb2020-01-16 12:17:17 -0800675 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800676 private final AppOpsManager mAppOpsManager;
677
678 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400679
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900680 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700681 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900682 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900683 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900684
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700685 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800686 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700687
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900688 // Sequence number for NetworkProvider IDs.
689 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
690 NetworkProvider.FIRST_PROVIDER_ID);
691
Erik Klineedf878b2015-07-09 18:24:03 +0900692 // NetworkRequest activity String log entries.
693 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
694 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
695
Hugo Benichid159fdd2016-07-11 11:05:12 +0900696 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900697 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900698 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
699
Hugo Benichi47011212017-03-30 10:46:05 +0900700 private static final int MAX_WAKELOCK_LOGS = 20;
701 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900702 private int mTotalWakelockAcquisitions = 0;
703 private int mTotalWakelockReleases = 0;
704 private long mTotalWakelockDurationMs = 0;
705 private long mMaxWakelockDurationMs = 0;
706 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900707
Hugo Benichi208c0102016-07-28 17:53:06 +0900708 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900709
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700710 @GuardedBy("mBandwidthRequests")
711 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
712
Erik Kline95ecfee2016-10-02 18:02:14 +0900713 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900714 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900715
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900716 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800717 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
718 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800719
Robert Greenwalt802c1102014-06-02 15:32:02 -0700720 /**
721 * Implements support for the legacy "one network per network type" model.
722 *
723 * We used to have a static array of NetworkStateTrackers, one for each
724 * network type, but that doesn't work any more now that we can have,
725 * for example, more that one wifi network. This class stores all the
726 * NetworkAgentInfo objects that support a given type, but the legacy
727 * API will only see the first one.
728 *
729 * It serves two main purposes:
730 *
731 * 1. Provide information about "the network for a given type" (since this
732 * API only supports one).
733 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
734 * the first network for a given type changes, or if the default network
735 * changes.
736 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900737 @VisibleForTesting
738 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900739
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900740 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900741 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900742
Robert Greenwalt802c1102014-06-02 15:32:02 -0700743 /**
744 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
745 * Each list holds references to all NetworkAgentInfos that are used to
746 * satisfy requests for that network type.
747 *
748 * This array is built out at startup such that an unsupported network
749 * doesn't get an ArrayList instance, making this a tristate:
750 * unsupported, supported but not active and active.
751 *
752 * The actual lists are populated when we scan the network types that
753 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900754 *
755 * Threading model:
756 * - addSupportedType() is only called in the constructor
757 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
758 * They are therefore not thread-safe with respect to each other.
759 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
760 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900761 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900762 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700763 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900764 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900765 @NonNull
766 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700767
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900768 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
769 // an entry have no timer (equivalent to -1). Lazily loaded.
770 @NonNull
771 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
772
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900773 LegacyTypeTracker(@NonNull ConnectivityService service) {
774 mService = service;
775 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700776 }
777
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900778 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
779 final PackageManager pm = ctx.getPackageManager();
780 if (pm.hasSystemFeature(FEATURE_WIFI)) {
781 addSupportedType(TYPE_WIFI);
782 }
783 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
784 addSupportedType(TYPE_WIFI_P2P);
785 }
786 if (tm.isDataCapable()) {
787 // Telephony does not have granular support for these types: they are either all
788 // supported, or none is supported
789 addSupportedType(TYPE_MOBILE);
790 addSupportedType(TYPE_MOBILE_MMS);
791 addSupportedType(TYPE_MOBILE_SUPL);
792 addSupportedType(TYPE_MOBILE_DUN);
793 addSupportedType(TYPE_MOBILE_HIPRI);
794 addSupportedType(TYPE_MOBILE_FOTA);
795 addSupportedType(TYPE_MOBILE_IMS);
796 addSupportedType(TYPE_MOBILE_CBS);
797 addSupportedType(TYPE_MOBILE_IA);
798 addSupportedType(TYPE_MOBILE_EMERGENCY);
799 }
800 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
801 addSupportedType(TYPE_BLUETOOTH);
802 }
803 if (pm.hasSystemFeature(FEATURE_WATCH)) {
804 // TYPE_PROXY is only used on Wear
805 addSupportedType(TYPE_PROXY);
806 }
807 // Ethernet is often not specified in the configs, although many devices can use it via
808 // USB host adapters. Add it as long as the ethernet service is here.
809 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
810 addSupportedType(TYPE_ETHERNET);
811 }
812
813 // Always add TYPE_VPN as a supported type
814 addSupportedType(TYPE_VPN);
815 }
816
817 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700818 if (mTypeLists[type] != null) {
819 throw new IllegalStateException(
820 "legacy list for type " + type + "already initialized");
821 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900822 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700823 }
824
Robert Greenwalt802c1102014-06-02 15:32:02 -0700825 public boolean isTypeSupported(int type) {
826 return isNetworkTypeValid(type) && mTypeLists[type] != null;
827 }
828
829 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900830 synchronized (mTypeLists) {
831 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
832 return mTypeLists[type].get(0);
833 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700834 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900835 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700836 }
837
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900838 public int getRestoreTimerForType(int type) {
839 synchronized (mTypeLists) {
840 if (mRestoreTimers == null) {
841 mRestoreTimers = loadRestoreTimers();
842 }
843 return mRestoreTimers.getOrDefault(type, -1);
844 }
845 }
846
847 private ArrayMap<Integer, Integer> loadRestoreTimers() {
848 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900849 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900850 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
851 for (final String config : configs) {
852 final String[] splits = TextUtils.split(config, ",");
853 if (splits.length != 2) {
854 logwtf("Invalid restore timer token count: " + config);
855 continue;
856 }
857 try {
858 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
859 } catch (NumberFormatException e) {
860 logwtf("Invalid restore timer number format: " + config, e);
861 }
862 }
863 return ret;
864 }
865
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700866 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900867 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900868 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900869 log("Sending " + state
870 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900871 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900872 }
873 }
874
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900875 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
876 // network type, to preserve previous behaviour.
877 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
878 if (vpnNai != mService.getLegacyLockdownNai()) return;
879
880 if (vpnNai.declaredUnderlyingNetworks == null
881 || vpnNai.declaredUnderlyingNetworks.length != 1) {
882 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
883 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
884 return;
885 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900886 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900887 vpnNai.declaredUnderlyingNetworks[0]);
888 if (underlyingNai == null) return;
889
890 final int type = underlyingNai.networkInfo.getType();
891 final DetailedState state = DetailedState.CONNECTED;
892 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
893 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
894 }
895
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900896 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700897 public void add(int type, NetworkAgentInfo nai) {
898 if (!isTypeSupported(type)) {
899 return; // Invalid network type.
900 }
901 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
902
903 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
904 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700905 return;
906 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900907 synchronized (mTypeLists) {
908 list.add(nai);
909 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +0900910
Chalard Jean5b409c72021-02-04 13:12:59 +0900911 // Send a broadcast if this is the first network of its type or if it's the default.
912 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900913
914 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
915 // to preserve previous behaviour.
916 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +0900917 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900918 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
919 mService.sendLegacyNetworkBroadcast(nai, state, type);
920 }
921
922 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
923 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -0700924 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700925 }
926
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900927 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +0900928 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900929 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
930 if (list == null || list.isEmpty()) {
931 return;
932 }
Lorenzo Colitti49767722015-05-01 00:30:10 +0900933 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900934
Hugo Benichi389633f2016-06-21 09:48:07 +0900935 synchronized (mTypeLists) {
936 if (!list.remove(nai)) {
937 return;
938 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900939 }
940
Lorenzo Colitti49767722015-05-01 00:30:10 +0900941 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +0900942 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
943 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900944 }
945
946 if (!list.isEmpty() && wasFirstNetwork) {
947 if (DBG) log("Other network available for type " + type +
948 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +0900949 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +0900950 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900951 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +0900952 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900953 }
954 }
955
956 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +0900957 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
958 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -0700959 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +0900960 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -0700961 }
962 }
Robert Greenwalt94e22142014-07-30 16:31:24 -0700963
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700964 // send out another legacy broadcast - currently only used for suspend/unsuspend
965 // toggle
966 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +0900967 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700968 final DetailedState state = nai.networkInfo.getDetailedState();
969 for (int type = 0; type < mTypeLists.length; type++) {
970 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -0700971 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +0900972 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +0900973 if (isFirst || contains && isDefault) {
974 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900975 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700976 }
977 }
978 }
979
Robert Greenwalt94e22142014-07-30 16:31:24 -0700980 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900981 pw.println("mLegacyTypeTracker:");
982 pw.increaseIndent();
983 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -0700984 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900985 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -0700986 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900987 pw.println();
988 pw.println("Current state:");
989 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +0900990 synchronized (mTypeLists) {
991 for (int type = 0; type < mTypeLists.length; type++) {
992 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
993 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +0900994 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +0900995 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900996 }
997 }
998 pw.decreaseIndent();
999 pw.decreaseIndent();
1000 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001001 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001002 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001003 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001004
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001005 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001006 /**
1007 * Helper class which parses out priority arguments and dumps sections according to their
1008 * priority. If priority arguments are omitted, function calls the legacy dump command.
1009 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001010 private class LocalPriorityDump {
1011 private static final String PRIORITY_ARG = "--dump-priority";
1012 private static final String PRIORITY_ARG_HIGH = "HIGH";
1013 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1014
1015 LocalPriorityDump() {}
1016
1017 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1018 doDump(fd, pw, new String[] {DIAG_ARG});
1019 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001020 }
1021
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001022 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1023 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001024 }
1025
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001026 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1027 if (args == null) {
1028 dumpNormal(fd, pw, args);
1029 return;
1030 }
1031
1032 String priority = null;
1033 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1034 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1035 argIndex++;
1036 priority = args[argIndex];
1037 }
1038 }
1039
1040 if (PRIORITY_ARG_HIGH.equals(priority)) {
1041 dumpHigh(fd, pw);
1042 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1043 dumpNormal(fd, pw, args);
1044 } else {
1045 // ConnectivityService publishes binder service using publishBinderService() with
1046 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001047 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1048 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001049 // TODO: Integrate into signal dump.
1050 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001051 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001052 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001053 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001054
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001055 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001056 * Keeps track of the number of requests made under different uids.
1057 */
1058 public static class PerUidCounter {
1059 private final int mMaxCountPerUid;
1060
1061 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001062 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001063 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001064 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001065
1066 /**
1067 * Constructor
1068 *
1069 * @param maxCountPerUid the maximum count per uid allowed
1070 */
1071 public PerUidCounter(final int maxCountPerUid) {
1072 mMaxCountPerUid = maxCountPerUid;
1073 }
1074
1075 /**
1076 * Increments the request count of the given uid. Throws an exception if the number
1077 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1078 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1079 *
1080 * @throws ServiceSpecificException with
1081 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1082 * the uid exceed the allowed number.
1083 *
1084 * @param uid the uid that the request was made under
1085 */
1086 public void incrementCountOrThrow(final int uid) {
1087 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001088 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001089 }
1090 }
1091
James Mattis20a4a8b2021-03-28 17:41:09 -07001092 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1093 final int newRequestCount =
1094 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1095 if (newRequestCount >= mMaxCountPerUid) {
1096 throw new ServiceSpecificException(
1097 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1098 }
1099 mUidToNetworkRequestCount.put(uid, newRequestCount);
1100 }
1101
Daniel Brightf9e945b2020-06-15 16:10:01 -07001102 /**
1103 * Decrements the request count of the given uid.
1104 *
1105 * @param uid the uid that the request was made under
1106 */
1107 public void decrementCount(final int uid) {
1108 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001109 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001110 }
1111 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001112
1113 private void decrementCount(final int uid, final int numToDecrement) {
1114 final int newRequestCount =
1115 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1116 if (newRequestCount < 0) {
1117 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1118 } else if (newRequestCount == 0) {
1119 mUidToNetworkRequestCount.delete(uid);
1120 } else {
1121 mUidToNetworkRequestCount.put(uid, newRequestCount);
1122 }
1123 }
1124
1125 /**
1126 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1127 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1128 * are used to create the new nris upon set. Therefore the request count limit can be
1129 * artificially hit. This method is used as a workaround for this particular case so that
1130 * the request counts are accounted for correctly.
1131 * @param uid the uid to adjust counts for
1132 * @param numOfNewRequests the new request count to account for
1133 * @param r the runnable to execute
1134 */
1135 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1136 // This should only be used on the handler thread as per all current and foreseen
1137 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1138 // no ref to the outer ConnectivityService.
1139 synchronized (mUidToNetworkRequestCount) {
1140 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1141 decrementCount(uid, reqCountOverage);
1142 r.run();
1143 incrementCountOrThrow(uid, reqCountOverage);
1144 }
1145 }
1146
1147 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1148 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1149 + numOfNewRequests;
1150 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1151 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1152 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001153 }
1154
1155 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001156 * Dependencies of ConnectivityService, for injection in tests.
1157 */
1158 @VisibleForTesting
1159 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001160 public int getCallingUid() {
1161 return Binder.getCallingUid();
1162 }
1163
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001164 /**
1165 * Get system properties to use in ConnectivityService.
1166 */
1167 public MockableSystemProperties getSystemProperties() {
1168 return new MockableSystemProperties();
1169 }
1170
1171 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001172 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1173 */
1174 public ConnectivityResources getResources(@NonNull Context ctx) {
1175 return new ConnectivityResources(ctx);
1176 }
1177
1178 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001179 * Create a HandlerThread to use in ConnectivityService.
1180 */
1181 public HandlerThread makeHandlerThread() {
1182 return new HandlerThread("ConnectivityServiceThread");
1183 }
1184
1185 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001186 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001187 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001188 public NetworkStackClientBase getNetworkStack() {
1189 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001190 }
1191
1192 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001193 * @see ProxyTracker
1194 */
1195 public ProxyTracker makeProxyTracker(@NonNull Context context,
1196 @NonNull Handler connServiceHandler) {
1197 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1198 }
1199
1200 /**
1201 * @see NetIdManager
1202 */
1203 public NetIdManager makeNetIdManager() {
1204 return new NetIdManager();
1205 }
1206
1207 /**
1208 * @see NetworkUtils#queryUserAccess(int, int)
1209 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001210 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1211 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001212 }
1213
1214 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001215 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1216 * requires CAP_NET_ADMIN, which the unit tests do not have.
1217 */
1218 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1219 InetSocketAddress remote) {
1220 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1221 }
1222
1223 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001224 * @see MultinetworkPolicyTracker
1225 */
1226 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1227 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1228 return new MultinetworkPolicyTracker(c, h, r);
1229 }
1230
Aaron Huang330a4c02020-10-27 03:36:19 +08001231 /**
1232 * @see BatteryStatsManager
1233 */
1234 public void reportNetworkInterfaceForTransports(Context context, String iface,
1235 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001236 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001237 context.getSystemService(BatteryStatsManager.class);
1238 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1239 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001240
1241 public boolean getCellular464XlatEnabled() {
1242 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1243 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001244 }
1245
junyulaie7c7d2a2021-01-26 15:29:15 +08001246 public ConnectivityService(Context context) {
1247 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001248 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1249 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001250 }
1251
1252 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001253 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1254 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001255 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001256
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001257 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001258 mSystemProperties = mDeps.getSystemProperties();
1259 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001260 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001261 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001262 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001263 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001264
Hugo Benichi208c0102016-07-28 17:53:06 +09001265 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001266 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001267 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1268 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001269 Process.myUid(), defaultInternetRequest, null,
Roshan Pius951c0032020-12-22 15:10:42 -08001270 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001271 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001272 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1273 mDefaultNetworkRequests.add(mDefaultRequest);
1274 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001275
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001276 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001277 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001278
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001279 // The default WiFi request is a background request so that apps using WiFi are
1280 // migrated to a better network (typically ethernet) when one comes up, instead
1281 // of staying on WiFi forever.
1282 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1283 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1284
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001285 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1286 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1287 NetworkRequest.Type.BACKGROUND_REQUEST);
1288
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001289 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001290 mHandlerThread.start();
1291 mHandler = new InternalHandler(mHandlerThread.getLooper());
1292 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001293 mConnectivityDiagnosticsHandler =
1294 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001295
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001296 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001297 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001298
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001299 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
junyulai0ac374f2020-12-14 18:41:52 +08001300 // TODO: Consider making the timer customizable.
1301 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09001302
junyulaie7c7d2a2021-01-26 15:29:15 +08001303 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001304 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001305 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001306 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001307
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001308 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001309 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001310 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1311 mLocationPermissionChecker = new LocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001312
Sudheer Shanka9967d462021-03-18 19:09:25 +00001313 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001314 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1315 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001316 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001317
1318 final PowerManager powerManager = (PowerManager) context.getSystemService(
1319 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001320 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001321 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001322
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001323 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1324 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001325 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001326 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001327 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001328 mProtectedNetworks.add(p);
1329 } else {
1330 if (DBG) loge("Ignoring protectedNetwork " + p);
1331 }
1332 }
1333
soma, kawata29444ae2019-05-23 09:30:40 +09001334 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1335
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001336 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001337
James Mattis02220e22021-03-13 19:27:21 -08001338 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001339 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001340 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001341 final IntentFilter userIntentFilter = new IntentFilter();
1342 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1343 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1344 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1345 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001346
James Mattis02220e22021-03-13 19:27:21 -08001347 // Listen to package add/removes for netd
1348 final IntentFilter packageIntentFilter = new IntentFilter();
1349 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1350 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1351 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1352 packageIntentFilter.addDataScheme("package");
1353 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001354 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001355
lucaslind5c2d072021-02-20 18:59:47 +08001356 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001357
lucaslin66f44212021-02-23 01:12:55 +08001358 mNetdCallback = new NetdCallback();
1359 try {
1360 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1361 } catch (RemoteException | ServiceSpecificException e) {
1362 loge("Error registering event listener :" + e);
1363 }
1364
Erik Kline05f2b402015-04-30 12:58:40 +09001365 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1366 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001367
junyulai7e06ad42019-03-04 22:45:36 +08001368 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001369 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001370 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001371
1372 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001373 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001374 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1375 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001376 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001377 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1378 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001379
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001380 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Erik Kline95ecfee2016-10-02 18:02:14 +09001381 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001382 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001383
Chiachang Wangc1215d32020-10-20 15:38:58 +08001384 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001385 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001386
Chalard Jean28018572020-12-21 18:36:52 +09001387 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1388 // request that doesn't allow fallback to the default network. It should never be visible
1389 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1390 // arguments like the handler or the DnsResolver.
1391 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001392 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001393 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001394 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001395 new LinkProperties(), new NetworkCapabilities(),
1396 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
1397 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID, mQosCallbackTracker,
1398 mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001399 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001400
Chalard Jean46adcf32018-04-18 20:18:38 +09001401 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001402 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1403 }
1404
1405 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1406 @NonNull final UidRange uids) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001407 final NetworkCapabilities netCap = new NetworkCapabilities();
1408 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001409 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001410 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Chiachang Wang8156c4e2021-03-19 00:45:39 +00001411 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
Chalard Jean46adcf32018-04-18 20:18:38 +09001412 return netCap;
1413 }
1414
James Mattis45d81842021-01-10 14:24:24 -08001415 private NetworkRequest createDefaultRequest() {
1416 return createDefaultInternetRequestForTransport(
1417 TYPE_NONE, NetworkRequest.Type.REQUEST);
1418 }
1419
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001420 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001421 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001422 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001423 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001424 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001425 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001426 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001427 netCap.addTransportType(transportType);
1428 }
James Mattis45d81842021-01-10 14:24:24 -08001429 return createNetworkRequest(type, netCap);
1430 }
1431
1432 private NetworkRequest createNetworkRequest(
1433 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001434 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001435 }
1436
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001437 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1438 NetworkRequest.Type type) {
1439 final NetworkCapabilities netCap = new NetworkCapabilities();
1440 netCap.clearAll();
1441 netCap.addCapability(capability);
1442 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1443 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1444 }
1445
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001446 // Used only for testing.
1447 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001448 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001449 // changing ContentResolver to make registerContentObserver non-final).
1450 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1451 // by subclassing SettingsObserver.
1452 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001453 void updateAlwaysOnNetworks() {
1454 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001455 }
1456
Erik Kline9a62f012018-03-21 07:18:33 -07001457 // See FakeSettingsProvider comment above.
1458 @VisibleForTesting
1459 void updatePrivateDnsSettings() {
1460 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1461 }
1462
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001463 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001464 final boolean enable = mContext.getResources().getBoolean(id);
1465 handleAlwaysOnNetworkRequest(networkRequest, enable);
1466 }
1467
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001468 private void handleAlwaysOnNetworkRequest(
1469 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001470 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001471 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001472 handleAlwaysOnNetworkRequest(networkRequest, enable);
1473 }
1474
1475 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001476 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001477 if (enable == isEnabled) {
1478 return; // Nothing to do.
1479 }
1480
1481 if (enable) {
1482 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001483 Process.myUid(), networkRequest, null, new Binder(),
Roshan Pius951c0032020-12-22 15:10:42 -08001484 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001485 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001486 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001487 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1488 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001489 }
1490 }
1491
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001492 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001493 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1494 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1495 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1496 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001497 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1498 R.bool.config_vehicleInternalNetworkAlwaysRequested);
1499 // TODO (b/183076074): remove legacy fallback after migrating overlays
1500 final boolean legacyAlwaysRequested = mContext.getResources().getBoolean(
1501 mContext.getResources().getIdentifier(
1502 "config_vehicleInternalNetworkAlwaysRequested", "bool", "android"));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001503 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001504 vehicleAlwaysRequested || legacyAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001505 }
1506
Erik Kline05f2b402015-04-30 12:58:40 +09001507 private void registerSettingsCallbacks() {
1508 // Watch for global HTTP proxy changes.
1509 mSettingsObserver.observe(
1510 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1511 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1512
1513 // Watch for whether or not to keep mobile data always on.
1514 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001515 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001516 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1517
1518 // Watch for whether or not to keep wifi always on.
1519 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001520 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001521 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Kline05f2b402015-04-30 12:58:40 +09001522 }
1523
Erik Kline31b4a9e2018-01-11 21:07:29 +09001524 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001525 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1526 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001527 }
1528 }
1529
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001530 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001531 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1532 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001533 return mNextNetworkRequestId++;
1534 }
1535
junyulai74f9a8b2018-06-13 15:00:37 +08001536 @VisibleForTesting
1537 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001538 if (network == null) {
1539 return null;
1540 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001541 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001542 }
1543
1544 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001545 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001546 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001547 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001548 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001549
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001550 // TODO: determine what to do when more than one VPN applies to |uid|.
1551 private NetworkAgentInfo getVpnForUid(int uid) {
1552 synchronized (mNetworkForNetId) {
1553 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1554 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1555 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1556 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001557 }
1558 }
1559 }
1560 return null;
1561 }
1562
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001563 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001564 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001565 final NetworkAgentInfo nai = getVpnForUid(uid);
1566 if (nai != null) return nai.declaredUnderlyingNetworks;
1567 return null;
1568 }
1569
Lorenzo Colittia7574052021-01-19 01:33:05 +09001570 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001571 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001572
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001573 final Network[] networks = getVpnUnderlyingNetworks(uid);
1574 if (networks != null) {
1575 // getUnderlyingNetworks() returns:
1576 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1577 // empty array => the VPN explicitly said "no default network".
1578 // non-empty array => the VPN specified one or more default networks; we use the
1579 // first one.
1580 if (networks.length > 0) {
1581 nai = getNetworkAgentInfoForNetwork(networks[0]);
1582 } else {
1583 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001584 }
1585 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001586 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001587 }
1588
1589 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001590 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001591 */
paulhu7aeba372020-12-30 00:42:19 +08001592 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1593 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001594 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001595 if (ignoreBlocked) {
1596 return false;
1597 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001598 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001599 final long ident = Binder.clearCallingIdentity();
1600 try {
1601 final boolean metered = nc == null ? true : nc.isMetered();
1602 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1603 } finally {
1604 Binder.restoreCallingIdentity(ident);
1605 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001606 }
1607
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001608 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001609 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1610 return;
1611 }
Hugo Benichi47011212017-03-30 10:46:05 +09001612 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001613 synchronized (mBlockedAppUids) {
1614 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001615 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001616 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001617 blocked = false;
1618 } else {
1619 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001620 }
1621 }
Hugo Benichi47011212017-03-30 10:46:05 +09001622 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1623 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1624 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001625 }
1626
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001627 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001628 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1629 return;
1630 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001631 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001632 final int requestId = nri.getActiveRequest() != null
1633 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001634 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001635 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001636 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001637 }
1638
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001639 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001640 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001641 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001642 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001643 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001644 @NonNull
1645 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1646 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001647 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1648 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1649 // but only exists if an app asks about them or requests them. Ensure the requesting app
1650 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001651 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001652 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1653 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1654 null /* extraInfo */);
1655 }
1656 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001657 return filtered;
1658 }
1659
1660 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1661 boolean ignoreBlocked) {
1662 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1663 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001664 }
1665
1666 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001667 * Return NetworkInfo for the active (i.e., connected) network interface.
1668 * It is assumed that at most one network is active at a time. If more
1669 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001670 * @return the info for the active network, or {@code null} if none is
1671 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001673 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001674 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001675 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001676 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001677 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1678 if (nai == null) return null;
1679 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1680 maybeLogBlockedNetworkInfo(networkInfo, uid);
1681 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001682 }
1683
Paul Jensen1f567382015-02-13 14:18:39 -05001684 @Override
1685 public Network getActiveNetwork() {
1686 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001687 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001688 }
1689
1690 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001691 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001692 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001693 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001694 }
1695
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001696 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001697 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1698 if (vpnNai != null) {
1699 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1700 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1701 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001702 }
Paul Jensen1f567382015-02-13 14:18:39 -05001703 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001704
James Mattis2516da32021-01-31 17:06:19 -08001705 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001706 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1707 ignoreBlocked)) {
1708 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001709 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001710 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001711 }
1712
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001713 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001714 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001715 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001716 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1717 if (nai == null) return null;
1718 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001719 }
1720
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001721 /** Returns a NetworkInfo object for a network that doesn't exist. */
1722 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1723 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1724 getNetworkTypeName(networkType), "" /* subtypeName */);
1725 info.setIsAvailable(true);
1726 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1727 // background data is restricted.
1728 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1729 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1730 ? DetailedState.BLOCKED
1731 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001732 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1733 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001734 return info;
1735 }
1736
Lorenzo Colittia7574052021-01-19 01:33:05 +09001737 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001738 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1739 return null;
1740 }
1741 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001742 if (nai == null) {
1743 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001744 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001745 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1746 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001747 }
1748
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001749 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001750 public NetworkInfo getNetworkInfo(int networkType) {
1751 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001752 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001753 if (getVpnUnderlyingNetworks(uid) != null) {
1754 // A VPN is active, so we may need to return one of its underlying networks. This
1755 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001756 // getNetworkAgentInfoForUid.
1757 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1758 if (nai == null) return null;
1759 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1760 if (networkInfo.getType() == networkType) {
1761 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001762 }
1763 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001764 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001765 }
1766
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001767 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001768 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001769 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001770 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001771 if (nai == null) return null;
1772 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001773 }
1774
1775 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001776 public NetworkInfo[] getAllNetworkInfo() {
1777 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001778 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001779 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1780 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001781 NetworkInfo info = getNetworkInfo(networkType);
1782 if (info != null) {
1783 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001784 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001786 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001787 }
1788
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001789 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001790 public Network getNetworkForType(int networkType) {
1791 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001792 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1793 return null;
1794 }
1795 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1796 if (nai == null) {
1797 return null;
1798 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001799 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001800 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1801 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001802 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001803 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001804 }
1805
1806 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001807 public Network[] getAllNetworks() {
1808 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001809 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001810 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001811 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001812 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001813 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001814 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001815 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001816 }
1817
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001818 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001819 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001820 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001821 // The basic principle is: if an app's traffic could possibly go over a
1822 // network, without the app doing anything multinetwork-specific,
1823 // (hence, by "default"), then include that network's capabilities in
1824 // the array.
1825 //
1826 // In the normal case, app traffic only goes over the system's default
1827 // network connection, so that's the only network returned.
1828 //
1829 // With a VPN in force, some app traffic may go into the VPN, and thus
1830 // over whatever underlying networks the VPN specifies, while other app
1831 // traffic may go over the system default network (e.g.: a split-tunnel
1832 // VPN, or an app disallowed by the VPN), so the set of networks
1833 // returned includes the VPN's underlying networks and the system
1834 // default.
1835 enforceAccessPermission();
1836
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001837 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001838
James Mattis2516da32021-01-31 17:06:19 -08001839 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1840 if (!nri.isBeingSatisfied()) {
1841 continue;
1842 }
1843 final NetworkAgentInfo nai = nri.getSatisfier();
1844 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1845 if (null != nc
1846 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1847 && !result.containsKey(nai.network)) {
1848 result.put(
1849 nai.network,
1850 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001851 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001852 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1853 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001854 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001855 }
1856
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001857 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001858 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001859 if (null != networks) {
1860 for (final Network network : networks) {
1861 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1862 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001863 result.put(
1864 network,
1865 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001866 nc,
1867 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001868 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001869 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001870 }
1871 }
1872 }
1873
1874 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1875 out = result.values().toArray(out);
1876 return out;
1877 }
1878
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001879 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001880 public boolean isNetworkSupported(int networkType) {
1881 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001882 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001883 }
1884
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001885 /**
1886 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08001887 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001888 * @return the ip properties for the active network, or {@code null} if
1889 * none is active
1890 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001891 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001892 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001893 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001894 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001895 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1896 if (nai == null) return null;
1897 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001898 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001899 }
1900
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001901 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001902 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001903 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001904 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001905 final LinkProperties lp = getLinkProperties(nai);
1906 if (lp == null) return null;
1907 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001908 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001909 }
1910
Robert Greenwaltbe46b752014-05-13 21:41:06 -07001911 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07001912 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001913 public LinkProperties getLinkProperties(Network network) {
1914 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001915 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1916 if (lp == null) return null;
1917 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001918 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09001919 }
1920
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001921 @Nullable
1922 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09001923 if (nai == null) {
1924 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001925 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09001926 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001927 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09001928 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001929 }
1930
Qingxi Lib2748102020-01-08 12:51:49 -08001931 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1932 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1933 }
1934
Lorenzo Colittie97685a2015-05-14 17:28:27 +09001935 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001936 if (nai == null) return null;
1937 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001938 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001939 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001940 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001941 }
1942
1943 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08001944 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1945 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001946 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09001947 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08001948 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08001949 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08001950 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001951 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09001952 }
1953
Qingxi Libb8da982020-01-17 17:54:27 -08001954 @VisibleForTesting
1955 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09001956 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09001957 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09001958 if (!checkSettingsPermission(callerPid, callerUid)) {
1959 newNc.setUids(null);
1960 newNc.setSSID(null);
1961 }
Etan Cohen107ae952018-12-30 17:59:59 -08001962 if (newNc.getNetworkSpecifier() != null) {
1963 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1964 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07001965 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07001966 if (!checkAnyPermissionOf(
1967 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08001968 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07001969 }
Qingxi Libb8da982020-01-17 17:54:27 -08001970
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09001971 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09001972 }
1973
Roshan Pius98f59ec2021-02-23 08:47:39 -08001974 /**
1975 * Wrapper used to cache the permission check results performed for the corresponding
1976 * app. This avoid performing multiple permission checks for different fields in
1977 * NetworkCapabilities.
1978 * Note: This wrapper does not support any sort of invalidation and thus must not be
1979 * persistent or long-lived. It may only be used for the time necessary to
1980 * compute the redactions required by one particular NetworkCallback or
1981 * synchronous call.
1982 */
1983 private class RedactionPermissionChecker {
1984 private final int mCallingPid;
1985 private final int mCallingUid;
1986 @NonNull private final String mCallingPackageName;
1987 @Nullable private final String mCallingAttributionTag;
1988
1989 private Boolean mHasLocationPermission = null;
1990 private Boolean mHasLocalMacAddressPermission = null;
1991 private Boolean mHasSettingsPermission = null;
1992
1993 RedactionPermissionChecker(int callingPid, int callingUid,
1994 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
1995 mCallingPid = callingPid;
1996 mCallingUid = callingUid;
1997 mCallingPackageName = callingPackageName;
1998 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08001999 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002000
2001 private boolean hasLocationPermissionInternal() {
2002 final long token = Binder.clearCallingIdentity();
2003 try {
2004 return mLocationPermissionChecker.checkLocationPermission(
2005 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2006 null /* message */);
2007 } finally {
2008 Binder.restoreCallingIdentity(token);
2009 }
2010 }
2011
2012 /**
2013 * Returns whether the app holds location permission or not (might return cached result
2014 * if the permission was already checked before).
2015 */
2016 public boolean hasLocationPermission() {
2017 if (mHasLocationPermission == null) {
2018 // If there is no cached result, perform the check now.
2019 mHasLocationPermission = hasLocationPermissionInternal();
2020 }
2021 return mHasLocationPermission;
2022 }
2023
2024 /**
2025 * Returns whether the app holds local mac address permission or not (might return cached
2026 * result if the permission was already checked before).
2027 */
2028 public boolean hasLocalMacAddressPermission() {
2029 if (mHasLocalMacAddressPermission == null) {
2030 // If there is no cached result, perform the check now.
2031 mHasLocalMacAddressPermission =
2032 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2033 }
2034 return mHasLocalMacAddressPermission;
2035 }
2036
2037 /**
2038 * Returns whether the app holds settings permission or not (might return cached
2039 * result if the permission was already checked before).
2040 */
2041 public boolean hasSettingsPermission() {
2042 if (mHasSettingsPermission == null) {
2043 // If there is no cached result, perform the check now.
2044 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2045 }
2046 return mHasSettingsPermission;
2047 }
2048 }
2049
2050 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2051 @NetworkCapabilities.NetCapability long redaction) {
2052 return (redactions & redaction) != 0;
2053 }
2054
2055 /**
2056 * Use the provided |applicableRedactions| to check the receiving app's
2057 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2058 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2059 * before being sent to the corresponding app.
2060 */
2061 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2062 @NetworkCapabilities.RedactionType long applicableRedactions,
2063 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2064 boolean includeLocationSensitiveInfo) {
2065 long redactions = applicableRedactions;
2066 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2067 if (includeLocationSensitiveInfo
2068 && redactionPermissionChecker.hasLocationPermission()) {
2069 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2070 }
2071 }
2072 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2073 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2074 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2075 }
2076 }
2077 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2078 if (redactionPermissionChecker.hasSettingsPermission()) {
2079 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2080 }
2081 }
2082 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002083 }
2084
Qingxi Lib2748102020-01-08 12:51:49 -08002085 @VisibleForTesting
2086 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002087 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002088 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002089 int callingPid, int callingUid, @NonNull String callingPkgName,
2090 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002091 if (nc == null) {
2092 return null;
2093 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002094 // Avoid doing location permission check if the transport info has no location sensitive
2095 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002096 final RedactionPermissionChecker redactionPermissionChecker =
2097 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2098 callingAttributionTag);
2099 final long redactions = retrieveRequiredRedactions(
2100 nc.getApplicableRedactions(), redactionPermissionChecker,
2101 includeLocationSensitiveInfo);
2102 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002103 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002104 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002105 newNc.setOwnerUid(INVALID_UID);
2106 return newNc;
2107 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002108 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2109 if (nc.hasTransport(TRANSPORT_VPN)) {
2110 // Owner UIDs already checked above. No need to re-check.
2111 return newNc;
2112 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002113 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2114 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002115 // compatibility for older apps.
2116 if (!includeLocationSensitiveInfo
2117 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002118 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002119 newNc.setOwnerUid(INVALID_UID);
2120 return newNc;
2121 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002122 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002123 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002124 newNc.setOwnerUid(INVALID_UID);
2125 }
Qingxi Lib2748102020-01-08 12:51:49 -08002126 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002127 }
2128
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002129 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2130 LinkProperties lp, int callerPid, int callerUid) {
2131 if (lp == null) return new LinkProperties();
2132
2133 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2134 final boolean needsSanitization =
2135 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2136 if (!needsSanitization) {
2137 return new LinkProperties(lp);
2138 }
2139
2140 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002141 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002142 }
2143
2144 final LinkProperties newLp = new LinkProperties(lp);
2145 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2146 // object gets parceled.
2147 newLp.setCaptivePortalApiUrl(null);
2148 newLp.setCaptivePortalData(null);
2149 return newLp;
2150 }
2151
Roshan Pius08c94fb2020-01-16 12:17:17 -08002152 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2153 int callerUid, String callerPackageName) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09002154 if (!checkSettingsPermission()) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09002155 // There is no need to track the effective UID of the request here. If the caller lacks
2156 // the settings permission, the effective UID is the same as the calling ID.
Roshan Pius08c94fb2020-01-16 12:17:17 -08002157 nc.setSingleUid(callerUid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002158 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002159 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002160 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002161
2162 // Clear owner UID; this can never come from an app.
2163 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002164 }
2165
Chalard Jean38354d12018-03-20 19:13:57 +09002166 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002167 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002168 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2169 }
2170 }
2171
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002172 @Override
2173 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2174 enforceAccessPermission();
2175 final int callerUid = Binder.getCallingUid();
2176 final long token = Binder.clearCallingIdentity();
2177 try {
2178 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2179 } finally {
2180 Binder.restoreCallingIdentity(token);
2181 }
2182 }
2183
junyulaiebd15162021-03-03 12:09:05 +08002184 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002185 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002186 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002187 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002188 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002189
Serik Beketayev05130302021-01-15 16:47:25 -08002190 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002191 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002192 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2193 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002194 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002195 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002196 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002197 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2198 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002199 }
2200 }
2201 return result.toArray(new NetworkState[result.size()]);
2202 }
2203
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002204 @Override
junyulaiebd15162021-03-03 12:09:05 +08002205 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002206 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002207 // This contains IMSI details, so make sure the caller is privileged.
2208 PermissionUtils.enforceNetworkStackPermission(mContext);
2209
2210 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2211 for (Network network : getAllNetworks()) {
2212 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2213 // TODO: Consider include SUSPENDED networks, which should be considered as
2214 // temporary shortage of connectivity of a connected network.
2215 if (nai != null && nai.networkInfo.isConnected()) {
2216 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2217 // NetworkCapabilities, which may contain UIDs of apps to which the
2218 // network applies. Should the UIDs be cleared so as not to leak or
2219 // interfere ?
2220 result.add(nai.getNetworkStateSnapshot());
2221 }
2222 }
2223 return result;
2224 }
2225
2226 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002227 public boolean isActiveNetworkMetered() {
2228 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002229
Qingxi Lib2748102020-01-08 12:51:49 -08002230 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002231 if (caps != null) {
2232 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2233 } else {
2234 // Always return the most conservative value
2235 return true;
2236 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002237 }
2238
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002239 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002240 * Ensures that the system cannot call a particular method.
2241 */
2242 private boolean disallowedBecauseSystemCaller() {
2243 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002244 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2245 // for devices launched with Q and above. However, existing devices upgrading to Q and
2246 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002247 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002248 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002249 log("This method exists only for app backwards compatibility"
2250 + " and must not be called by system services.");
2251 return true;
2252 }
2253 return false;
2254 }
2255
2256 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002257 * Ensure that a network route exists to deliver traffic to the specified
2258 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002259 * @param networkType the type of the network over which traffic to the
2260 * specified host is to be routed
2261 * @param hostAddress the IP address of the host to which the route is
2262 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002263 * @return {@code true} on success, {@code false} on failure
2264 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002265 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002266 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2267 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002268 if (disallowedBecauseSystemCaller()) {
2269 return false;
2270 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002271 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002272 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002273 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002274 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002275
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002276 InetAddress addr;
2277 try {
2278 addr = InetAddress.getByAddress(hostAddress);
2279 } catch (UnknownHostException e) {
2280 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2281 return false;
2282 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002283
The Android Open Source Project28527d22009-03-03 19:31:44 -08002284 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002285 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002286 return false;
2287 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002288
2289 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2290 if (nai == null) {
2291 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2292 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2293 } else {
2294 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2295 }
2296 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002297 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002298
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002299 DetailedState netState;
2300 synchronized (nai) {
2301 netState = nai.networkInfo.getDetailedState();
2302 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002303
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002304 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002305 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002306 log("requestRouteToHostAddress on down network "
2307 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002308 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002309 }
2310 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002311 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002312
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002313 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002314 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002315 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002316 LinkProperties lp;
2317 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002318 synchronized (nai) {
2319 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002320 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002321 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002322 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002323 if (DBG) {
2324 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2325 }
Wink Saville32506bc2013-06-29 21:10:57 -07002326 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002327 } finally {
2328 Binder.restoreCallingIdentity(token);
2329 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002330 }
2331
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002332 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002333 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002334 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002335 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002336 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002337 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002338 if (bestRoute.getGateway().equals(addr)) {
2339 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002340 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002341 } else {
2342 // if we will connect to this through another route, add a direct route
2343 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002344 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002345 }
2346 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002347 if (DBG) log("Adding legacy route " + bestRoute +
2348 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002349
2350 final String dst = bestRoute.getDestinationLinkAddress().toString();
2351 final String nextHop = bestRoute.hasGateway()
2352 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002353 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002354 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2355 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002356 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002357 return false;
2358 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002359 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002360 }
2361
paulhu7c0a2e62021-01-08 00:51:49 +08002362 class DnsResolverUnsolicitedEventCallback extends
2363 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002364 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002365 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002366 try {
2367 mHandler.sendMessage(mHandler.obtainMessage(
2368 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002369 new PrivateDnsValidationUpdate(event.netId,
2370 InetAddresses.parseNumericAddress(event.ipAddress),
2371 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002372 } catch (IllegalArgumentException e) {
2373 loge("Error parsing ip address in validation event");
2374 }
2375 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002376
2377 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002378 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2379 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002380 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2381 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2382 // event callback for certain nai. e.g. cellular. Register here to pass to
2383 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002384 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2385 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2386 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002387 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002388 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002389 }
2390 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002391
2392 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002393 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2394 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2395 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002396 }
dalyk1720e542018-03-05 12:42:22 -05002397
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002398 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002399 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002400 return this.VERSION;
2401 }
2402
2403 @Override
2404 public String getInterfaceHash() {
2405 return this.HASH;
2406 }
paulhu7c0a2e62021-01-08 00:51:49 +08002407 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002408
2409 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002410 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2411 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002412
paulhu7c0a2e62021-01-08 00:51:49 +08002413 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002414 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002415 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002416 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002417 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002418 }
2419 }
2420
Sudheer Shanka9967d462021-03-18 19:09:25 +00002421 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002422 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002423 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2425 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002426 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002427 };
2428
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002429 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002430 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002431 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002432 }
2433
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002434 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002435 for (String permission : permissions) {
2436 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002437 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002438 }
2439 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002440 return false;
2441 }
2442
paulhu1a407652019-03-22 16:35:06 +08002443 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2444 for (String permission : permissions) {
2445 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2446 return true;
2447 }
2448 }
2449 return false;
2450 }
2451
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002452 private void enforceAnyPermissionOf(String... permissions) {
2453 if (!checkAnyPermissionOf(permissions)) {
2454 throw new SecurityException("Requires one of the following permissions: "
2455 + String.join(", ", permissions) + ".");
2456 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002457 }
2458
Paul Jensen83f5d572014-08-29 09:54:01 -04002459 private void enforceInternetPermission() {
2460 mContext.enforceCallingOrSelfPermission(
2461 android.Manifest.permission.INTERNET,
2462 "ConnectivityService");
2463 }
2464
The Android Open Source Project28527d22009-03-03 19:31:44 -08002465 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002466 mContext.enforceCallingOrSelfPermission(
2467 android.Manifest.permission.ACCESS_NETWORK_STATE,
2468 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002469 }
2470
paulhua6ee2122021-02-22 15:40:43 +08002471 /**
2472 * Performs a strict and comprehensive check of whether a calling package is allowed to
2473 * change the state of network, as the condition differs for pre-M, M+, and
2474 * privileged/preinstalled apps. The caller is expected to have either the
2475 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2476 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2477 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2478 * permission and cannot be revoked. See http://b/23597341
2479 *
2480 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2481 * of this app will be updated to the current time.
2482 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002483 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002484 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2485 == PackageManager.PERMISSION_GRANTED) {
2486 return;
2487 }
2488
2489 if (callingPkg == null) {
2490 throw new SecurityException("Calling package name is null.");
2491 }
2492
2493 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2494 final int uid = mDeps.getCallingUid();
2495 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2496 callingPkg, callingAttributionTag, null /* message */);
2497
2498 if (mode == AppOpsManager.MODE_ALLOWED) {
2499 return;
2500 }
2501
2502 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2503 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2504 return;
2505 }
2506
2507 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2508 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2509 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002510 }
2511
Charles He9369e612017-05-15 17:07:18 +01002512 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002513 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002514 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002515 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002516 }
2517
paulhu8e96a752019-08-12 16:25:11 +08002518 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002519 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002520 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002521 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002522 }
2523
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002524 private void enforceNetworkFactoryOrSettingsPermission() {
2525 enforceAnyPermissionOf(
2526 android.Manifest.permission.NETWORK_SETTINGS,
2527 android.Manifest.permission.NETWORK_FACTORY,
2528 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2529 }
2530
2531 private void enforceNetworkFactoryOrTestNetworksPermission() {
2532 enforceAnyPermissionOf(
2533 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2534 android.Manifest.permission.NETWORK_FACTORY,
2535 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2536 }
2537
Chalard Jean9a396cc2018-02-21 18:43:54 +09002538 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002539 return checkAnyPermissionOf(
2540 android.Manifest.permission.NETWORK_SETTINGS,
2541 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002542 }
2543
2544 private boolean checkSettingsPermission(int pid, int uid) {
2545 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002546 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2547 || PERMISSION_GRANTED == mContext.checkPermission(
2548 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002549 }
2550
paulhu8e96a752019-08-12 16:25:11 +08002551 private void enforceNetworkStackOrSettingsPermission() {
2552 enforceAnyPermissionOf(
2553 android.Manifest.permission.NETWORK_SETTINGS,
2554 android.Manifest.permission.NETWORK_STACK,
2555 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2556 }
2557
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002558 private void enforceNetworkStackSettingsOrSetup() {
2559 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002560 android.Manifest.permission.NETWORK_SETTINGS,
2561 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002562 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002563 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002564 }
2565
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002566 private void enforceAirplaneModePermission() {
2567 enforceAnyPermissionOf(
2568 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2569 android.Manifest.permission.NETWORK_SETTINGS,
2570 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2571 android.Manifest.permission.NETWORK_STACK,
2572 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2573 }
2574
James Mattis8378aec2021-01-26 14:05:36 -08002575 private void enforceOemNetworkPreferencesPermission() {
2576 mContext.enforceCallingOrSelfPermission(
2577 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2578 "ConnectivityService");
2579 }
2580
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002581 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002582 return checkAnyPermissionOf(
2583 android.Manifest.permission.NETWORK_STACK,
2584 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002585 }
2586
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002587 private boolean checkNetworkStackPermission(int pid, int uid) {
2588 return checkAnyPermissionOf(pid, uid,
2589 android.Manifest.permission.NETWORK_STACK,
2590 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2591 }
2592
paulhu1a407652019-03-22 16:35:06 +08002593 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2594 return checkAnyPermissionOf(pid, uid,
2595 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002596 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2597 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002598 }
2599
Hugo Benichibd0cc762016-07-19 15:59:27 +09002600 private void enforceConnectivityRestrictedNetworksPermission() {
2601 try {
2602 mContext.enforceCallingOrSelfPermission(
2603 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2604 "ConnectivityService");
2605 return;
2606 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002607 // TODO: Remove this fallback check after all apps have declared
2608 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2609 mContext.enforceCallingOrSelfPermission(
2610 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2611 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002612 }
2613
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002614 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002615 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002616 }
2617
Roshan Pius98f59ec2021-02-23 08:47:39 -08002618 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2619 return PERMISSION_GRANTED == mContext.checkPermission(
2620 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2621 }
2622
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002623 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002624 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002625 }
2626
2627 private void sendInetConditionBroadcast(NetworkInfo info) {
2628 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2629 }
2630
Wink Saville4f0de1e2011-08-04 15:01:58 -07002631 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002632 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002633 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002634 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002635 if (info.isFailover()) {
2636 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2637 info.setFailover(false);
2638 }
2639 if (info.getReason() != null) {
2640 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2641 }
2642 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002643 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2644 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002645 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002646 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002647 return intent;
2648 }
2649
2650 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2651 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2652 }
2653
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002654 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002655 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002656 if (!mSystemReady
2657 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002658 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002659 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002660 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002661 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002662 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002663 }
2664
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002665 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002666 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002667 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002668 final NetworkInfo ni = intent.getParcelableExtra(
2669 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002670 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2671 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2672 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002673 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002674 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002675 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002676 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002677 } finally {
2678 Binder.restoreCallingIdentity(ident);
2679 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002680 }
2681 }
2682
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002683 /**
Aaron Huang96011892020-06-27 07:18:23 +08002684 * Called by SystemServer through ConnectivityManager when the system is ready.
2685 */
2686 @Override
2687 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002688 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002689 throw new SecurityException("Calling Uid is not system uid.");
2690 }
2691 systemReadyInternal();
2692 }
2693
2694 /**
2695 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002696 */
2697 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002698 public void systemReadyInternal() {
Aaron Huang9a57acf2020-12-08 10:03:29 +08002699 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2700 // listening network request which is sent by MultipathPolicyTracker won't be added
2701 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2702 // be called after PermissionMonitor#startMonitoring().
2703 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2704 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2705 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002706 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002707 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002708 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002709
Hugo Benichie5220992017-04-26 14:53:28 +09002710 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002711 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002712 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002713 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002714 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002715 }
2716 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002717
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002718 // Create network requests for always-on networks.
2719 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
The Android Open Source Project28527d22009-03-03 19:31:44 -08002720 }
2721
The Android Open Source Project28527d22009-03-03 19:31:44 -08002722 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002723 * Start listening for default data network activity state changes.
2724 */
2725 @Override
2726 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002727 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002728 }
2729
2730 /**
2731 * Stop listening for default data network activity state changes.
2732 */
2733 @Override
2734 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002735 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002736 }
2737
2738 /**
2739 * Check whether the default network radio is currently active.
2740 */
2741 @Override
2742 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002743 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002744 }
2745
2746 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002747 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002748 * and set it on it's iface.
2749 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002750 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2751 final String iface = newLp.getInterfaceName();
2752 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002753 if (oldLp == null && mtu == 0) {
2754 // Silently ignore unset MTU value.
2755 return;
2756 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002757 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2758 if (VDBG) log("identical MTU - not setting");
2759 return;
2760 }
paulhucbbc3db2019-03-08 16:35:20 +08002761 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002762 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002763 return;
2764 }
sy.yun4aa73922013-09-02 05:24:09 +09002765
w19976e714f1d2014-08-05 15:18:11 -07002766 // Cannot set MTU without interface name
2767 if (TextUtils.isEmpty(iface)) {
2768 loge("Setting MTU size with null iface.");
2769 return;
2770 }
2771
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002772 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002773 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002774 mNetd.interfaceSetMtu(iface, mtu);
2775 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002776 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002777 }
2778 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002779
Chenbo Feng15416292018-11-08 17:36:21 -08002780 @VisibleForTesting
2781 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002782
lucaslin821c9782018-11-28 19:27:52 +08002783 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002784 String[] values = null;
2785 if (tcpBufferSizes != null) {
2786 values = tcpBufferSizes.split(",");
2787 }
2788
2789 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002790 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002791 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2792 values = tcpBufferSizes.split(",");
2793 }
2794
2795 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2796
2797 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002798 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002799
Chenbo Feng15416292018-11-08 17:36:21 -08002800 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2801 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2802 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002803 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002804 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002805 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002806 }
2807 }
2808
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002809 @Override
2810 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002811 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002812 NETWORK_RESTORE_DELAY_PROP_NAME);
2813 if(restoreDefaultNetworkDelayStr != null &&
2814 restoreDefaultNetworkDelayStr.length() != 0) {
2815 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002816 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002817 } catch (NumberFormatException e) {
2818 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002819 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002820 // if the system property isn't set, use the value for the apn type
2821 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2822
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002823 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2824 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002825 }
2826 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002827 }
2828
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002829 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2830 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2831 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09002832 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08002833 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002834 // Start gathering diagnostic information.
2835 netDiags.add(new NetworkDiagnostics(
2836 nai.network,
2837 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08002838 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002839 DIAG_TIME_MS));
2840 }
2841
2842 for (NetworkDiagnostics netDiag : netDiags) {
2843 pw.println();
2844 netDiag.waitForMeasurements();
2845 netDiag.dump(pw);
2846 }
2847 }
2848
The Android Open Source Project28527d22009-03-03 19:31:44 -08002849 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09002850 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2851 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08002852 if (!checkDumpPermission(mContext, TAG, writer)) return;
2853
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08002854 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07002855 }
2856
lucaslin99473f62020-12-10 15:10:54 +08002857 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2858 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2859 != PackageManager.PERMISSION_GRANTED) {
2860 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002861 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08002862 + " due to missing android.permission.DUMP permission");
2863 return false;
2864 } else {
2865 return true;
2866 }
2867 }
2868
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08002869 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002870 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002871
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002872 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002873 dumpNetworkDiagnostics(pw);
2874 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002875 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002876 dumpNetworks(pw);
2877 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002878 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002879 dumpNetworkRequests(pw);
2880 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002881 }
Erik Kline9647f382015-06-05 17:47:34 +09002882
Lorenzo Colittia86fae72020-01-10 00:40:28 +09002883 pw.print("NetworkProviders for:");
2884 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2885 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07002886 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09002887 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07002888 pw.println();
2889
Chalard Jean5b409c72021-02-04 13:12:59 +09002890 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002891 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09002892 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002893 pw.println("none");
2894 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09002895 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002896 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002897 pw.println();
2898
James Mattis45d81842021-01-10 14:24:24 -08002899 pw.print("Current per-app default networks: ");
2900 pw.increaseIndent();
2901 dumpPerAppNetworkPreferences(pw);
2902 pw.decreaseIndent();
2903 pw.println();
2904
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002905 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002906 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002907 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002908 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002909 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002910
junyulaif2c67e42018-08-07 19:50:45 +08002911 pw.println("Status for known UIDs:");
2912 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00002913 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08002914 for (int i = 0; i < size; i++) {
2915 // Don't crash if the array is modified while dumping in bugreports.
2916 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002917 final int uid = mUidBlockedReasons.keyAt(i);
2918 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2919 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002920 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08002921 } catch (ArrayIndexOutOfBoundsException e) {
2922 pw.println(" ArrayIndexOutOfBoundsException");
2923 } catch (ConcurrentModificationException e) {
2924 pw.println(" ConcurrentModificationException");
2925 }
2926 }
2927 pw.println();
2928 pw.decreaseIndent();
2929
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002930 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002931 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002932 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002933 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002934 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002935
Robert Greenwalt94e22142014-07-30 16:31:24 -07002936 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07002937
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002938 pw.println();
markchien5e866652019-09-30 14:40:57 +08002939 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002940
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002941 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09002942 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002943
Lorenzo Colitti389a8142018-01-24 17:35:07 +09002944 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09002945
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002946 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07002947 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09002948 pw.println("mNetworkRequestInfoLogs (most recent first):");
2949 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07002950 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09002951 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09002952
2953 pw.println();
2954 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2955 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07002956 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09002957 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09002958
2959 pw.println();
2960 pw.println("NetTransition WakeLock activity (most recent first):");
2961 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09002962 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2963 pw.println("total releases: " + mTotalWakelockReleases);
2964 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2965 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2966 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2967 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2968 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2969 }
James Mattiscb1e0362021-04-06 17:07:42 -07002970 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07002971
2972 pw.println();
2973 pw.println("bandwidth update requests (by uid):");
2974 pw.increaseIndent();
2975 synchronized (mBandwidthRequests) {
2976 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2977 pw.println("[" + mBandwidthRequests.keyAt(i)
2978 + "]: " + mBandwidthRequests.valueAt(i));
2979 }
2980 }
2981 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07002982 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07002983
James Mattiscb1e0362021-04-06 17:07:42 -07002984 pw.println();
2985 pw.println("mOemNetworkPreferencesLogs (most recent first):");
2986 pw.increaseIndent();
2987 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09002988 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07002989 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09002990
2991 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00002992
2993 pw.println();
2994 pw.println("Permission Monitor:");
2995 pw.increaseIndent();
2996 mPermissionMonitor.dump(pw);
2997 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08002998
2999 pw.println();
3000 pw.println("Legacy network activity:");
3001 pw.increaseIndent();
3002 mNetworkActivityTracker.dump(pw);
3003 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003004 }
3005
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003006 private void dumpNetworks(IndentingPrintWriter pw) {
3007 for (NetworkAgentInfo nai : networksSortedById()) {
3008 pw.println(nai.toString());
3009 pw.increaseIndent();
3010 pw.println(String.format(
3011 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3012 nai.numForegroundNetworkRequests(),
3013 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3014 nai.numBackgroundNetworkRequests(),
3015 nai.numNetworkRequests()));
3016 pw.increaseIndent();
3017 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3018 pw.println(nai.requestAt(i).toString());
3019 }
3020 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003021 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003022 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003023 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003024 pw.decreaseIndent();
3025 pw.decreaseIndent();
3026 }
3027 }
3028
James Mattis45d81842021-01-10 14:24:24 -08003029 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3030 pw.println("Per-App Network Preference:");
3031 pw.increaseIndent();
3032 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3033 pw.println("none");
3034 } else {
3035 pw.println(mOemNetworkPreferences.toString());
3036 }
3037 pw.decreaseIndent();
3038
3039 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3040 if (mDefaultRequest == defaultRequest) {
3041 continue;
3042 }
3043
3044 final boolean isActive = null != defaultRequest.getSatisfier();
3045 pw.println("Is per-app network active:");
3046 pw.increaseIndent();
3047 pw.println(isActive);
3048 if (isActive) {
3049 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3050 }
3051 pw.println("Tracked UIDs:");
3052 pw.increaseIndent();
3053 if (0 == defaultRequest.mRequests.size()) {
3054 pw.println("none, this should never occur.");
3055 } else {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00003056 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
James Mattis45d81842021-01-10 14:24:24 -08003057 }
3058 pw.decreaseIndent();
3059 pw.decreaseIndent();
3060 }
3061 }
3062
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003063 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3064 for (NetworkRequestInfo nri : requestsSortedById()) {
3065 pw.println(nri.toString());
3066 }
3067 }
3068
Hugo Benichia480ba52018-09-03 08:19:02 +09003069 /**
3070 * Return an array of all current NetworkAgentInfos sorted by network id.
3071 */
3072 private NetworkAgentInfo[] networksSortedById() {
3073 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003074 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003075 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003076 return networks;
3077 }
3078
3079 /**
3080 * Return an array of all current NetworkRequest sorted by request id.
3081 */
James Mattis258ea3c2020-11-15 15:04:40 -08003082 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003083 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003084 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003085 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003086 // Sort the array based off the NRI containing the min requestId in its requests.
3087 Arrays.sort(requests,
3088 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3089 Comparator.comparingInt(req -> req.requestId)).requestId
3090 )
3091 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003092 return requests;
3093 }
3094
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003095 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003096 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003097 if (officialNai != null && officialNai.equals(nai)) return true;
3098 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003099 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003100 " - " + nai);
3101 }
3102 return false;
3103 }
3104
Robert Greenwalt2034b912009-08-12 16:08:25 -07003105 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003106 private class NetworkStateTrackerHandler extends Handler {
3107 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003108 super(looper);
3109 }
3110
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003111 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003112 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3113 final NetworkAgentInfo nai = arg.first;
3114 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003115 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003116 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003117 }
3118 return;
3119 }
3120
3121 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003122 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003123 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003124 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003125 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003126 }
Chalard Jean5b639762020-03-09 21:25:37 +09003127 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3128 // Make sure the original object is not mutated. NetworkAgent normally
3129 // makes a copy of the capabilities when sending the message through
3130 // the Messenger, but if this ever changes, not making a defensive copy
3131 // here will give attack vectors to clients using this code path.
3132 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Cody Kestingfc7cad32020-04-07 16:07:33 -07003133 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003134 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003135 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003136 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003137 break;
3138 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003139 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003140 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003141 processLinkPropertiesFromAgent(nai, newLp);
3142 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003143 break;
3144 }
3145 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003146 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003147 updateNetworkInfo(nai, info);
3148 break;
3149 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003150 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003151 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003152 break;
3153 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003154 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003155 if (nai.everConnected) {
3156 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003157 // Note that if the NAI had been connected, this would affect the
3158 // score, and therefore would require re-mixing the score and performing
3159 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003160 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003161 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3162 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003163 // Mark the network as temporarily accepting partial connectivity so that it
3164 // will be validated (and possibly become default) even if it only provides
3165 // partial internet access. Note that if user connects to partial connectivity
3166 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3167 // out of wifi coverage) and if the same wifi is available again, the device
3168 // will auto connect to this wifi even though the wifi has "no internet".
3169 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003170 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003171 break;
3172 }
junyulai011b1f12019-01-03 18:50:15 +08003173 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003174 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003175 break;
3176 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003177 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003178 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003179 if (!nai.supportsUnderlyingNetworks()) {
3180 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3181 break;
3182 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003183
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003184 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003185
3186 if (isLegacyLockdownNai(nai)
3187 && (underlying == null || underlying.size() != 1)) {
3188 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3189 + " must have exactly one underlying network: " + underlying);
3190 }
3191
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003192 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3193 nai.declaredUnderlyingNetworks = (underlying != null)
3194 ? underlying.toArray(new Network[0]) : null;
3195
3196 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3197 if (DBG) {
3198 log(nai.toShortString() + " changed underlying networks to "
3199 + Arrays.toString(nai.declaredUnderlyingNetworks));
3200 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003201 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003202 notifyIfacesChangedForNetworkStats();
3203 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003204 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003205 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003206 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3207 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3208 nai.teardownDelayMs = msg.arg1;
3209 } else {
3210 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3211 }
3212 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003213 }
3214 }
3215
3216 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3217 switch (msg.what) {
3218 default:
3219 return false;
lucasline117e2e2019-10-22 18:27:33 +08003220 case EVENT_PROBE_STATUS_CHANGED: {
3221 final Integer netId = (Integer) msg.obj;
3222 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3223 if (nai == null) {
3224 break;
3225 }
3226 final boolean probePrivateDnsCompleted =
3227 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3228 final boolean privateDnsBroken =
3229 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3230 if (probePrivateDnsCompleted) {
3231 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3232 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003233 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003234 }
3235 // Only show the notification when the private DNS is broken and the
3236 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003237 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003238 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3239 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003240 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003241 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3242 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3243 // private DNS is broken, it means this network is being reevaluated.
3244 // Either probing private DNS is not necessary any more or it hasn't been
3245 // done yet. In either case, the networkCapabilities should be updated to
3246 // reflect the new status.
3247 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003248 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003249 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003250 }
3251 break;
3252 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003253 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003254 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3255
3256 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003257 if (nai == null) break;
3258
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003259 handleNetworkTested(nai, results.mTestResult,
3260 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003261 break;
3262 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003263 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003264 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003265 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003266 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003267 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003268 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3269 nai.lastCaptivePortalDetected = visible;
3270 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003271 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003272 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3273 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003274 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003275 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003276 teardownUnneededNetwork(nai);
3277 break;
3278 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003279 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003280 }
3281 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003282 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003283 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003284 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3285 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003286 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003287 if (nai == null) {
3288 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3289 break;
3290 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003291 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003292 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003293 (PendingIntent) msg.obj,
3294 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003295 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003296 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003297 break;
3298 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003299 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003300 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003301 if (nai == null) break;
3302
Erik Kline9a62f012018-03-21 07:18:33 -07003303 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003304 break;
3305 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003306 case EVENT_CAPPORT_DATA_CHANGED: {
3307 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3308 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003309 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003310 break;
3311 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003312 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003313 return true;
3314 }
3315
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003316 private void handleNetworkTested(
3317 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3318 final boolean wasPartial = nai.partialConnectivity;
3319 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3320 final boolean partialConnectivityChanged =
3321 (wasPartial != nai.partialConnectivity);
3322
3323 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3324 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003325 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003326
3327 if (DBG) {
3328 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3329 ? " with redirect to " + redirectUrl
3330 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003331 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003332 }
3333 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003334 final int oldScore = nai.getCurrentScore();
3335 nai.lastValidated = valid;
3336 nai.everValidated |= valid;
3337 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3338 // If score has changed, rebroadcast to NetworkProviders. b/17726566
3339 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
3340 if (valid) {
3341 handleFreshlyValidatedNetwork(nai);
3342 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3343 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003344 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003345 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003346 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003347 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003348 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003349 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003350 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003351 NotificationType.PRIVATE_DNS_BROKEN);
3352 // If network becomes valid, the hasShownBroken should be reset for
3353 // that network so that the notification will be fired when the private
3354 // DNS is broken again.
3355 nai.networkAgentConfig.hasShownBroken = false;
3356 }
3357 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003358 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003359 }
3360 updateInetCondition(nai);
3361 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003362 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003363 nai.onValidationStatusChanged(
3364 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3365 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003366
3367 // If NetworkMonitor detects partial connectivity before
3368 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3369 // immediately. Re-notify partial connectivity silently if no internet
3370 // notification already there.
3371 if (!wasPartial && nai.partialConnectivity) {
3372 // Remove delayed message if there is a pending message.
3373 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3374 handlePromptUnvalidated(nai.network);
3375 }
3376
3377 if (wasValidated && !nai.lastValidated) {
3378 handleNetworkUnvalidated(nai);
3379 }
3380 }
3381
Calvin Ondada1452016-10-11 15:10:46 -07003382 private int getCaptivePortalMode() {
3383 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003384 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3385 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003386 }
3387
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003388 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3389 switch (msg.what) {
3390 default:
3391 return false;
3392 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3393 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3394 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3395 handleLingerComplete(nai);
3396 }
3397 break;
3398 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003399 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3400 handleNetworkAgentRegistered(msg);
3401 break;
3402 }
3403 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3404 handleNetworkAgentDisconnected(msg);
3405 break;
3406 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003407 }
3408 return true;
3409 }
3410
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003411 @Override
3412 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003413 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003414 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003415 maybeHandleNetworkAgentMessage(msg);
3416 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003417 }
3418 }
3419
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003420 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003421 private final int mNetId;
3422 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003423
3424 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003425 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003426 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003427 }
3428
3429 @Override
3430 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3431 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003432 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003433 }
3434
3435 @Override
3436 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003437 // Legacy version of notifyNetworkTestedWithExtras.
3438 // Would only be called if the system has a NetworkStack module older than the
3439 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003440 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003441 }
3442
3443 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003444 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003445 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3446 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003447 final Message msg = mTrackerHandler.obtainMessage(
3448 EVENT_NETWORK_TESTED,
3449 new NetworkTestedResults(
3450 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003451 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003452
3453 // Invoke ConnectivityReport generation for this Network test event.
3454 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3455 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003456
3457 final PersistableBundle extras = new PersistableBundle();
3458 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3459 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3460 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3461
Aaron Huang959d3642021-01-21 15:47:41 +08003462 ConnectivityReportEvent reportEvent =
3463 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3464 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3465 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003466 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003467 }
3468
3469 @Override
3470 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3471 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3472 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003473 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003474 }
3475
3476 @Override
lucasline117e2e2019-10-22 18:27:33 +08003477 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3478 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3479 EVENT_PROBE_STATUS_CHANGED,
3480 probesCompleted, probesSucceeded, new Integer(mNetId)));
3481 }
3482
3483 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003484 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3485 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3486 EVENT_CAPPORT_DATA_CHANGED,
3487 0, mNetId, data));
3488 }
3489
3490 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003491 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003492 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003493 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003494
3495 final PendingIntent pendingIntent;
3496 // Only the system server can register notifications with package "android"
3497 final long token = Binder.clearCallingIdentity();
3498 try {
paulhu7746e4e2020-06-09 19:07:03 +08003499 pendingIntent = PendingIntent.getBroadcast(
3500 mContext,
3501 0 /* requestCode */,
3502 intent,
3503 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003504 } finally {
3505 Binder.restoreCallingIdentity(token);
3506 }
3507 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3508 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003509 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003510 }
3511
3512 @Override
3513 public void hideProvisioningNotification() {
3514 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003515 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003516 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003517
3518 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003519 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003520 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003521 }
3522
3523 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003524 public int getInterfaceVersion() {
3525 return this.VERSION;
3526 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003527
3528 @Override
3529 public String getInterfaceHash() {
3530 return this.HASH;
3531 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003532 }
3533
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003534 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003535 log("Data stall detected with methods: " + p.detectionMethod);
3536
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003537 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003538 int detectionMethod = 0;
3539 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3540 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3541 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3542 }
3543 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3544 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3545 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3546 p.tcpMetricsCollectionPeriodMillis);
3547 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003548 }
3549
Cody Kestingf53a0752020-04-15 12:33:28 -07003550 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003551 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003552 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003553
3554 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3555 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3556 // the cost of going through two handlers.
3557 mConnectivityDiagnosticsHandler.sendMessage(msg);
3558 }
3559
Cody Kestingb37958e2020-05-15 10:36:01 -07003560 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3561 return (p.detectionMethod & detectionMethod) != 0;
3562 }
3563
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003564 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3565 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003566 }
3567
Erik Klinea73af002018-06-26 18:53:43 +09003568 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3569 if (nai == null) return;
3570 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3571 // in order to restart a validation pass from within netd.
3572 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3573 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003574 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003575 }
3576 }
3577
Erik Kline31b4a9e2018-01-11 21:07:29 +09003578 private void handlePrivateDnsSettingsChanged() {
3579 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3580
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003581 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003582 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003583 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003584 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3585 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003586 }
3587 }
3588
Erik Kline9a62f012018-03-21 07:18:33 -07003589 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3590 // Private DNS only ever applies to networks that might provide
3591 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003592 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003593
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003594 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003595 // schedule DNS resolutions. If a DNS resolution is required the
3596 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003597 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003598
3599 // With Private DNS bypass support, we can proceed to update the
3600 // Private DNS config immediately, even if we're in strict mode
3601 // and have not yet resolved the provider name into a set of IPs.
3602 updatePrivateDns(nai, cfg);
3603 }
3604
3605 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3606 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003607 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003608 }
3609
dalyk1720e542018-03-05 12:42:22 -05003610 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3611 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3612 if (nai == null) {
3613 return;
3614 }
3615 mDnsManager.updatePrivateDnsValidation(update);
3616 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3617 }
3618
paulhu7c0a2e62021-01-08 00:51:49 +08003619 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003620 int prefixLength) {
3621 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3622 if (nai == null) return;
3623
paulhu7c0a2e62021-01-08 00:51:49 +08003624 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3625 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003626
3627 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003628 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003629 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003630 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003631 prefixLength);
3632 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003633 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003634 return;
3635 }
3636 }
3637
Lorenzo Colittid523d142020-04-01 20:16:30 +09003638 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003639 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3640 }
3641
Hai Shalome58bdc62021-01-11 18:45:34 -08003642 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003643 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003644 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003645 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3646 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3647 }
3648
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003649 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003650 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003651 * @param nai the agent info to update
3652 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003653 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003654 */
junyulai2b6f0c22021-02-03 20:15:30 +08003655 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3656 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3657 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003658 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003659 // one lingered request, set inactive.
3660 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003661 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003662 if (DBG) log("Unsetting inactive " + nai.toShortString());
3663 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003664 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003665 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003666 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003667 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3668 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003669 }
junyulai2b6f0c22021-02-03 20:15:30 +08003670 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003671 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003672 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003673 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003674 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003675 }
3676
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003677 private void handleNetworkAgentRegistered(Message msg) {
3678 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3679 if (!mNetworkAgentInfos.contains(nai)) {
3680 return;
3681 }
3682
3683 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3684 if (VDBG) log("NetworkAgent registered");
3685 } else {
3686 loge("Error connecting NetworkAgent");
3687 mNetworkAgentInfos.remove(nai);
3688 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003689 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003690 synchronized (mNetworkForNetId) {
3691 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003692 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003693 mNetIdManager.releaseNetId(nai.network.getNetId());
3694 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003695 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003696 }
3697 }
3698 }
Paul Jensend5f53392014-11-25 15:26:53 -05003699
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003700 private void handleNetworkAgentDisconnected(Message msg) {
3701 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3702 if (mNetworkAgentInfos.contains(nai)) {
3703 disconnectAndDestroyNetwork(nai);
3704 }
3705 }
3706
Chalard Jeand9fffc32018-05-11 20:19:20 +09003707 // Destroys a network, remove references to it from the internal state managed by
3708 // ConnectivityService, free its interfaces and clean up.
3709 // Must be called on the Handler thread.
3710 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003711 ensureRunningOnConnectivityServiceThread();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003712 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003713 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003714 }
lucaslinb25c9a62019-02-12 15:30:13 +08003715 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003716 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003717 // A network agent has disconnected.
3718 // TODO - if we move the logic to the network agent (have them disconnect
3719 // because they lost all their requests or because their score isn't good)
3720 // then they would disconnect organically, report their new state and then
3721 // disconnect the channel.
3722 if (nai.networkInfo.isConnected()) {
3723 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3724 null, null);
3725 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003726 final boolean wasDefault = isDefaultNetwork(nai);
3727 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003728 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003729 }
3730 notifyIfacesChangedForNetworkStats();
3731 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3732 // by other networks that are already connected. Perhaps that can be done by
3733 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3734 // of rematchAllNetworksAndRequests
3735 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003736 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003737
3738 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003739 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3740 // Disable wakeup packet monitoring for each interface.
3741 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3742 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003743 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003744 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003745 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003746 synchronized (mNetworkForNetId) {
3747 // Remove the NetworkAgent, but don't mark the netId as
3748 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003749 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003750 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09003751 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003752 // Remove all previously satisfied requests.
3753 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003754 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09003755 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08003756 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08003757 if (currentNetwork != null
3758 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003759 // uid rules for this network will be removed in destroyNativeNetwork(nai).
James Mattisa076c532020-12-02 14:12:41 -08003760 nri.setSatisfier(null, null);
James Mattisd31bdfa2020-12-23 16:37:26 -08003761 if (request.isRequest()) {
3762 sendUpdatedScoreToFactories(request, null);
3763 }
James Mattise3ef1912020-12-20 11:09:58 -08003764
Chalard Jean5b409c72021-02-04 13:12:59 +09003765 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08003766 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09003767 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08003768 // network, because while incorrect this is the closest to the old (also
3769 // incorrect) behavior.
3770 mNetworkActivityTracker.updateDataActivityTracking(
3771 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08003772 ensureNetworkTransitionWakelock(nai.toShortString());
3773 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09003774 }
3775 }
junyulai2b6f0c22021-02-03 20:15:30 +08003776 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08003777 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09003778 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08003779 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09003780 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09003781 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003782 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003783
3784 // Immediate teardown.
3785 if (nai.teardownDelayMs == 0) {
3786 destroyNetwork(nai);
3787 return;
3788 }
3789
3790 // Delayed teardown.
3791 try {
3792 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3793 } catch (RemoteException e) {
3794 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3795 }
3796 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3797 }
3798
3799 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003800 if (nai.created) {
3801 // Tell netd to clean up the configuration for this network
3802 // (routing rules, DNS, etc).
3803 // This may be slow as it requires a lot of netd shelling out to ip and
3804 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09003805 // after we've rematched networks with requests (which might change the default
3806 // network or service a new request from an app), so network traffic isn't interrupted
3807 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08003808 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003809 mDnsManager.removeNetwork(nai.network);
3810 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08003811 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003812 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003813 }
3814
Ken Chen6df7a902021-04-09 15:08:42 +08003815 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08003816 try {
3817 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08003818 final NativeNetworkConfig config;
3819 if (nai.isVPN()) {
3820 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08003821 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08003822 return false;
3823 }
3824 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3825 INetd.PERMISSION_NONE,
3826 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3827 getVpnType(nai));
Luke Huangfdd11f82019-04-09 18:41:49 +08003828 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08003829 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3830 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3831 VpnManager.TYPE_VPN_NONE);
Luke Huangfdd11f82019-04-09 18:41:49 +08003832 }
Ken Chen6df7a902021-04-09 15:08:42 +08003833 mNetd.networkCreate(config);
3834 mDnsResolver.createNetworkCache(nai.network.getNetId());
3835 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3836 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08003837 return true;
3838 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08003839 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08003840 return false;
3841 }
3842 }
3843
Ken Chen6df7a902021-04-09 15:08:42 +08003844 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08003845 try {
Ken Chen6df7a902021-04-09 15:08:42 +08003846 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09003847 } catch (RemoteException | ServiceSpecificException e) {
3848 loge("Exception destroying network(networkDestroy): " + e);
3849 }
3850 try {
Ken Chen6df7a902021-04-09 15:08:42 +08003851 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08003852 } catch (RemoteException | ServiceSpecificException e) {
3853 loge("Exception destroying network: " + e);
3854 }
3855 }
3856
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003857 // If this method proves to be too slow then we can maintain a separate
3858 // pendingIntent => NetworkRequestInfo map.
3859 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3860 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003861 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3862 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3863 if (existingPendingIntent != null &&
paulhu90b43ff2021-03-04 11:36:55 +08003864 existingPendingIntent.intentFilterEquals(pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003865 return entry.getValue();
3866 }
3867 }
3868 return null;
3869 }
3870
James Mattisf7027322020-12-13 16:28:14 -08003871 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003872 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08003873 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3874 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3875 final NetworkRequestInfo existingRequest =
3876 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003877 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08003878 if (DBG) {
3879 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3880 + nri.mRequests.get(0) + " because their intents matched.");
3881 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09003882 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08003883 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003884 }
Erik Kline05f2b402015-04-30 12:58:40 +09003885 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003886 }
3887
James Mattisf7027322020-12-13 16:28:14 -08003888 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08003889 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08003890 }
3891
James Mattis3ce3d3c2021-02-09 18:18:28 -08003892 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003893 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08003894 for (final NetworkRequestInfo nri : nris) {
3895 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3896 for (final NetworkRequest req : nri.mRequests) {
3897 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08003898 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08003899 if (req.isListen()) {
3900 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3901 if (req.networkCapabilities.hasSignalStrength()
3902 && network.satisfiesImmutableCapabilitiesOf(req)) {
3903 updateSignalStrengthThresholds(network, "REGISTER", req);
3904 }
James Mattisf7027322020-12-13 16:28:14 -08003905 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09003906 }
3907 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09003908 // If this NRI has a satisfier already, it is replacing an older request that
3909 // has been removed. Track it.
3910 final NetworkRequest activeRequest = nri.getActiveRequest();
3911 if (null != activeRequest) {
3912 // If there is an active request, then for sure there is a satisfier.
3913 nri.getSatisfier().addRequest(activeRequest);
3914 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09003915 }
James Mattisf7027322020-12-13 16:28:14 -08003916
James Mattis45d81842021-01-10 14:24:24 -08003917 rematchAllNetworksAndRequests();
3918 for (final NetworkRequestInfo nri : nris) {
3919 // If the nri is satisfied, return as its score has already been sent if needed.
3920 if (nri.isBeingSatisfied()) {
3921 return;
3922 }
3923
3924 // As this request was not satisfied on rematch and thus never had any scores sent to
3925 // the factories, send null now for each request of type REQUEST.
3926 for (final NetworkRequest req : nri.mRequests) {
3927 if (req.isRequest()) sendUpdatedScoreToFactories(req, null);
3928 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003929 }
3930 }
3931
James Mattisf7027322020-12-13 16:28:14 -08003932 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3933 final int callingUid) {
3934 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003935 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08003936 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3937 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3938 handleReleaseNetworkRequest(
3939 nri.mRequests.get(0),
3940 callingUid,
3941 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003942 }
3943 }
3944
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003945 // Determines whether the network is the best (or could become the best, if it validated), for
3946 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3947 // on the value of reason:
3948 //
3949 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3950 // then it should be torn down.
3951 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3952 // then it should be lingered.
3953 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003954 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003955 final int numRequests;
3956 switch (reason) {
3957 case TEARDOWN:
3958 numRequests = nai.numRequestNetworkRequests();
3959 break;
3960 case LINGER:
3961 numRequests = nai.numForegroundNetworkRequests();
3962 break;
3963 default:
Aaron Huang6616df32020-10-30 22:04:25 +08003964 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003965 return true;
3966 }
3967
junyulai0ac374f2020-12-14 18:41:52 +08003968 if (!nai.everConnected || nai.isVPN() || nai.isInactive() || numRequests > 0) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003969 return false;
3970 }
Paul Jensende49eb12015-06-25 15:30:08 -04003971 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08003972 if (reason == UnneededFor.LINGER
3973 && !nri.isMultilayerRequest()
3974 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003975 // Background requests don't affect lingering.
3976 continue;
3977 }
3978
James Mattis3d229892020-11-16 16:46:28 -08003979 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04003980 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05003981 }
3982 }
Paul Jensende49eb12015-06-25 15:30:08 -04003983 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05003984 }
3985
James Mattis3d229892020-11-16 16:46:28 -08003986 private boolean isNetworkPotentialSatisfier(
3987 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
3988 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08003989 // request, return immediately. For multilayer requests, check to see if any of the
3990 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08003991 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
3992 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08003993 return false;
3994 }
3995 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08003996 // This multilayer listen request is satisfied therefore no further requests need to be
3997 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08003998 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08003999 return false;
4000 }
James Mattis3d229892020-11-16 16:46:28 -08004001 // As non-multilayer listen requests have already returned, the below would only happen
4002 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004003 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004004 continue;
4005 }
4006 // If this Network is already the highest scoring Network for a request, or if
4007 // there is hope for it to become one if it validated, then it is needed.
4008 if (candidate.satisfies(req)) {
4009 // As soon as a network is found that satisfies a request, return. Specifically for
4010 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4011 // is important so as to not evaluate lower priority requests further in
4012 // nri.mRequests.
4013 final boolean isNetworkNeeded = candidate.isSatisfyingRequest(req.requestId)
4014 // Note that this catches two important cases:
4015 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4016 // is currently satisfying the request. This is desirable when
4017 // cellular ends up validating but WiFi does not.
4018 // 2. Unvalidated WiFi will not be reaped when validated cellular
4019 // is currently satisfying the request. This is desirable when
4020 // WiFi ends up validating and out scoring cellular.
James Mattisa076c532020-12-02 14:12:41 -08004021 || nri.getSatisfier().getCurrentScore()
James Mattis3d229892020-11-16 16:46:28 -08004022 < candidate.getCurrentScoreAsValidated();
4023 return isNetworkNeeded;
4024 }
4025 }
4026
4027 return false;
4028 }
4029
Erik Kline0c04b742016-07-07 16:50:58 +09004030 private NetworkRequestInfo getNriForAppRequest(
4031 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004032 // Looking up the app passed param request in mRequests isn't possible since it may return
4033 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4034 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004035 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4036 // to avoid potential race conditions when validating a package->uid mapping when sending
4037 // the callback on the very low-chance that an application shuts down prior to the callback
4038 // being sent.
4039 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4040 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004041
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004042 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004043 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004044 log(String.format("UID %d attempted to %s for unowned request %s",
4045 callingUid, requestedOperation, nri));
4046 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004047 }
Erik Kline0c04b742016-07-07 16:50:58 +09004048 }
4049
4050 return nri;
4051 }
4052
James Mattisf7027322020-12-13 16:28:14 -08004053 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4054 final String callingMethod) {
4055 if (nri.isMultilayerRequest()) {
4056 throw new IllegalStateException(
4057 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004058 }
4059 }
4060
James Mattisf7027322020-12-13 16:28:14 -08004061 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004062 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004063 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4064 // single NetworkRequest and thus does not apply to multilayer requests.
4065 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4066 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004067 return;
4068 }
James Mattis2516da32021-01-31 17:06:19 -08004069 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004070 return;
4071 }
James Mattisf7027322020-12-13 16:28:14 -08004072 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4073 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004074 }
4075 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004076 callCallbackForRequest(
4077 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004078 }
4079
James Mattisf7027322020-12-13 16:28:14 -08004080 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4081 final int callingUid,
4082 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004083 final NetworkRequestInfo nri =
4084 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4085 if (nri == null) {
4086 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004087 }
James Mattisf7027322020-12-13 16:28:14 -08004088 if (VDBG || (DBG && request.isRequest())) {
4089 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004090 }
4091 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004092 if (callOnUnavailable) {
4093 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4094 }
Erik Kline155a59a2015-11-25 12:49:38 +09004095 }
Erik Kline0c04b742016-07-07 16:50:58 +09004096
James Mattisa076c532020-12-02 14:12:41 -08004097 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004098 ensureRunningOnConnectivityServiceThread();
Erik Kline0c04b742016-07-07 16:50:58 +09004099 nri.unlinkDeathRecipient();
James Mattisa076c532020-12-02 14:12:41 -08004100 for (final NetworkRequest req : nri.mRequests) {
4101 mNetworkRequests.remove(req);
4102 if (req.isListen()) {
4103 removeListenRequestFromNetworks(req);
4104 }
4105 }
Chalard Jean738c5bf2021-03-01 22:08:57 +09004106 if (mDefaultNetworkRequests.remove(nri)) {
4107 // If this request was one of the defaults, then the UID rules need to be updated
4108 // WARNING : if the app(s) for which this network request is the default are doing
4109 // traffic, this will kill their connected sockets, even if an equivalent request
4110 // is going to be reinstated right away ; unconnected traffic will go on the default
4111 // until the new default is set, which will happen very soon.
4112 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4113 // remove ranges for those requests that won't have a replacement
4114 final NetworkAgentInfo satisfier = nri.getSatisfier();
4115 if (null != satisfier) {
4116 try {
4117 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4118 toUidRangeStableParcels(nri.getUids()));
4119 } catch (RemoteException e) {
4120 loge("Exception setting network preference default network", e);
4121 }
4122 }
4123 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004124 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004125 mNetworkRequestInfoLogs.log("RELEASE " + nri);
James Mattisa076c532020-12-02 14:12:41 -08004126
4127 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004128 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004129 removeSatisfiedNetworkRequestFromNetwork(nri);
4130 } else {
4131 nri.setSatisfier(null, null);
4132 }
4133 }
4134
4135 cancelNpiRequests(nri);
4136 }
4137
James Mattis3ce3d3c2021-02-09 18:18:28 -08004138 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4139 for (final NetworkRequestInfo nri : nris) {
4140 if (mDefaultRequest == nri) {
4141 // Make sure we never remove the default request.
4142 continue;
4143 }
4144 handleRemoveNetworkRequest(nri);
4145 }
4146 }
4147
James Mattisa076c532020-12-02 14:12:41 -08004148 private void cancelNpiRequests(@NonNull final NetworkRequestInfo nri) {
4149 for (final NetworkRequest req : nri.mRequests) {
4150 cancelNpiRequest(req);
4151 }
4152 }
4153
4154 private void cancelNpiRequest(@NonNull final NetworkRequest req) {
4155 if (req.isRequest()) {
4156 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
4157 npi.cancelRequest(req);
4158 }
4159 }
4160 }
4161
4162 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4163 // listens don't have a singular affected Network. Check all networks to see
4164 // if this listen request applies and remove it.
4165 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4166 nai.removeRequest(req.requestId);
4167 if (req.networkCapabilities.hasSignalStrength()
4168 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4169 updateSignalStrengthThresholds(nai, "RELEASE", req);
4170 }
4171 }
4172 }
4173
4174 /**
4175 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4176 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4177 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4178 */
4179 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4180 boolean wasKept = false;
4181 final NetworkAgentInfo nai = nri.getSatisfier();
4182 if (nai != null) {
4183 final int requestLegacyType = nri.getActiveRequest().legacyType;
4184 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4185 nai.removeRequest(nri.getActiveRequest().requestId);
4186 if (VDBG || DDBG) {
4187 log(" Removing from current network " + nai.toShortString()
4188 + ", leaving " + nai.numNetworkRequests() + " requests.");
4189 }
4190 // If there are still lingered requests on this network, don't tear it down,
4191 // but resume lingering instead.
4192 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004193 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004194 notifyNetworkLosing(nai, now);
4195 }
4196 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4197 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4198 teardownUnneededNetwork(nai);
4199 } else {
4200 wasKept = true;
4201 }
4202 nri.setSatisfier(null, null);
4203 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4204 // Went from foreground to background.
4205 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004206 }
4207
Erik Kline0c04b742016-07-07 16:50:58 +09004208 // Maintain the illusion. When this request arrived, we might have pretended
4209 // that a network connected to serve it, even though the network was already
4210 // connected. Now that this request has gone away, we might have to pretend
4211 // that the network disconnected. LegacyTypeTracker will generate that
4212 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004213 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004214 boolean doRemove = true;
4215 if (wasKept) {
4216 // check if any of the remaining requests for this network are for the
4217 // same legacy type - if so, don't remove the nai
4218 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4219 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004220 if (otherRequest.legacyType == requestLegacyType
4221 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004222 if (DBG) log(" still have other legacy request - leaving");
4223 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004224 }
4225 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004226 }
4227
Erik Kline0c04b742016-07-07 16:50:58 +09004228 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004229 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004230 }
4231 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004232 }
4233 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004234
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004235 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4236 return checkAnyPermissionOf(
4237 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4238 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4239 }
4240
Lorenzo Colittid6459092016-07-04 12:55:44 +09004241 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004242 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004243 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004244 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004245 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004246 }
4247
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004248 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004249 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4250 enforceNetworkStackSettingsOrSetup();
4251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4252 encodeBool(accept), encodeBool(always), network));
4253 }
4254
4255 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004256 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004257 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004258 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4259 }
4260
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004261 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4262 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4263 " accept=" + accept + " always=" + always);
4264
4265 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4266 if (nai == null) {
4267 // Nothing to do.
4268 return;
4269 }
4270
4271 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004272 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004273 return;
4274 }
4275
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004276 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004277 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004278 }
4279
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004280 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4281 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004282 // If network becomes partial connectivity and user already accepted to use this
4283 // network, we should respect the user's option and don't need to popup the
4284 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004285 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jeanfbc54672021-01-20 20:47:32 +09004286 nai.updateScoreForNetworkAgentConfigUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004287 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004288 sendUpdatedScoreToFactories(nai);
4289 }
4290
4291 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004292 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004293 }
4294
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004295 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004296 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004297 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004298 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004299 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004300 }
4301
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004302 }
4303
lucaslin2240ef62019-03-12 13:08:03 +08004304 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4305 boolean always) {
4306 if (DBG) {
4307 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4308 + " always=" + always);
4309 }
4310
4311 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4312 if (nai == null) {
4313 // Nothing to do.
4314 return;
4315 }
4316
4317 if (nai.lastValidated) {
4318 // The network validated while the dialog box was up. Take no action.
4319 return;
4320 }
4321
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004322 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4323 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004324 }
4325
4326 // TODO: Use the current design or save the user choice into IpMemoryStore.
4327 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004328 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004329 }
4330
4331 if (!accept) {
4332 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004333 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004334 // Tear down the network.
4335 teardownUnneededNetwork(nai);
4336 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004337 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4338 // result in a partial connectivity result which will be processed by
4339 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004340 //
4341 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4342 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004343 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004344 }
4345 }
4346
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004347 private void handleSetAvoidUnvalidated(Network network) {
4348 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4349 if (nai == null || nai.lastValidated) {
4350 // Nothing to do. The network either disconnected or revalidated.
4351 return;
4352 }
4353 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004354 nai.avoidUnvalidated = true;
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004355 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004356 sendUpdatedScoreToFactories(nai);
4357 }
4358 }
4359
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004360 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004361 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004362 mHandler.sendMessageDelayed(
4363 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4364 PROMPT_UNVALIDATED_DELAY_MS);
4365 }
4366
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004367 @Override
4368 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004369 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004370 mHandler.post(() -> {
4371 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4372 if (nai == null) return;
4373 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004374 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004375 });
4376 }
4377
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004378 /**
4379 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4380 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004381 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004382 * @param appExtras Bundle to use as intent extras for the captive portal application.
4383 * Must be treated as opaque to avoid preventing the captive portal app to
4384 * update its arguments.
4385 */
4386 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004387 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004388 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4389 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004390
4391 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4392 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004393 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4394 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004395 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4396
lucaslin75ff7022020-12-17 04:14:35 +08004397 final long token = Binder.clearCallingIdentity();
4398 try {
4399 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4400 } finally {
4401 Binder.restoreCallingIdentity(token);
4402 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004403 }
4404
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004405 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4406 private final Network mNetwork;
4407
4408 private CaptivePortalImpl(Network network) {
4409 mNetwork = network;
4410 }
4411
4412 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004413 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004414 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4415 enforceSettingsPermission();
4416 }
4417
Chiachang Wang938bfba2020-01-09 13:50:55 +08004418 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004419 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004420 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004421 }
4422
4423 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004424 public void appRequest(final int request) {
4425 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4426 if (nm == null) return;
4427
4428 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004429 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004430 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004431 }
4432 }
4433
4434 @Nullable
4435 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4436 // getNetworkAgentInfoForNetwork is thread-safe
4437 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4438 if (nai == null) return null;
4439
4440 // nai.networkMonitor() is thread-safe
4441 return nai.networkMonitor();
4442 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004443 }
4444
Hugo Benichic9048bc2016-09-14 23:23:08 +00004445 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004446 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004447 }
4448
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004449 /**
4450 * Return whether the device should maintain continuous, working connectivity by switching away
4451 * from WiFi networks having no connectivity.
4452 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4453 */
4454 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004455 if (!checkNetworkStackPermission()) {
4456 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4457 }
4458 return avoidBadWifi();
4459 }
4460
4461
Erik Kline95ecfee2016-10-02 18:02:14 +09004462 private void rematchForAvoidBadWifiUpdate() {
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004463 rematchAllNetworksAndRequests();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004464 for (NetworkAgentInfo nai: mNetworkAgentInfos) {
Erik Kline95ecfee2016-10-02 18:02:14 +09004465 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4466 sendUpdatedScoreToFactories(nai);
4467 }
4468 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004469 }
4470
Erik Kline95ecfee2016-10-02 18:02:14 +09004471 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004472 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004473 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004474 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004475 if (!configRestrict) {
4476 pw.println("Bad Wi-Fi avoidance: unrestricted");
4477 return;
4478 }
4479
4480 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4481 pw.increaseIndent();
4482 pw.println("Config restrict: " + configRestrict);
4483
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004484 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004485 String description;
4486 // Can't use a switch statement because strings are legal case labels, but null is not.
4487 if ("0".equals(value)) {
4488 description = "get stuck";
4489 } else if (value == null) {
4490 description = "prompt";
4491 } else if ("1".equals(value)) {
4492 description = "avoid";
4493 } else {
4494 description = value + " (?)";
4495 }
4496 pw.println("User setting: " + description);
4497 pw.println("Network overrides:");
4498 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004499 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004500 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004501 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004502 }
4503 }
4504 pw.decreaseIndent();
4505 pw.decreaseIndent();
4506 }
4507
paulhu7746e4e2020-06-09 19:07:03 +08004508 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4509 // unify the method.
4510 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4511 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4512 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4513 return settingsComponent != null
4514 ? settingsComponent.getPackageName() : "com.android.settings";
4515 }
4516
lucaslinb1e8e382019-01-24 15:55:30 +08004517 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004518 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004519 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004520 switch (type) {
4521 case NO_INTERNET:
4522 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004523 // High priority because it is only displayed for explicitly selected networks.
4524 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004525 break;
lucasline117e2e2019-10-22 18:27:33 +08004526 case PRIVATE_DNS_BROKEN:
4527 action = Settings.ACTION_WIRELESS_SETTINGS;
4528 // High priority because we should let user know why there is no internet.
4529 highPriority = true;
4530 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004531 case LOST_INTERNET:
4532 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004533 // High priority because it could help the user avoid unexpected data usage.
4534 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004535 break;
lucaslin2240ef62019-03-12 13:08:03 +08004536 case PARTIAL_CONNECTIVITY:
4537 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004538 // Don't bother the user with a high-priority notification if the network was not
4539 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004540 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004541 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004542 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004543 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004544 return;
4545 }
4546
4547 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004548 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004549 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004550 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004551 // Some OEMs have their own Settings package. Thus, need to get the current using
4552 // Settings package name instead of just use default name "com.android.settings".
4553 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4554 intent.setClassName(settingsPkgName,
4555 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004556 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004557
paulhu2af50222020-10-11 22:52:27 +08004558 PendingIntent pendingIntent = PendingIntent.getActivity(
4559 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004560 0 /* requestCode */,
4561 intent,
paulhu2af50222020-10-11 22:52:27 +08004562 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004563
Serik Beketayevec8ad212020-12-07 22:43:07 -08004564 mNotifier.showNotification(
4565 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004566 }
4567
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004568 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4569 // Don't prompt if the network is validated, and don't prompt on captive portals
4570 // because we're already prompting the user to sign in.
4571 if (nai.everValidated || nai.everCaptivePortalDetected) {
4572 return false;
4573 }
4574
4575 // If a network has partial connectivity, always prompt unless the user has already accepted
4576 // partial connectivity and selected don't ask again. This ensures that if the device
4577 // automatically connects to a network that has partial Internet access, the user will
4578 // always be able to use it, either because they've already chosen "don't ask again" or
4579 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004580 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004581 return true;
4582 }
4583
4584 // If a network has no Internet access, only prompt if the network was explicitly selected
4585 // and if the user has not already told us to use the network regardless of whether it
4586 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004587 if (nai.networkAgentConfig.explicitlySelected
4588 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004589 return true;
4590 }
4591
4592 return false;
4593 }
4594
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004595 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004596 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004597 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4598
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004599 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004600 return;
4601 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004602
4603 // Stop automatically reconnecting to this network in the future. Automatically connecting
4604 // to a network that provides no or limited connectivity is not useful, because the user
4605 // cannot use that network except through the notification shown by this method, and the
4606 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004607 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004608
lucaslin2240ef62019-03-12 13:08:03 +08004609 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4610 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4611 // popup the notification immediately when the network is partial connectivity.
4612 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004613 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004614 } else {
4615 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4616 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004617 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004618
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004619 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4620 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004621 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004622
lucaslin2240ef62019-03-12 13:08:03 +08004623 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4624 return;
4625 }
4626
4627 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004628 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004629 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004630 }
4631
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004632 @Override
4633 public int getMultipathPreference(Network network) {
4634 enforceAccessPermission();
4635
4636 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004637 if (nai != null && nai.networkCapabilities
4638 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004639 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4640 }
4641
Aaron Huang9a57acf2020-12-08 10:03:29 +08004642 final NetworkPolicyManager netPolicyManager =
4643 mContext.getSystemService(NetworkPolicyManager.class);
4644
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004645 final long token = Binder.clearCallingIdentity();
4646 final int networkPreference;
4647 try {
4648 networkPreference = netPolicyManager.getMultipathPreference(network);
4649 } finally {
4650 Binder.restoreCallingIdentity(token);
4651 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004652 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004653 return networkPreference;
4654 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004655 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4656 }
4657
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004658 @Override
4659 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004660 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004661 }
4662
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004663 private class InternalHandler extends Handler {
4664 public InternalHandler(Looper looper) {
4665 super(looper);
4666 }
4667
4668 @Override
4669 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004670 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004671 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004672 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004673 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004674 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004675 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004676 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004677 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004678 break;
4679 }
Jason Monka69f1b02013-10-10 14:02:51 -04004680 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004681 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4682 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004683 break;
4684 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004685 case EVENT_REGISTER_NETWORK_PROVIDER: {
4686 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004687 break;
4688 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004689 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4690 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004691 break;
4692 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004693 case EVENT_REGISTER_NETWORK_OFFER: {
4694 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4695 break;
4696 }
4697 case EVENT_UNREGISTER_NETWORK_OFFER: {
4698 final NetworkOfferInfo offer =
4699 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4700 if (null != offer) {
4701 handleUnregisterNetworkOffer(offer);
4702 }
4703 break;
4704 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004705 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004706 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4707 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4708 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004709 break;
4710 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004711 case EVENT_REGISTER_NETWORK_REQUEST:
4712 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09004713 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004714 break;
4715 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004716 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4717 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004718 handleRegisterNetworkRequestWithIntent(msg);
4719 break;
4720 }
Erik Kline155a59a2015-11-25 12:49:38 +09004721 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4722 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4723 handleTimedOutNetworkRequest(nri);
4724 break;
4725 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004726 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4727 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4728 break;
4729 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004730 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08004731 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4732 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004733 break;
4734 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004735 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09004736 Network network = (Network) msg.obj;
4737 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004738 break;
4739 }
lucaslin2240ef62019-03-12 13:08:03 +08004740 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4741 Network network = (Network) msg.obj;
4742 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4743 toBool(msg.arg2));
4744 break;
4745 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004746 case EVENT_SET_AVOID_UNVALIDATED: {
4747 handleSetAvoidUnvalidated((Network) msg.obj);
4748 break;
4749 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004750 case EVENT_PROMPT_UNVALIDATED: {
4751 handlePromptUnvalidated((Network) msg.obj);
4752 break;
4753 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07004754 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4755 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09004756 break;
4757 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004758 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08004759 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004760 mKeepaliveTracker.handleStartKeepalive(msg);
4761 break;
4762 }
4763 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08004764 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004765 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4766 int slot = msg.arg1;
4767 int reason = msg.arg2;
4768 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4769 break;
4770 }
Hugo Benichid6b510a2017-04-06 17:22:18 +09004771 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichif4210292017-04-21 15:07:12 +09004772 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09004773 break;
4774 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004775 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4776 handlePrivateDnsSettingsChanged();
4777 break;
dalyk1720e542018-03-05 12:42:22 -05004778 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4779 handlePrivateDnsValidationUpdate(
4780 (PrivateDnsValidationUpdate) msg.obj);
4781 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00004782 case EVENT_UID_BLOCKED_REASON_CHANGED:
4783 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08004784 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09004785 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4786 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4787 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004788 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09004789 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4790 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004791 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08004792 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004793 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09004794 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4795 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4796 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4797 msg.obj;
4798 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08004799 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09004800 }
lucaslin1193a5d2021-01-21 02:04:15 +08004801 case EVENT_REPORT_NETWORK_ACTIVITY:
4802 mNetworkActivityTracker.handleReportNetworkActivity();
4803 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004804 }
4805 }
4806 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004807
Lorenzo Colittid6459092016-07-04 12:55:44 +09004808 @Override
markchien5776f962019-12-16 20:15:20 +08004809 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004810 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08004811 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4812 Context.TETHERING_SERVICE);
4813 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004814 }
4815
Lorenzo Colittid6459092016-07-04 12:55:44 +09004816 @Override
markchien5776f962019-12-16 20:15:20 +08004817 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004818 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08004819 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4820 Context.TETHERING_SERVICE);
4821 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004822 }
4823
Lorenzo Colittid6459092016-07-04 12:55:44 +09004824 @Override
markchien5776f962019-12-16 20:15:20 +08004825 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004826 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08004827 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4828 Context.TETHERING_SERVICE);
4829 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004830 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004831
markchien5776f962019-12-16 20:15:20 +08004832
Lorenzo Colittid6459092016-07-04 12:55:44 +09004833 @Override
markchien5776f962019-12-16 20:15:20 +08004834 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004835 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08004836 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4837 Context.TETHERING_SERVICE);
4838
4839 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004840 }
4841
Lorenzo Colittid6459092016-07-04 12:55:44 +09004842 @Override
markchien5776f962019-12-16 20:15:20 +08004843 @Deprecated
4844 public String[] getTetherableUsbRegexs() {
4845 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4846 Context.TETHERING_SERVICE);
4847
4848 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07004849 }
4850
Udam Saini8f7d6a72017-06-07 12:06:28 -07004851 @Override
markchien5776f962019-12-16 20:15:20 +08004852 @Deprecated
4853 public String[] getTetherableWifiRegexs() {
4854 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4855 Context.TETHERING_SERVICE);
4856 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08004857 }
4858
Robert Greenwalte0b00512014-07-02 09:59:16 -07004859 // Called when we lose the default network and have no replacement yet.
4860 // This will automatically be cleared after X seconds or a new default network
4861 // becomes CONNECTED, whichever happens first. The timer is started by the
4862 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09004863 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004864 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004865 if (mNetTransitionWakeLock.isHeld()) {
4866 return;
4867 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004868 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004869 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4870 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004871 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004872 mWakelockLogs.log("ACQUIRE for " + forWhom);
4873 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09004874 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09004875 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09004876 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004877 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07004878
Hugo Benichi471b62a2017-03-30 23:18:10 +09004879 // Called when we gain a new default network to release the network transition wakelock in a
4880 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4881 // message is cancelled.
4882 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09004883 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004884 if (!mNetTransitionWakeLock.isHeld()) {
4885 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09004886 }
4887 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004888 // Cancel self timeout on wakelock hold.
4889 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4890 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4891 mHandler.sendMessageDelayed(msg, 1000);
4892 }
4893
4894 // Called when either message of ensureNetworkTransitionWakelock or
4895 // scheduleReleaseNetworkTransitionWakelock is processed.
4896 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4897 String event = eventName(eventId);
4898 synchronized (this) {
4899 if (!mNetTransitionWakeLock.isHeld()) {
4900 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08004901 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09004902 return;
4903 }
4904 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004905 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4906 mTotalWakelockDurationMs += lockDuration;
4907 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4908 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09004909 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004910 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09004911 }
4912
Robert Greenwalt986c7412010-09-08 15:24:47 -07004913 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09004914 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07004915 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07004916 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09004917 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04004918 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07004919 }
4920
Lorenzo Colittid6459092016-07-04 12:55:44 +09004921 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04004922 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04004923 enforceAccessPermission();
4924 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004925 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09004926 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08004927
Cody Kesting3d1df812020-06-25 11:13:39 -07004928 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4929 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4930 // does not match the known connectivity of the network - this causes NetworkMonitor to
4931 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08004932 final NetworkAgentInfo nai;
4933 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004934 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08004935 } else {
4936 nai = getNetworkAgentInfoForNetwork(network);
4937 }
4938 if (nai != null) {
4939 mConnectivityDiagnosticsHandler.sendMessage(
4940 mConnectivityDiagnosticsHandler.obtainMessage(
4941 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4942 connectivityInfo, 0, nai));
4943 }
Cody Kesting3d1df812020-06-25 11:13:39 -07004944
4945 mHandler.sendMessage(
4946 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
Hugo Benichid6b510a2017-04-06 17:22:18 +09004947 }
Paul Jensen83f5d572014-08-29 09:54:01 -04004948
Hugo Benichid6b510a2017-04-06 17:22:18 +09004949 private void handleReportNetworkConnectivity(
4950 Network network, int uid, boolean hasConnectivity) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09004951 final NetworkAgentInfo nai;
Paul Jensenb95d7952015-04-07 12:43:13 -04004952 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004953 nai = getDefaultNetwork();
Paul Jensenb95d7952015-04-07 12:43:13 -04004954 } else {
4955 nai = getNetworkAgentInfoForNetwork(network);
4956 }
Paul Jensen3c3c6e82015-06-25 10:28:34 -04004957 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4958 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4959 return;
4960 }
Paul Jensenb95d7952015-04-07 12:43:13 -04004961 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09004962 if (hasConnectivity == nai.lastValidated) {
4963 return;
4964 }
Paul Jensenb95d7952015-04-07 12:43:13 -04004965 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004966 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09004967 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04004968 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09004969 // Validating a network that has not yet connected could result in a call to
4970 // rematchNetworkAndRequests() which is not meant to work on such networks.
4971 if (!nai.everConnected) {
4972 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04004973 }
paulhu7aeba372020-12-30 00:42:19 +08004974 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
4975 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09004976 return;
4977 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004978 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004979 }
4980
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09004981 // TODO: call into netd.
4982 private boolean queryUserAccess(int uid, Network network) {
4983 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4984 if (nai == null) return false;
4985
4986 // Any UID can use its default network.
4987 if (nai == getDefaultNetworkForUid(uid)) return true;
4988
4989 // Privileged apps can use any network.
4990 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
4991 return true;
4992 }
4993
4994 // An unprivileged UID can use a VPN iff the VPN applies to it.
4995 if (nai.isVPN()) {
4996 return nai.networkCapabilities.appliesToUid(uid);
4997 }
4998
4999 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5000 // sockets, i.e., if it is the owner.
5001 final NetworkAgentInfo vpn = getVpnForUid(uid);
5002 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5003 && uid != vpn.networkCapabilities.getOwnerUid()) {
5004 return false;
5005 }
5006
5007 // The UID's permission must be at least sufficient for the network. Since the restricted
5008 // permission was already checked above, that just leaves background networks.
5009 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5010 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5011 }
5012
5013 // Unrestricted network. Anyone gets to use it.
5014 return true;
5015 }
5016
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005017 /**
5018 * Returns information about the proxy a certain network is using. If given a null network, it
5019 * it will return the proxy for the bound network for the caller app or the default proxy if
5020 * none.
5021 *
5022 * @param network the network we want to get the proxy information for.
5023 * @return Proxy information if a network has a proxy configured, or otherwise null.
5024 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005025 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005026 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005027 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005028 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005029 if (network == null) {
5030 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005031 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005032 true);
5033 if (activeNetwork == null) {
5034 return null;
5035 }
5036 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005037 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005038 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5039 // caller may not have.
5040 return getLinkPropertiesProxyInfo(network);
5041 }
5042 // No proxy info available if the calling UID does not have network access.
5043 return null;
5044 }
5045
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005046
5047 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005048 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5049 if (nai == null) return null;
5050 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005051 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5052 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005053 }
5054 }
5055
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005056 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005057 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005058 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005059 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005060 }
5061
Chalard Jean777e2e52018-06-07 18:02:37 +09005062 @Override
5063 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005064 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005065 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005066 }
5067
Jason Monk4d5e20f2014-04-25 15:00:09 -04005068 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005069 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005070 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005071 proxy = null;
5072 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005073 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005074 }
5075
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005076 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5077 // when any network changes proxy.
5078 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5079 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005080 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005081 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5082 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5083
Chalard Jean7d97afc2018-06-07 17:41:29 +09005084 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005085 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005086 }
5087 }
5088
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005089 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005090 final private HashMap<Uri, Integer> mUriEventMap;
5091 final private Context mContext;
5092 final private Handler mHandler;
5093
5094 SettingsObserver(Context context, Handler handler) {
5095 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005096 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005097 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005098 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005099 }
5100
Erik Kline05f2b402015-04-30 12:58:40 +09005101 void observe(Uri uri, int what) {
5102 mUriEventMap.put(uri, what);
5103 final ContentResolver resolver = mContext.getContentResolver();
5104 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005105 }
5106
5107 @Override
5108 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005109 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005110 }
5111
5112 @Override
5113 public void onChange(boolean selfChange, Uri uri) {
5114 final Integer what = mUriEventMap.get(uri);
5115 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005116 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005117 } else {
5118 loge("No matching event to send for URI=" + uri);
5119 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005120 }
5121 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005122
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005123 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005124 Log.d(TAG, s);
5125 }
5126
5127 private static void logw(String s) {
5128 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005129 }
5130
Daniel Brightf9e945b2020-06-15 16:10:01 -07005131 private static void logwtf(String s) {
5132 Log.wtf(TAG, s);
5133 }
5134
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005135 private static void logwtf(String s, Throwable t) {
5136 Log.wtf(TAG, s, t);
5137 }
5138
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005139 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005140 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005141 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005142
Hugo Benichi39621362017-02-11 17:04:43 +09005143 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005144 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005145 }
5146
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005147 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005148 * Return the information of all ongoing VPNs.
5149 *
5150 * <p>This method is used to update NetworkStatsService.
5151 *
5152 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005153 */
junyulai2050bed2021-01-23 09:46:34 +08005154 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005155 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005156 if (mLockdownEnabled) {
5157 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005158 }
junyulai2050bed2021-01-23 09:46:34 +08005159 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005160 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005161 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005162 if (info != null) {
5163 infoList.add(info);
5164 }
5165 }
junyulai2050bed2021-01-23 09:46:34 +08005166 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005167 }
5168
5169 /**
5170 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005171 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005172 */
junyulai2050bed2021-01-23 09:46:34 +08005173 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005174 if (!nai.isVPN()) return null;
5175
5176 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005177 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5178 // the underlyingNetworks list.
5179 if (underlyingNetworks == null) {
James Mattis2516da32021-01-31 17:06:19 -08005180 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5181 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005182 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005183 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005184 }
5185 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005186
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005187 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005188
5189 List<String> interfaces = new ArrayList<>();
5190 for (Network network : underlyingNetworks) {
5191 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5192 if (underlyingNai == null) continue;
5193 LinkProperties lp = underlyingNai.linkProperties;
5194 for (String iface : lp.getAllInterfaceNames()) {
5195 if (!TextUtils.isEmpty(iface)) {
5196 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005197 }
5198 }
Benedict Wong34857f82019-06-12 17:46:15 +00005199 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005200
5201 if (interfaces.isEmpty()) return null;
5202
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005203 // Must be non-null or NetworkStatsService will crash.
5204 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5205 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005206 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005207 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005208
junyulai2050bed2021-01-23 09:46:34 +08005209 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5210 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005211 }
5212
James Mattisd31bdfa2020-12-23 16:37:26 -08005213 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005214 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5215 Network[] underlyingNetworks) {
5216 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005217 if (underlyingNetworks == null && defaultNetwork != null) {
5218 // null underlying networks means to track the default.
5219 underlyingNetworks = new Network[] { defaultNetwork };
5220 }
5221 return underlyingNetworks;
5222 }
5223
5224 // Returns true iff |network| is an underlying network of |nai|.
5225 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5226 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5227 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5228 if (!nai.supportsUnderlyingNetworks()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005229 final Network[] underlying = underlyingNetworksOrDefault(
5230 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005231 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005232 }
5233
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005234 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005235 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005236 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005237 * When underlying networks change, such networks may have to update capabilities to reflect
5238 * things like the metered bit, their transports, and so on. The capabilities are calculated
5239 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005240 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005241 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005242 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005243 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005244 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005245 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005246 }
5247 }
5248 }
5249
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005250 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5251 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5252 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5253 // a VPN is not up.
5254 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5255 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5256 for (UidRange range : blockedUidRanges) {
5257 if (range.contains(uid)) return true;
5258 }
5259 return false;
5260 }
5261
5262 @Override
5263 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005264 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005265 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5266 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5267 }
5268
5269 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5270 if (DBG) {
5271 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5272 + Arrays.toString(ranges));
5273 }
5274 // Cannot use a Set since the list of UID ranges might contain duplicates.
5275 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5276 for (int i = 0; i < ranges.length; i++) {
5277 if (requireVpn) {
5278 newVpnBlockedUidRanges.add(ranges[i]);
5279 } else {
5280 newVpnBlockedUidRanges.remove(ranges[i]);
5281 }
5282 }
5283
5284 try {
5285 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5286 } catch (RemoteException | ServiceSpecificException e) {
5287 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5288 + Arrays.toString(ranges) + "): netd command failed: " + e);
5289 }
5290
5291 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5292 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005293 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5294 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005295 }
5296
5297 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5298 }
5299
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005300 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005301 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005302 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005303 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005304 }
5305
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005306 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5307 return mLockdownEnabled
5308 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5309 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005310 }
5311
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005312 private NetworkAgentInfo getLegacyLockdownNai() {
5313 if (!mLockdownEnabled) {
5314 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005315 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005316 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005317 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5318 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005319
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005320 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005321 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5322 // a local variable. There is no need to make a copy because its contents cannot change.
5323 final Network[] underlying = nai.declaredUnderlyingNetworks;
5324 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005325 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005326 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005327
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005328 // The legacy lockdown VPN always uses the default network.
5329 // If the VPN's underlying network is no longer the current default network, it means that
5330 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005331 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5332 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005333 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005334 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005335 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005336 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005337
5338 return nai;
5339 };
5340
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005341 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5342 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5343 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005344 private DetailedState getLegacyLockdownState(DetailedState origState) {
5345 if (origState != DetailedState.CONNECTED) {
5346 return origState;
5347 }
5348 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5349 ? DetailedState.CONNECTING
5350 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005351 }
5352
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005353 private void filterForLegacyLockdown(NetworkInfo ni) {
5354 if (!mLockdownEnabled || !ni.isConnected()) return;
5355 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5356 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5357 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5358 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5359 // network, this time with a state of CONNECTED.
5360 //
5361 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5362 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5363 // is not too far off the truth, since an always-on VPN, when not connected, is always
5364 // trying to reconnect.
5365 if (getLegacyLockdownNai() == null) {
5366 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5367 }
5368 }
5369
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005370 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005371 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005372 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005373 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005374 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5375 return;
5376 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005377 final long ident = Binder.clearCallingIdentity();
5378 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005379 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005380 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005381 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005382 } finally {
5383 Binder.restoreCallingIdentity(ident);
5384 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005385 }
Wink Savillecb117d32013-08-29 14:57:08 -07005386
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005387 @Override
5388 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005389 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005390 final long ident = Binder.clearCallingIdentity();
5391 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005392 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005393 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005394 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5395 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005396 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005397 } finally {
5398 Binder.restoreCallingIdentity(ident);
5399 }
5400 }
5401
James Mattis02220e22021-03-13 19:27:21 -08005402 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005403 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005404 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5405 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5406 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005407 }
5408
James Mattis02220e22021-03-13 19:27:21 -08005409 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005410 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005411 // If there was a network preference for this user, remove it.
5412 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5413 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005414 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5415 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5416 }
junyulaid91e7052020-08-28 13:44:33 +08005417 }
5418
James Mattis02220e22021-03-13 19:27:21 -08005419 private void onPackageChanged(@NonNull final String packageName) {
5420 // This is necessary in case a package is added or removed, but also when it's replaced to
5421 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5422 // as one in the preferences, then it should follow the same routing as that other package,
5423 // which means updating the rules is never to be needed in this case (whether it joins or
5424 // leaves a UID with a preference).
5425 if (isMappedInOemNetworkPreference(packageName)) {
5426 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5427 }
5428 }
5429
5430 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005431 @Override
5432 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005433 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005434 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005435 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005436
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005437 // User should be filled for below intents, check the existence.
5438 if (user == null) {
5439 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5440 return;
5441 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005442
Lorenzo Colitticd675292021-02-04 17:32:07 +09005443 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005444 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005445 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005446 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005447 } else {
junyulaid91e7052020-08-28 13:44:33 +08005448 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005449 }
5450 }
5451 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005452
James Mattis02220e22021-03-13 19:27:21 -08005453 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5454 @Override
5455 public void onReceive(Context context, Intent intent) {
5456 ensureRunningOnConnectivityServiceThread();
5457 switch (intent.getAction()) {
5458 case Intent.ACTION_PACKAGE_ADDED:
5459 case Intent.ACTION_PACKAGE_REMOVED:
5460 case Intent.ACTION_PACKAGE_REPLACED:
5461 onPackageChanged(intent.getData().getSchemeSpecificPart());
5462 break;
5463 default:
5464 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5465 }
5466 }
5467 };
5468
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005469 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005470 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005471
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005472 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005473 public final String name;
5474 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005475 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005476 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005477
lifraf3a3492021-03-10 13:58:14 +08005478 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5479 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005480 this.name = name;
5481 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005482 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005483 mDeathRecipient = deathRecipient;
5484
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005485 if (mDeathRecipient == null) {
5486 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005487 }
5488 }
5489
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005490 void sendMessageToNetworkProvider(int what, int arg1, int arg2, Object obj) {
5491 try {
5492 messenger.send(Message.obtain(null /* handler */, what, arg1, arg2, obj));
5493 } catch (RemoteException e) {
5494 // Remote process died. Ignore; the death recipient will remove this
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005495 // NetworkProviderInfo from mNetworkProviderInfos.
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005496 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005497 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005498
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005499 void requestNetwork(NetworkRequest request, int score, int servingProviderId) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005500 sendMessageToNetworkProvider(NetworkProvider.CMD_REQUEST_NETWORK, score,
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005501 servingProviderId, request);
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005502 }
5503
5504 void cancelRequest(NetworkRequest request) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005505 sendMessageToNetworkProvider(NetworkProvider.CMD_CANCEL_REQUEST, 0, 0, request);
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005506 }
5507
5508 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005509 try {
5510 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5511 } catch (RemoteException e) {
5512 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005513 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005514 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005515 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005516
James Mattis4fce5d12020-11-12 15:53:42 -08005517 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5518 for (int i = 0; i < requests.size(); i++) {
5519 ensureNetworkRequestHasType(requests.get(i));
5520 }
5521 }
5522
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005523 private void ensureNetworkRequestHasType(NetworkRequest request) {
5524 if (request.type == NetworkRequest.Type.NONE) {
5525 throw new IllegalArgumentException(
5526 "All NetworkRequests in ConnectivityService must have a type");
5527 }
5528 }
5529
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005530 /**
5531 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005532 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005533 */
James Mattis258ea3c2020-11-15 15:04:40 -08005534 @VisibleForTesting
5535 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005536 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5537 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005538 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005539
James Mattisa076c532020-12-02 14:12:41 -08005540 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5541 void setSatisfier(
5542 @Nullable final NetworkAgentInfo satisfier,
5543 @Nullable final NetworkRequest activeRequest) {
5544 mSatisfier = satisfier;
5545 mActiveRequest = activeRequest;
5546 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005547
James Mattisd31bdfa2020-12-23 16:37:26 -08005548 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005549 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005550 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005551 private NetworkAgentInfo mSatisfier;
5552 NetworkAgentInfo getSatisfier() {
5553 return mSatisfier;
5554 }
5555
5556 // The request in mRequests assigned to a network agent. This is null if none of the
5557 // requests in mRequests can be satisfied. This member has the constraint of only being
5558 // accessible on the handler thread.
5559 @Nullable
5560 private NetworkRequest mActiveRequest;
5561 NetworkRequest getActiveRequest() {
5562 return mActiveRequest;
5563 }
5564
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005565 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005566 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005567 @Nullable
5568 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005569
5570 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005571 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005572 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005573 final int mPid;
5574 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005575 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005576 @Nullable
5577 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005578
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005579 // Counter keeping track of this NRI.
5580 final PerUidCounter mPerUidCounter;
5581
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005582 // Effective UID of this request. This is different from mUid when a privileged process
5583 // files a request on behalf of another UID. This UID is used to determine blocked status,
5584 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5585 // maximum limit of registered callbacks per UID.
5586 final int mAsUid;
5587
James Mattis3ce3d3c2021-02-09 18:18:28 -08005588 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5589 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5590 // maintained for keying off of. This is only a concern when the original nri
5591 // mNetworkRequests changes which happens currently for apps that register callbacks to
5592 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5593 // that match the per-app default nri that currently tracks the calling app's uid so that
5594 // callbacks are fired at the appropriate time. When the callbacks fire,
5595 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5596 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5597 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5598 @NonNull
5599 private final NetworkRequest mNetworkRequestForCallback;
5600 NetworkRequest getNetworkRequestForCallback() {
5601 return mNetworkRequestForCallback;
5602 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005603
James Mattisd31bdfa2020-12-23 16:37:26 -08005604 /**
5605 * Get the list of UIDs this nri applies to.
5606 */
5607 @NonNull
5608 private Set<UidRange> getUids() {
5609 // networkCapabilities.getUids() returns a defensive copy.
5610 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005611 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5612 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005613 }
5614
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005615 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5616 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5617 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005618 }
5619
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005620 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005621 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5622 @Nullable String callingAttributionTag) {
5623 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005624 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005625 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005626 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005627 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005628 mBinder = null;
5629 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005630 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005631 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005632 mPerUidCounter = getRequestCounter(this);
5633 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005634 /**
5635 * Location sensitive data not included in pending intent. Only included in
5636 * {@link NetworkCallback}.
5637 */
5638 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005639 mCallingAttributionTag = callingAttributionTag;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005640 }
5641
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005642 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005643 @Nullable final IBinder binder,
5644 @NetworkCallback.Flag int callbackFlags,
5645 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005646 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5647 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005648 }
5649
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005650 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005651 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005652 @Nullable final IBinder binder,
5653 @NetworkCallback.Flag int callbackFlags,
5654 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005655 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005656 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005657 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005658 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005659 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005660 mBinder = binder;
5661 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005662 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005663 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005664 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005665 mPerUidCounter = getRequestCounter(this);
5666 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005667 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005668 mCallingAttributionTag = callingAttributionTag;
James Mattisb1392002021-03-31 13:57:52 -07005669 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005670 }
5671
James Mattis3ce3d3c2021-02-09 18:18:28 -08005672 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5673 @NonNull final List<NetworkRequest> r) {
5674 super();
5675 ensureAllNetworkRequestsHaveType(r);
5676 mRequests = initializeRequests(r);
5677 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005678 final NetworkAgentInfo satisfier = nri.getSatisfier();
5679 if (null != satisfier) {
5680 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5681 // The active request is necessary to figure out what callbacks to send, in
5682 // particular then a network updates its capabilities.
5683 // As this code creates a new NRI with a new set of requests, figure out which of
5684 // the list of requests should be the active request. It is always the first
5685 // request of the list that can be satisfied by the satisfier since the order of
5686 // requests is a priority order.
5687 // Note even in the presence of a satisfier there may not be an active request,
5688 // when the satisfier is the no-service network.
5689 NetworkRequest activeRequest = null;
5690 for (final NetworkRequest candidate : r) {
5691 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5692 activeRequest = candidate;
5693 break;
5694 }
5695 }
5696 setSatisfier(satisfier, activeRequest);
5697 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005698 mMessenger = nri.mMessenger;
5699 mBinder = nri.mBinder;
5700 mPid = nri.mPid;
5701 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005702 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005703 mPendingIntent = nri.mPendingIntent;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005704 mPerUidCounter = getRequestCounter(this);
5705 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005706 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005707 mCallingAttributionTag = nri.mCallingAttributionTag;
James Mattisb1392002021-03-31 13:57:52 -07005708 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005709 }
5710
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005711 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5712 this(asUid, Collections.singletonList(r));
James Mattis45d81842021-01-10 14:24:24 -08005713 }
5714
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005715 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5716 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
Cody Kesting73708bf2019-12-18 10:57:50 -08005717 }
5718
James Mattis2516da32021-01-31 17:06:19 -08005719 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5720 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5721 // false.
5722 boolean isBeingSatisfied() {
5723 return (null != mSatisfier && null != mActiveRequest);
5724 }
5725
James Mattis3d229892020-11-16 16:46:28 -08005726 boolean isMultilayerRequest() {
5727 return mRequests.size() > 1;
5728 }
5729
James Mattis45d81842021-01-10 14:24:24 -08005730 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5731 // Creating a defensive copy to prevent the sender from modifying the list being
5732 // reflected in the return value of this method.
5733 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08005734 return Collections.unmodifiableList(tempRequests);
5735 }
5736
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005737 void decrementRequestCount() {
5738 mPerUidCounter.decrementCount(mUid);
5739 }
5740
James Mattisb1392002021-03-31 13:57:52 -07005741 void linkDeathRecipient() {
5742 if (null != mBinder) {
5743 try {
5744 mBinder.linkToDeath(this, 0);
5745 } catch (RemoteException e) {
5746 binderDied();
5747 }
5748 }
5749 }
5750
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005751 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07005752 if (null != mBinder) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005753 mBinder.unlinkToDeath(this, 0);
5754 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005755 }
5756
James Mattis4fce5d12020-11-12 15:53:42 -08005757 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005758 public void binderDied() {
5759 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis4fce5d12020-11-12 15:53:42 -08005760 mRequests + ", " + mBinder + ")");
James Mattisa152f882020-11-20 16:08:10 -08005761 releaseNetworkRequests(mRequests);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005762 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005763
James Mattis4fce5d12020-11-12 15:53:42 -08005764 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005765 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005766 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5767 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08005768 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005769 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005770 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08005771 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08005772 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
Roshan Piuse1220262021-03-11 21:16:44 -08005773 + " callback flags: " + mCallbackFlags;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005774 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005775 }
5776
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09005777 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5778 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5779 if (badCapability != null) {
5780 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04005781 }
5782 }
5783
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005784 // This checks that the passed capabilities either do not request a
5785 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005786 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08005787 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09005788 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005789 throw new SecurityException("Insufficient permissions to request a specific SSID");
5790 }
paulhu1a407652019-03-22 16:35:06 +08005791
5792 if (nc.hasSignalStrength()
5793 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5794 throw new SecurityException(
5795 "Insufficient permissions to request a specific signal strength");
5796 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08005797 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07005798
junyulai2217bec2021-04-14 23:33:31 +08005799 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07005800 enforceNetworkFactoryPermission();
5801 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005802 }
5803
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005804 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005805 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005806 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08005807 // mNetworkRequests may contain the same value multiple times in case of
5808 // multilayer requests. It won't matter in this case because the thresholds
5809 // will then be the same and be deduplicated as they enter the `thresholds` set.
5810 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08005811 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5812 for (final NetworkRequest req : nri.mRequests) {
5813 if (req.networkCapabilities.hasSignalStrength()
5814 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5815 thresholds.add(req.networkCapabilities.getSignalStrength());
5816 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005817 }
5818 }
5819 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005820 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005821 }
5822
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005823 private void updateSignalStrengthThresholds(
5824 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005825 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005826
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09005827 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005828 String detail;
5829 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5830 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5831 } else {
5832 detail = reason;
5833 }
5834 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005835 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005836 }
5837
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005838 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005839 }
5840
Etan Cohen1b6d4182017-04-03 17:42:34 -07005841 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5842 if (nc == null) {
5843 return;
5844 }
5845 NetworkSpecifier ns = nc.getNetworkSpecifier();
5846 if (ns == null) {
5847 return;
5848 }
lucaslin22f9b9f2021-01-22 15:15:23 +08005849 if (ns instanceof MatchAllNetworkSpecifier) {
5850 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5851 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07005852 }
5853
lucasline117e2e2019-10-22 18:27:33 +08005854 private void ensureValid(NetworkCapabilities nc) {
5855 ensureValidNetworkSpecifier(nc);
5856 if (nc.isPrivateDnsBroken()) {
5857 throw new IllegalArgumentException("Can't request broken private DNS");
5858 }
5859 }
5860
Roshan Pius951c0032020-12-22 15:10:42 -08005861 private boolean isTargetSdkAtleast(int version, int callingUid,
5862 @NonNull String callingPackageName) {
5863 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08005864 final PackageManager pm =
5865 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08005866 try {
Roshan Pius951c0032020-12-22 15:10:42 -08005867 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08005868 if (callingVersion < version) return false;
5869 } catch (PackageManager.NameNotFoundException e) { }
5870 return true;
5871 }
5872
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005873 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005874 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
junyulaiad010792021-01-11 16:53:38 +08005875 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08005876 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08005877 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08005878 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08005879 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5880 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08005881 throw new SecurityException("Insufficient permissions to specify legacy type");
5882 }
markchienfac84a22020-03-18 21:16:15 +08005883 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005884 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005885 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005886 // Privileged callers can track the default network of another UID by passing in a UID.
5887 if (asUid != Process.INVALID_UID) {
5888 enforceSettingsPermission();
5889 } else {
5890 asUid = callingUid;
5891 }
junyulaiad010792021-01-11 16:53:38 +08005892 final NetworkRequest.Type reqType;
5893 try {
5894 reqType = NetworkRequest.Type.values()[reqTypeInt];
5895 } catch (ArrayIndexOutOfBoundsException e) {
5896 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5897 }
5898 switch (reqType) {
5899 case TRACK_DEFAULT:
5900 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005901 // is unused and will be replaced by ones appropriate for the UID (usually, the
5902 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08005903 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005904 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08005905 enforceAccessPermission();
5906 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005907 case TRACK_SYSTEM_DEFAULT:
5908 enforceSettingsPermission();
5909 networkCapabilities = new NetworkCapabilities(defaultNc);
5910 break;
Junyu Laia62493f2021-01-19 11:10:56 +00005911 case BACKGROUND_REQUEST:
5912 enforceNetworkStackOrSettingsPermission();
5913 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08005914 case REQUEST:
5915 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5916 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5917 callingAttributionTag);
5918 // TODO: this is incorrect. We mark the request as metered or not depending on
5919 // the state of the app when the request is filed, but we never change the
5920 // request if the app changes network state. http://b/29964605
5921 enforceMeteredApnPolicy(networkCapabilities);
5922 break;
junyulai1b1c8742021-03-12 20:05:08 +08005923 case LISTEN_FOR_BEST:
5924 enforceAccessPermission();
5925 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5926 break;
junyulaiad010792021-01-11 16:53:38 +08005927 default:
5928 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09005929 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09005930 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005931 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08005932 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005933
junyulai1b1c8742021-03-12 20:05:08 +08005934 // Enforce FOREGROUND if the caller does not have permission to use background network.
5935 if (reqType == LISTEN_FOR_BEST) {
5936 restrictBackgroundRequestForCaller(networkCapabilities);
5937 }
5938
5939 // Set the UID range for this request to the single UID of the requester, unless the
5940 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09005941 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5942 // are no visible methods to set the UIDs, an app could use reflection to try and get
5943 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08005944 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08005945 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5946 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005947
Etan Cohen85000162017-02-05 10:42:27 -08005948 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005949 throw new IllegalArgumentException("Bad timeout specified");
5950 }
lucasline117e2e2019-10-22 18:27:33 +08005951 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08005952
James Mattis3ce3d3c2021-02-09 18:18:28 -08005953 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08005954 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005955 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005956 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005957 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09005958 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005959
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005960 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5961 // copied from the default request above. (This is necessary to ensure, for example, that
5962 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5963 // changes don't alter request matching.
5964 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5965 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09005966 throw new IllegalStateException(
5967 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005968 + networkCapabilities + " vs. " + defaultNc);
5969 }
5970
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005971 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07005972 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005973 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07005974 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005975 }
5976 return networkRequest;
5977 }
5978
James Mattis3ce3d3c2021-02-09 18:18:28 -08005979 /**
5980 * Return the nri to be used when registering a network request. Specifically, this is used with
5981 * requests registered to track the default request. If there is currently a per-app default
5982 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5983 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005984 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5985 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08005986 * @param nr the network request for the nri.
5987 * @param msgr the messenger for the nri.
5988 * @param binder the binder for the nri.
5989 * @param callingAttributionTag the calling attribution tag for the nri.
5990 * @return the nri to register.
5991 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005992 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005993 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08005994 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005995 @Nullable String callingAttributionTag) {
5996 final List<NetworkRequest> requests;
5997 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
5998 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005999 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006000 } else {
6001 requests = Collections.singletonList(nr);
6002 }
Roshan Pius951c0032020-12-22 15:10:42 -08006003 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006004 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006005 }
6006
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006007 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6008 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006009 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006010 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006011 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006012 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006013 }
6014 }
6015
fenglu3f357402015-03-20 11:29:56 -07006016 @Override
fenglub00f4882015-04-21 17:12:05 -07006017 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006018 enforceAccessPermission();
6019 NetworkAgentInfo nai = null;
6020 if (network == null) {
6021 return false;
6022 }
6023 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006024 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006025 }
6026 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006027 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006028 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006029 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006030 Integer uidReqs = mBandwidthRequests.get(uid);
6031 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006032 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006033 }
6034 mBandwidthRequests.put(uid, ++uidReqs);
6035 }
fenglu3f357402015-03-20 11:29:56 -07006036 return true;
6037 }
6038 return false;
6039 }
6040
Felipe Leme0a5ae422016-06-20 16:36:29 -07006041 private boolean isSystem(int uid) {
6042 return uid < Process.FIRST_APPLICATION_UID;
6043 }
fenglu3f357402015-03-20 11:29:56 -07006044
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006045 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006046 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006047 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006048 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006049 return;
6050 }
Hugo Benichi39621362017-02-11 17:04:43 +09006051 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6052 // Policy already enforced.
6053 return;
6054 }
paulhuaf50d7d2020-12-24 19:47:34 +08006055 final long ident = Binder.clearCallingIdentity();
6056 try {
6057 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6058 // If UID is restricted, don't allow them to bring up metered APNs.
6059 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6060 }
6061 } finally {
6062 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006063 }
6064 }
6065
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006066 @Override
6067 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006068 PendingIntent operation, @NonNull String callingPackageName,
6069 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006070 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006071 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006072 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006073 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6074 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006075 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006076 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006077 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006078 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006079 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006080 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6081 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006082
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006083 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006084 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006085 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6086 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006087 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006088 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6089 nri));
6090 return networkRequest;
6091 }
6092
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006093 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6094 mHandler.sendMessageDelayed(
6095 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006096 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006097 }
6098
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006099 @Override
6100 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006101 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006102 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006103 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006104 }
6105
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006106 // In order to implement the compatibility measure for pre-M apps that call
6107 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6108 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6109 // This ensures it has permission to do so.
6110 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6111 if (nc == null) {
6112 return false;
6113 }
6114 int[] transportTypes = nc.getTransportTypes();
6115 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6116 return false;
6117 }
6118 try {
6119 mContext.enforceCallingOrSelfPermission(
6120 android.Manifest.permission.ACCESS_WIFI_STATE,
6121 "ConnectivityService");
6122 } catch (SecurityException e) {
6123 return false;
6124 }
6125 return true;
6126 }
6127
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006128 @Override
6129 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006130 Messenger messenger, IBinder binder,
6131 @NetworkCallback.Flag int callbackFlags,
6132 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006133 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006134 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6135 enforceAccessPermission();
6136 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006137
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006138 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006139 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006140 Binder.getCallingPid(), callingUid, callingPackageName);
6141 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006142 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6143 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6144 // onLost and onAvailable callbacks when networks move in and out of the background.
6145 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6146 // can't request networks.
6147 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006148 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006149
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006150 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006151 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006152 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006153 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006154 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006155 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006156
6157 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6158 return networkRequest;
6159 }
6160
6161 @Override
6162 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006163 PendingIntent operation, @NonNull String callingPackageName,
6164 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006165 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006166 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006167 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6168 enforceAccessPermission();
6169 }
lucasline117e2e2019-10-22 18:27:33 +08006170 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006171 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006172 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006173 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006174 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006175
6176 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006177 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006178 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6179 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006180 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006181
6182 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006183 }
6184
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006185 /** Returns the next Network provider ID. */
6186 public final int nextNetworkProviderId() {
6187 return mNextNetworkProviderId.getAndIncrement();
6188 }
6189
James Mattisa152f882020-11-20 16:08:10 -08006190 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
James Mattis4fce5d12020-11-12 15:53:42 -08006191 for (int i = 0; i < networkRequests.size(); i++) {
6192 releaseNetworkRequest(networkRequests.get(i));
6193 }
6194 }
6195
Erik Kline0c04b742016-07-07 16:50:58 +09006196 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006197 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006198 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006199 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006200 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006201 }
6202
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006203 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6204 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006205 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6206 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6207 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006208 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006209 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006210 return;
6211 }
6212
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006213 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6214 mNetworkProviderInfos.put(npi.messenger, npi);
6215 npi.connect(mContext, mTrackerHandler);
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006216 sendAllRequestsToProvider(npi);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006217 }
6218
6219 @Override
6220 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006221 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006222 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006223 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006224 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006225 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6226 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006227 }
6228
6229 @Override
6230 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006231 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006233 }
6234
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006235 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006236 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006237 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6238 @NonNull final INetworkOfferCallback callback) {
6239 final NetworkOffer offer = new NetworkOffer(
Chalard Jean30689b82021-03-22 22:44:02 +09006240 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006241 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6242 }
6243
6244 @Override
6245 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6246 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6247 }
6248
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006249 private void handleUnregisterNetworkProvider(Messenger messenger) {
6250 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6251 if (npi == null) {
6252 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006253 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006254 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006255 // Unregister all the offers from this provider
6256 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6257 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006258 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006259 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6260 toRemove.add(noi);
6261 }
6262 }
6263 for (NetworkOfferInfo noi : toRemove) {
6264 handleUnregisterNetworkOffer(noi);
6265 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006266 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006267 }
6268
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006269 @Override
James Mattisf7027322020-12-13 16:28:14 -08006270 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006271 if (request.hasTransport(TRANSPORT_TEST)) {
6272 enforceNetworkFactoryOrTestNetworksPermission();
6273 } else {
6274 enforceNetworkFactoryPermission();
6275 }
James Mattisf7027322020-12-13 16:28:14 -08006276 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6277 if (nri != null) {
6278 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6279 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6280 mHandler.post(() -> handleReleaseNetworkRequest(
6281 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6282 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006283 }
6284
Paul Jensen1f567382015-02-13 14:18:39 -05006285 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6286 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006287 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006288 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006289 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006290 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006291 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006292
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006293 // NetworkAgentInfo keyed off its connecting messenger
6294 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen1f567382015-02-13 14:18:39 -05006295 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006296 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006297
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006298 // UID ranges for users that are currently blocked by VPNs.
6299 // This array is accessed and iterated on multiple threads without holding locks, so its
6300 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6301 // (on the handler thread).
6302 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6303
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006304 // Must only be accessed on the handler thread
6305 @NonNull
6306 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6307
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006308 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006309 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006310
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006311 // Current OEM network preferences. This object must only be written to on the handler thread.
6312 // Since it is immutable and always non-null, other threads may read it if they only care
6313 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006314 @NonNull
6315 private OemNetworkPreferences mOemNetworkPreferences =
6316 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006317 // Current per-profile network preferences. This object follows the same threading rules as
6318 // the OEM network preferences above.
6319 @NonNull
6320 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
James Mattis45d81842021-01-10 14:24:24 -08006321
James Mattiscb1e0362021-04-06 17:07:42 -07006322 // OemNetworkPreferences activity String log entries.
6323 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6324 @NonNull
6325 private final LocalLog mOemNetworkPreferencesLogs =
6326 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6327
James Mattis02220e22021-03-13 19:27:21 -08006328 /**
6329 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6330 * @param packageName the package name to check existence of a mapping for.
6331 * @return true if a mapping exists, false otherwise
6332 */
6333 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6334 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6335 }
6336
James Mattise3ef1912020-12-20 11:09:58 -08006337 // The always-on request for an Internet-capable network that apps without a specific default
6338 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006339 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006340 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006341 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006342 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006343 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006344 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006345 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006346
James Mattisd31bdfa2020-12-23 16:37:26 -08006347 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6348 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6349 }
6350
6351 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006352 * Return the default network request currently tracking the given uid.
6353 * @param uid the uid to check.
6354 * @return the NetworkRequestInfo tracking the given uid.
6355 */
6356 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006357 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006358 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6359 if (nri == mDefaultRequest) {
6360 continue;
6361 }
6362 // Checking the first request is sufficient as only multilayer requests will have more
6363 // than one request and for multilayer, all requests will track the same uids.
6364 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6365 return nri;
6366 }
6367 }
6368 return mDefaultRequest;
6369 }
6370
6371 /**
6372 * Get a copy of the network requests of the default request that is currently tracking the
6373 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006374 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6375 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006376 * @param requestorUid the uid to check the default for.
6377 * @param requestorPackageName the requestor's package name.
6378 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6379 */
6380 @NonNull
6381 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006382 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006383 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006384 getDefaultRequestTrackingUid(asUid).mRequests,
6385 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006386 }
6387
6388 /**
6389 * Copy the given nri's NetworkRequest collection.
6390 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006391 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6392 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006393 * @param requestorUid the uid to set on the copied collection.
6394 * @param requestorPackageName the package name to set on the copied collection.
6395 * @return the copied NetworkRequest collection.
6396 */
6397 @NonNull
6398 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006399 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6400 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006401 final List<NetworkRequest> requests = new ArrayList<>();
6402 for (final NetworkRequest nr : requestsToCopy) {
6403 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006404 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006405 nr.legacyType, nextNetworkRequestId(), nr.type));
6406 }
6407 return requests;
6408 }
6409
6410 @NonNull
6411 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006412 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6413 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006414 // These capabilities are for a TRACK_DEFAULT callback, so:
6415 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6416 // mDefaultRequest and a per-UID default request.
6417 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006418 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006419 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006420 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6421 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006422 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006423 restrictRequestUidsForCallerAndSetRequestorInfo(
6424 netCap, requestorUid, requestorPackageName);
6425 return netCap;
6426 }
6427
6428 /**
6429 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6430 * @param nr the network request to check for equality against.
6431 * @return the nri if one exists, null otherwise.
6432 */
6433 @Nullable
6434 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6435 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6436 if (nri.getNetworkRequestForCallback().equals(nr)) {
6437 return nri;
6438 }
6439 }
6440 return null;
6441 }
6442
6443 /**
6444 * Check if an nri is currently being managed by per-app default networking.
6445 * @param nri the nri to check.
6446 * @return true if this nri is currently being managed by per-app default networking.
6447 */
6448 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6449 // nri.mRequests.get(0) is only different from the original request filed in
6450 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6451 // functionality therefore if these two don't match, it means this particular nri is
6452 // currently being managed by a per-app default.
6453 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6454 }
6455
6456 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006457 * Determine if an nri is a managed default request that disallows default networking.
6458 * @param nri the request to evaluate
6459 * @return true if device-default networking is disallowed
6460 */
6461 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6462 // Check if this nri is a managed default that supports the default network at its
6463 // lowest priority request.
6464 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6465 final NetworkCapabilities lowestPriorityNetCap =
6466 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6467 return isPerAppDefaultRequest(nri)
6468 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6469 lowestPriorityNetCap));
6470 }
6471
Erik Kline05f2b402015-04-30 12:58:40 +09006472 // Request used to optionally keep mobile data active even when higher
6473 // priority networks like Wi-Fi are active.
6474 private final NetworkRequest mDefaultMobileDataRequest;
6475
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006476 // Request used to optionally keep wifi data active even when higher
6477 // priority networks like ethernet are active.
6478 private final NetworkRequest mDefaultWifiRequest;
6479
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006480 // Request used to optionally keep vehicle internal network always active
6481 private final NetworkRequest mDefaultVehicleRequest;
6482
James Mattisd31bdfa2020-12-23 16:37:26 -08006483 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6484 // network with no service. This NAI should never be matched against, nor should any public API
6485 // ever return the associated network. For this reason, this NAI is not in the list of available
6486 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6487 // default requests that don't support using the device default network which will ultimately
6488 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6489 @VisibleForTesting
6490 final NetworkAgentInfo mNoServiceNetwork;
6491
Chalard Jean5b409c72021-02-04 13:12:59 +09006492 // The NetworkAgentInfo currently satisfying the default request, if any.
6493 private NetworkAgentInfo getDefaultNetwork() {
6494 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006495 }
6496
James Mattis2516da32021-01-31 17:06:19 -08006497 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6498 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6499 // Currently, all network requests will have the same uids therefore checking the first
6500 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006501 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006502 if (null == uids) {
6503 continue;
6504 }
6505 for (final UidRange range : uids) {
6506 if (range.contains(uid)) {
6507 return nri.getSatisfier();
6508 }
6509 }
6510 }
6511 return getDefaultNetwork();
6512 }
6513
Varun Ananddf569952019-02-06 10:13:38 -08006514 @Nullable
6515 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6516 return nai != null ? nai.network : null;
6517 }
6518
6519 private void ensureRunningOnConnectivityServiceThread() {
6520 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6521 throw new IllegalStateException(
6522 "Not running on ConnectivityService thread: "
6523 + Thread.currentThread().getName());
6524 }
6525 }
6526
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006527 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006528 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6529 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006530 }
6531
Chalard Jean29d06db2018-05-02 21:14:54 +09006532 /**
6533 * Register a new agent with ConnectivityService to handle a network.
6534 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006535 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006536 * @param networkInfo the initial info associated with this network. It can be updated later :
6537 * see {@link #updateNetworkInfo}.
6538 * @param linkProperties the initial link properties of this network. They can be updated
6539 * later : see {@link #updateLinkProperties}.
6540 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006541 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006542 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006543 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006544 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006545 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006546 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006547 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006548 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006549 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006550 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6551 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006552 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6553 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6554 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006555 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006556 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006557 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6558 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006559 } else {
6560 enforceNetworkFactoryPermission();
6561 }
6562
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006563 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006564 final long token = Binder.clearCallingIdentity();
6565 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006566 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006567 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006568 } finally {
6569 Binder.restoreCallingIdentity(token);
6570 }
6571 }
6572
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006573 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006574 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006575 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6576 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006577 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006578 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6579 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6580 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6581 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006582 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006583 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006584
Rubin Xuffd77d82017-09-05 18:40:49 +01006585 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006586
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006587 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006588 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006589 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006590 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09006591 this, mNetd, mDnsResolver, providerId, uid, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006592
6593 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006594 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006595 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006596 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6597
Chalard Jeanf2da1772018-04-26 16:16:10 +09006598 final String extraInfo = networkInfo.getExtraInfo();
6599 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006600 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006601 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006602 mDeps.getNetworkStack().makeNetworkMonitor(
6603 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006604 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6605 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006606 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006607 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006608 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006609 }
6610
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006611 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6612 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006613 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006614 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006615 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006616 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006617 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006618
6619 try {
6620 networkMonitor.start();
6621 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006622 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006623 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006624 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006625 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006626 updateNetworkInfo(nai, networkInfo);
6627 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006628 }
6629
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006630 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6631 @NonNull public final NetworkOffer offer;
6632
6633 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6634 this.offer = offer;
6635 }
6636
6637 @Override
6638 public void binderDied() {
6639 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6640 }
6641 }
6642
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006643 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6644 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6645 if (npi.providerId == providerId) return true;
6646 }
6647 return false;
6648 }
6649
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006650 /**
6651 * Register or update a network offer.
6652 * @param newOffer The new offer. If the callback member is the same as an existing
6653 * offer, it is an update of that offer.
6654 */
6655 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6656 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006657 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006658 // This may actually happen if a provider updates its score or registers and then
6659 // immediately unregisters. The offer would still be in the handler queue, but the
6660 // provider would have been removed.
6661 if (DBG) log("Received offer from an unregistered provider");
6662 return;
6663 }
6664
6665 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6666 if (null != existingOffer) {
6667 handleUnregisterNetworkOffer(existingOffer);
6668 newOffer.migrateFrom(existingOffer.offer);
6669 }
6670 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6671 try {
Chalard Jean30689b82021-03-22 22:44:02 +09006672 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006673 } catch (RemoteException e) {
6674 noi.binderDied();
6675 return;
6676 }
6677 mNetworkOffers.add(noi);
6678 // TODO : send requests to the provider.
6679 }
6680
6681 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6682 ensureRunningOnConnectivityServiceThread();
6683 mNetworkOffers.remove(noi);
Chalard Jean30689b82021-03-22 22:44:02 +09006684 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006685 }
6686
6687 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6688 @NonNull final INetworkOfferCallback callback) {
6689 ensureRunningOnConnectivityServiceThread();
6690 for (final NetworkOfferInfo noi : mNetworkOffers) {
6691 if (noi.offer.callback.equals(callback)) return noi;
6692 }
6693 return null;
6694 }
6695
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006696 /**
6697 * Called when receiving LinkProperties directly from a NetworkAgent.
6698 * Stores into |nai| any data coming from the agent that might also be written to the network's
6699 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6700 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09006701 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006702 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006703 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6704 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09006705 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08006706 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006707 }
6708
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006709 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006710 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006711 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006712
Lorenzo Colittid523d142020-04-01 20:16:30 +09006713 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6714 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6715 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09006716 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09006717
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006718 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00006719
6720 // update filtering rules, need to happen after the interface update so netd knows about the
6721 // new interface (the interface name -> index map becomes initialized)
6722 updateVpnFiltering(newLp, oldLp, networkAgent);
6723
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006724 updateMtu(newLp, oldLp);
6725 // TODO - figure out what to do for clat
6726// for (LinkProperties lp : newLp.getStackedLinks()) {
6727// updateMtu(lp, null);
6728// }
Chalard Jean5b409c72021-02-04 13:12:59 +09006729 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08006730 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6731 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09006732
Erik Klineb9888902016-04-05 13:30:49 +09006733 updateRoutes(newLp, oldLp, netId);
6734 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05006735 // Make sure LinkProperties represents the latest private DNS status.
6736 // This does not need to be done before updateDnses because the
6737 // LinkProperties are not the source of the private DNS configuration.
6738 // updateDnses will fetch the private DNS configuration from DnsManager.
6739 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09006740
Chalard Jean5b409c72021-02-04 13:12:59 +09006741 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05006742 handleApplyDefaultProxy(newLp.getHttpProxy());
6743 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006744 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05006745 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02006746
6747 updateWakeOnLan(newLp);
6748
Hai Shalome58bdc62021-01-11 18:45:34 -08006749 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6750 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6751 // does, it needs to be merged here.
6752 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6753 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09006754
Robert Greenwalte525a0a2014-09-30 16:50:07 -07006755 // TODO - move this check to cover the whole function
6756 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09006757 synchronized (networkAgent) {
6758 networkAgent.linkProperties = newLp;
6759 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09006760 // Start or stop DNS64 detection and 464xlat according to network state.
6761 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08006762 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09006763 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6764 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08006765 if (networkAgent.everConnected) {
6766 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6767 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07006768 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006769
6770 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04006771 }
6772
Hai Shalome58bdc62021-01-11 18:45:34 -08006773 /**
6774 * @param naData captive portal data from NetworkAgent
6775 * @param apiData captive portal data from capport API
6776 */
6777 @Nullable
6778 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6779 CaptivePortalData apiData) {
6780 if (naData == null || apiData == null) {
6781 return naData == null ? apiData : naData;
6782 }
6783 final CaptivePortalData.Builder captivePortalBuilder =
6784 new CaptivePortalData.Builder(naData);
6785
6786 if (apiData.isCaptive()) {
6787 captivePortalBuilder.setCaptive(true);
6788 }
6789 if (apiData.isSessionExtendable()) {
6790 captivePortalBuilder.setSessionExtendable(true);
6791 }
6792 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6793 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6794 // otherwise data would be inconsistent. Prefer the capport API info if present,
6795 // as it can generally be refreshed more often.
6796 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6797 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6798 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6799 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6800 // No source has time / bytes remaining information: surface the newest refresh time
6801 // for other fields
6802 captivePortalBuilder.setRefreshTime(
6803 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6804 }
6805
Hai Shalom7c6ab402021-02-04 19:34:06 -08006806 // Prioritize the user portal URL from the network agent if the source is authenticated.
6807 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6808 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6809 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6810 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08006811 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08006812 // Prioritize the venue information URL from the network agent if the source is
6813 // authenticated.
6814 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6815 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6816 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6817 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08006818 }
6819 return captivePortalBuilder.build();
6820 }
6821
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006822 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09006823 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09006824 // marks on unsupported interfaces is harmless.
6825 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6826 return;
6827 }
Joel Scherpelza235a812017-05-22 13:47:41 +09006828
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006829 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6830 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6831
6832 // TODO (b/183076074): remove legacy fallback after migrating overlays
6833 final int legacyMark = mContext.getResources().getInteger(mContext.getResources()
6834 .getIdentifier("config_networkWakeupPacketMark", "integer", "android"));
6835 final int legacyMask = mContext.getResources().getInteger(mContext.getResources()
6836 .getIdentifier("config_networkWakeupPacketMask", "integer", "android"));
6837 mark = mark == 0 ? legacyMark : mark;
6838 mask = mask == 0 ? legacyMask : mask;
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006839
6840 // Mask/mark of zero will not detect anything interesting.
6841 // Don't install rules unless both values are nonzero.
6842 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09006843 return;
6844 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006845
6846 final String prefix = "iface:" + iface;
6847 try {
6848 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08006849 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006850 } else {
Luke Huang46289a22018-09-27 19:33:11 +08006851 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006852 }
6853 } catch (Exception e) {
6854 loge("Exception modifying wakeup packet monitoring: " + e);
6855 }
6856
Joel Scherpelza235a812017-05-22 13:47:41 +09006857 }
6858
Chalard Jean9589e722019-11-19 19:03:53 +09006859 private void updateInterfaces(final @Nullable LinkProperties newLp,
6860 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006861 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09006862 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01006863 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6864 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09006865 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09006866 for (final String iface : interfaceDiff.added) {
6867 try {
6868 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08006869 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09006870 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08006871 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6872 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09006873 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08006874 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09006875 }
Paul Jensenbff73492014-04-28 10:33:11 -04006876 }
6877 }
Chalard Jean9589e722019-11-19 19:03:53 +09006878 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04006879 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006880 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006881 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08006882 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04006883 } catch (Exception e) {
6884 loge("Exception removing interface: " + e);
6885 }
6886 }
6887 }
6888
Tyler Weare4314862019-12-05 14:55:30 -08006889 // TODO: move to frameworks/libs/net.
6890 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6891 final String nextHop;
6892
6893 switch (route.getType()) {
6894 case RouteInfo.RTN_UNICAST:
6895 if (route.hasGateway()) {
6896 nextHop = route.getGateway().getHostAddress();
6897 } else {
6898 nextHop = INetd.NEXTHOP_NONE;
6899 }
6900 break;
6901 case RouteInfo.RTN_UNREACHABLE:
6902 nextHop = INetd.NEXTHOP_UNREACHABLE;
6903 break;
6904 case RouteInfo.RTN_THROW:
6905 nextHop = INetd.NEXTHOP_THROW;
6906 break;
6907 default:
6908 nextHop = INetd.NEXTHOP_NONE;
6909 break;
6910 }
6911
6912 final RouteInfoParcel rip = new RouteInfoParcel();
6913 rip.ifName = route.getInterface();
6914 rip.destination = route.getDestination().toString();
6915 rip.nextHop = nextHop;
6916 rip.mtu = route.getMtu();
6917
6918 return rip;
6919 }
6920
Paul Jensene0fd4a82014-08-06 15:51:33 -04006921 /**
6922 * Have netd update routes from oldLp to newLp.
6923 * @return true if routes changed between oldLp and newLp
6924 */
6925 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08006926 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08006927 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
6928 new CompareOrUpdateResult<>(
6929 oldLp != null ? oldLp.getAllRoutes() : null,
6930 newLp != null ? newLp.getAllRoutes() : null,
6931 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006932
6933 // add routes before removing old in case it helps with continuous connectivity
6934
Chalard Jean9dd11612018-06-04 16:52:49 +09006935 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006936 for (RouteInfo route : routeDiff.added) {
6937 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09006938 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006939 try {
Tyler Weare4314862019-12-05 14:55:30 -08006940 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006941 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006942 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08006943 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006944 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006945 }
6946 }
6947 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006948 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09006949 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006950 try {
Tyler Weare4314862019-12-05 14:55:30 -08006951 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006952 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006953 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08006954 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006955 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006956 }
6957 }
6958
6959 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09006960 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006961 try {
Tyler Weare4314862019-12-05 14:55:30 -08006962 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006963 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08006964 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006965 }
6966 }
Tyler Weare4314862019-12-05 14:55:30 -08006967
6968 for (RouteInfo route : routeDiff.updated) {
6969 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
6970 try {
6971 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
6972 } catch (Exception e) {
6973 loge("Exception in networkUpdateRouteParcel: " + e);
6974 }
6975 }
6976 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
6977 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006978 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09006979
Erik Klineb9888902016-04-05 13:30:49 +09006980 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
6981 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
6982 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006983 }
Erik Klineb9888902016-04-05 13:30:49 +09006984
Erik Kline31b4a9e2018-01-11 21:07:29 +09006985 if (DBG) {
6986 final Collection<InetAddress> dnses = newLp.getDnsServers();
6987 log("Setting DNS servers for network " + netId + " to " + dnses);
6988 }
Erik Klineb9888902016-04-05 13:30:49 +09006989 try {
chenbruce7b2f8982020-02-20 14:28:31 +08006990 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08006991 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09006992 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09006993 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09006994 }
Erik Kline54e35c02017-04-07 15:29:29 +09006995 }
6996
Lorenzo Colittibad9d912019-04-12 10:48:06 +00006997 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
6998 NetworkAgentInfo nai) {
6999 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7000 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7001 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7002 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7003
7004 if (!wasFiltering && !needsFiltering) {
7005 // Nothing to do.
7006 return;
7007 }
7008
7009 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7010 // Nothing changed.
7011 return;
7012 }
7013
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007014 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007015 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007016 // TODO: this create a window of opportunity for apps to receive traffic between the time
7017 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007018 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007019 // old rules are being removed.
7020 if (wasFiltering) {
7021 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7022 }
7023 if (needsFiltering) {
7024 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7025 }
7026 }
7027
Valentin Iftime9fa35092019-09-24 13:32:13 +02007028 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007029 if (mWolSupportedInterfaces == null) {
7030 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007031 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007032 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007033 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7034 }
7035
Luke Huangb913c812018-08-24 20:33:16 +08007036 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007037 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007038 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007039 }
7040 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007041 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007042 }
Luke Huangb913c812018-08-24 20:33:16 +08007043 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007044 }
7045
Chalard Jean62edfd82019-12-02 18:39:29 +09007046 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7047 @NonNull final NetworkCapabilities newNc) {
7048 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7049 final int newPermission = getNetworkPermission(newNc);
7050 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7051 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007052 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007053 } catch (RemoteException | ServiceSpecificException e) {
7054 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007055 }
7056 }
7057 }
7058
Paul Jensen53f08952015-06-16 14:27:36 -04007059 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007060 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7061 * Stores into |nai| any data coming from the agent that might also be written to the network's
7062 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7063 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007064 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007065 */
7066 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007067 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7068 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7069 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7070 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007071 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7072 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7073 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7074 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7075 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007076 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007077 }
7078
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007079 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007080 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007081 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007082 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007083 underlyingNetworks = underlyingNetworksOrDefault(
7084 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007085 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007086 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7087 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007088 // metered if any underlying is metered, or originally declared metered by the agent.
7089 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007090 boolean roaming = false; // roaming if any underlying is roaming
7091 boolean congested = false; // congested if any underlying is congested
7092 boolean suspended = true; // suspended if all underlying are suspended
7093
7094 boolean hadUnderlyingNetworks = false;
7095 if (null != underlyingNetworks) {
7096 for (Network underlyingNetwork : underlyingNetworks) {
7097 final NetworkAgentInfo underlying =
7098 getNetworkAgentInfoForNetwork(underlyingNetwork);
7099 if (underlying == null) continue;
7100
7101 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7102 hadUnderlyingNetworks = true;
7103 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007104 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007105 }
7106
7107 // Merge capabilities of this underlying network. For bandwidth, assume the
7108 // worst case.
7109 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7110 underlyingCaps.getLinkDownstreamBandwidthKbps());
7111 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7112 underlyingCaps.getLinkUpstreamBandwidthKbps());
7113 // If this underlying network is metered, the VPN is metered (it may cost money
7114 // to send packets on this network).
7115 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7116 // If this underlying network is roaming, the VPN is roaming (the billing structure
7117 // is different than the usual, local one).
7118 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7119 // If this underlying network is congested, the VPN is congested (the current
7120 // condition of the network affects the performance of this network).
7121 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7122 // If this network is not suspended, the VPN is not suspended (the VPN
7123 // is able to transfer some data).
7124 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7125 }
7126 }
7127 if (!hadUnderlyingNetworks) {
7128 // No idea what the underlying networks are; assume reasonable defaults
7129 metered = true;
7130 roaming = false;
7131 congested = false;
7132 suspended = false;
7133 }
7134
lifrade6c2a2021-03-04 14:08:08 +08007135 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007136 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7137 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7138 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7139 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7140 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7141 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007142 }
7143
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007144 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007145 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7146 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7147 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007148 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007149 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007150 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007151 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007152 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7153 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007154 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007155 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007156 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007157 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007158 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7159 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007160 // does not cause any request (that is not a listen) currently matching that agent to
7161 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007162 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007163 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007164 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007165 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007166 }
7167
Paul Jensen53f08952015-06-16 14:27:36 -04007168 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007169 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007170 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007171 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007172 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007173 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007174 }
Paul Jensende49eb12015-06-25 15:30:08 -04007175 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007176 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007177 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007178 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007179 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007180 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007181 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007182 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007183 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007184 }
lucaslin2240ef62019-03-12 13:08:03 +08007185 if (nai.partialConnectivity) {
7186 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7187 } else {
7188 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7189 }
lucasline117e2e2019-10-22 18:27:33 +08007190 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007191
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007192 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007193 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7194 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007195 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007196 }
7197
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007198 if (nai.supportsUnderlyingNetworks()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007199 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7200 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007201 }
7202
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007203 return newNc;
7204 }
7205
Lorenzo Colitti44840702021-01-11 22:27:57 +09007206 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7207 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7208 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7209 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7210 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7211 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7212 if (prevSuspended != suspended) {
7213 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7214 // onResumed have been removed.
7215 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7216 : ConnectivityManager.CALLBACK_RESUMED);
7217 }
7218 if (prevSuspended != suspended || prevRoaming != roaming) {
7219 // updateNetworkInfo will mix in the suspended info from the capabilities and
7220 // take appropriate action for the network having possibly changed state.
7221 updateNetworkInfo(nai, nai.networkInfo);
7222 }
7223 }
7224
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007225 /**
7226 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7227 *
7228 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7229 * capabilities we manage and store in {@code nai}, such as validated status and captive
7230 * portal status)
7231 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7232 * potentially triggers rematches.
7233 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7234 * change.)
7235 *
7236 * @param oldScore score of the network before any of the changes that prompted us
7237 * to call this function.
7238 * @param nai the network having its capabilities updated.
7239 * @param nc the new network capabilities.
7240 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007241 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7242 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007243 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007244 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007245 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007246 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007247
Chalard Jeanb2a49912018-01-16 18:43:05 +09007248 updateUids(nai, prevNc, newNc);
7249
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007250 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007251 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7252 // the change we're processing can't affect any requests, it can only affect the listens
7253 // on this network. We might have been called by rematchNetworkAndRequests when a
7254 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007255 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007256 } else {
7257 // If the requestable capabilities have changed or the score changed, we can't have been
7258 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007259 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007260 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007261 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007262 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007263
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007264 final boolean oldMetered = prevNc.isMetered();
7265 final boolean newMetered = newNc.isMetered();
7266 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007267
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007268 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007269 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7270 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007271 }
junyulaif2c67e42018-08-07 19:50:45 +08007272
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007273 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7274 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007275
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007276 // Report changes that are interesting for network statistics tracking.
7277 if (meteredChanged || roamingChanged) {
7278 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007279 }
7280
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007281 // This network might have been underlying another network. Propagate its capabilities.
7282 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007283
7284 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007285 mDnsManager.updateTransportsForNetwork(
7286 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007287 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007288 }
7289
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007290 /** Convenience method to update the capabilities for a given network. */
7291 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7292 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7293 }
7294
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007295 /**
7296 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7297 * network.
7298 *
7299 * Ingress interface filtering enforces that all apps under the given network can only receive
7300 * packets from the network's interface (and loopback). This is important for VPNs because
7301 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7302 * non-VPN interfaces.
7303 *
7304 * As a result, this method should return true iff
7305 * 1. the network is an app VPN (not legacy VPN)
7306 * 2. the VPN does not allow bypass
7307 * 3. the VPN is fully-routed
7308 * 4. the VPN interface is non-null
7309 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007310 * @see INetd#firewallAddUidInterfaceRules
7311 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007312 */
7313 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7314 LinkProperties lp) {
7315 if (nc == null || lp == null) return false;
7316 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007317 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007318 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007319 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007320 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7321 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007322 }
7323
Chiachang Wang28afaff2020-12-10 22:24:47 +08007324 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7325 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7326 int index = 0;
7327 for (UidRange range : ranges) {
7328 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7329 index++;
7330 }
7331 return stableRanges;
7332 }
7333
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007334 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7335 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7336 for (int i = 0; i < ranges.length; i++) {
7337 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7338 }
7339 return stableRanges;
7340 }
7341
Ken Chen5e65a852020-12-24 12:59:10 +08007342 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7343 int[] exemptUids) {
7344 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7345 try {
7346 mNetd.socketDestroy(ranges, exemptUids);
7347 } catch (Exception e) {
7348 loge("Exception in socket destroy: ", e);
7349 }
7350 }
7351 }
7352
7353 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7354 int[] exemptUids = new int[2];
7355 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7356 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7357 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7358 exemptUids[0] = VPN_UID;
7359 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7360 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7361
7362 maybeCloseSockets(nai, ranges, exemptUids);
7363 try {
7364 if (add) {
7365 mNetd.networkAddUidRanges(nai.network.netId, ranges);
7366 } else {
7367 mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
7368 }
7369 } catch (Exception e) {
7370 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7371 " on netId " + nai.network.netId + ". " + e);
7372 }
7373 maybeCloseSockets(nai, ranges, exemptUids);
7374 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007375
Chalard Jeanb2a49912018-01-16 18:43:05 +09007376 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7377 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007378 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7379 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007380 if (null == prevRanges) prevRanges = new ArraySet<>();
7381 if (null == newRanges) newRanges = new ArraySet<>();
7382 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7383
7384 prevRanges.removeAll(newRanges);
7385 newRanges.removeAll(prevRangesCopy);
7386
7387 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007388 // When updating the VPN uid routing rules, add the new range first then remove the old
7389 // range. If old range were removed first, there would be a window between the old
7390 // range being removed and the new range being added, during which UIDs contained
7391 // in both ranges are not subject to any VPN routing rules. Adding new range before
7392 // removing old range works because, unlike the filtering rules below, it's possible to
7393 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007394 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7395 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7396 // [1-5] & [1-2],[4-5] == [3]
7397 // Then we can do:
7398 // maybeCloseSockets([3])
7399 // mNetd.networkAddUidRanges([1-2],[4-5])
7400 // mNetd.networkRemoveUidRanges([1-5])
7401 // maybeCloseSockets([3])
7402 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7403 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007404 if (!newRanges.isEmpty()) {
Ken Chen5e65a852020-12-24 12:59:10 +08007405 updateUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007406 }
7407 if (!prevRanges.isEmpty()) {
Ken Chen5e65a852020-12-24 12:59:10 +08007408 updateUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007409 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007410 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7411 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7412 final String iface = nai.linkProperties.getInterfaceName();
7413 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007414 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007415 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7416 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7417 // were added first and then newRanges got removed later, there would be only one uid
7418 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7419 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7420 // Note that this is in contrast with the (more robust) update of VPN routing rules
7421 // above, where the addition of new ranges happens before the removal of old ranges.
7422 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7423 // to be removed will never overlap with the new range to be added.
7424 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007425 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007426 }
7427 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007428 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007429 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007430 } catch (Exception e) {
7431 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007432 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007433 }
7434 }
7435
Hugo Benichi9d35b752017-09-01 01:23:32 +00007436 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007437 ensureRunningOnConnectivityServiceThread();
7438
Serik Beketayevec8ad212020-12-07 22:43:07 -08007439 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007440 // Ignore updates for disconnected networks
7441 return;
7442 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007443 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007444 log("Update of LinkProperties for " + nai.toShortString()
7445 + "; created=" + nai.created
7446 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007447 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007448 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7449 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007450 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007451 }
7452
Paul Jensenaf94b982014-09-30 15:37:41 -04007453 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007454 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7455 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007456 // Don't send listening or track default request to factories. b/17393458
7457 if (!nr.isRequest()) continue;
Chalard Jean29d06db2018-05-02 21:14:54 +09007458 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenaf94b982014-09-30 15:37:41 -04007459 }
7460 }
7461
James Mattisa076c532020-12-02 14:12:41 -08007462 private void sendUpdatedScoreToFactories(
7463 @NonNull final NetworkReassignment.RequestReassignment event) {
7464 // If a request of type REQUEST is now being satisfied by a new network.
7465 if (null != event.mNewNetworkRequest && event.mNewNetworkRequest.isRequest()) {
7466 sendUpdatedScoreToFactories(event.mNewNetworkRequest, event.mNewNetwork);
7467 }
7468
7469 // If a previously satisfied request of type REQUEST is no longer being satisfied.
7470 if (null != event.mOldNetworkRequest && event.mOldNetworkRequest.isRequest()
7471 && event.mOldNetworkRequest != event.mNewNetworkRequest) {
7472 sendUpdatedScoreToFactories(event.mOldNetworkRequest, null);
7473 }
7474
7475 cancelMultilayerLowerPriorityNpiRequests(event.mNetworkRequestInfo);
7476 }
7477
7478 /**
7479 * Cancel with all NPIs the given NRI's multilayer requests that are a lower priority than
7480 * its currently satisfied active request.
7481 * @param nri the NRI to cancel lower priority requests for.
7482 */
7483 private void cancelMultilayerLowerPriorityNpiRequests(
7484 @NonNull final NetworkRequestInfo nri) {
7485 if (!nri.isMultilayerRequest() || null == nri.mActiveRequest) {
7486 return;
7487 }
7488
7489 final int indexOfNewRequest = nri.mRequests.indexOf(nri.mActiveRequest);
7490 for (int i = indexOfNewRequest + 1; i < nri.mRequests.size(); i++) {
7491 cancelNpiRequest(nri.mRequests.get(i));
7492 }
7493 }
7494
Chalard Jean00419ab2019-12-03 20:37:01 +09007495 private void sendUpdatedScoreToFactories(@NonNull NetworkRequest networkRequest,
7496 @Nullable NetworkAgentInfo nai) {
Chalard Jean04bc8072019-12-03 21:35:40 +09007497 final int score;
7498 final int serial;
Chalard Jean29d06db2018-05-02 21:14:54 +09007499 if (nai != null) {
7500 score = nai.getCurrentScore();
7501 serial = nai.factorySerialNumber;
Chalard Jean04bc8072019-12-03 21:35:40 +09007502 } else {
7503 score = 0;
7504 serial = 0;
Chalard Jean29d06db2018-05-02 21:14:54 +09007505 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007506 if (VDBG || DDBG){
7507 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
7508 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007509 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7510 npi.requestNetwork(networkRequest, score, serial);
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007511 }
7512 }
7513
7514 /** Sends all current NetworkRequests to the specified factory. */
James Mattisf8b661d2020-12-07 20:47:49 -08007515 private void sendAllRequestsToProvider(@NonNull final NetworkProviderInfo npi) {
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007516 ensureRunningOnConnectivityServiceThread();
James Mattisf8b661d2020-12-07 20:47:49 -08007517 for (final NetworkRequestInfo nri : getNrisFromGlobalRequests()) {
7518 for (final NetworkRequest req : nri.mRequests) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007519 if (!req.isRequest() && nri.getActiveRequest() == req) {
James Mattisf8b661d2020-12-07 20:47:49 -08007520 break;
7521 }
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007522 if (!req.isRequest()) {
James Mattisf8b661d2020-12-07 20:47:49 -08007523 continue;
7524 }
7525 // Only set the nai for the request it is satisfying.
7526 final NetworkAgentInfo nai =
7527 nri.getActiveRequest() == req ? nri.getSatisfier() : null;
7528 final int score;
7529 final int serial;
7530 if (null != nai) {
7531 score = nai.getCurrentScore();
7532 serial = nai.factorySerialNumber;
7533 } else {
7534 score = 0;
7535 serial = NetworkProvider.ID_NONE;
7536 }
7537 npi.requestNetwork(req, score, serial);
7538 // For multilayer requests, don't send lower priority requests if a higher priority
7539 // request is already satisfied.
7540 if (null != nai) {
7541 break;
7542 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007543 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007544 }
7545 }
7546
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007547 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7548 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007549 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007550 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007551 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007552 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7553 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7554 // such an API is ever implemented, there is no doubt the right request to send in
7555 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7556 // be sent as a separate extra.
7557 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007558 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007559 sendIntent(nri.mPendingIntent, intent);
7560 }
7561 // else not handled
7562 }
7563
7564 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7565 mPendingIntentWakeLock.acquire();
7566 try {
7567 if (DBG) log("Sending " + pendingIntent);
7568 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7569 } catch (PendingIntent.CanceledException e) {
7570 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7571 mPendingIntentWakeLock.release();
7572 releasePendingNetworkRequest(pendingIntent);
7573 }
7574 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7575 }
7576
7577 @Override
7578 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7579 String resultData, Bundle resultExtras) {
7580 if (DBG) log("Finished sending " + pendingIntent);
7581 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007582 // Release with a delay so the receiving client has an opportunity to put in its
7583 // own request.
7584 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007585 }
7586
James Mattis212df9e2020-12-03 19:57:41 -08007587 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7588 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7589 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007590 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007591 // Default request has no msgr. Also prevents callbacks from being invoked for
7592 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7593 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7594 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007595 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007596 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007597 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007598 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007599 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007600 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007601 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007602 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7603 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007604 }
Roshan Pius951c0032020-12-22 15:10:42 -08007605 final boolean includeLocationSensitiveInfo =
7606 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007607 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007608 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007609 final NetworkCapabilities nc =
7610 networkCapabilitiesRestrictedForCallerPermissions(
7611 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7612 putParcelable(
7613 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007614 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007615 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007616 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007617 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007618 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7619 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007620 // For this notification, arg1 contains the blocked status.
7621 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007622 break;
7623 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007624 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007625 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007626 break;
7627 }
7628 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007629 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007630 final NetworkCapabilities netCap =
7631 networkCapabilitiesRestrictedForCallerPermissions(
7632 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7633 putParcelable(
7634 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007635 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007636 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007637 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007638 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007639 break;
7640 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007641 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007642 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7643 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007644 break;
7645 }
junyulaif2c67e42018-08-07 19:50:45 +08007646 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007647 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007648 msg.arg1 = arg1;
7649 break;
7650 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007651 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007652 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007653 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007654 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007655 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007656 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007657 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007658 }
James Mattis45d81842021-01-10 14:24:24 -08007659 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007660 } catch (RemoteException e) {
7661 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007662 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007663 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007664 }
7665
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007666 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7667 bundle.putParcelable(t.getClass().getSimpleName(), t);
7668 }
7669
Paul Jensenaf94b982014-09-30 15:37:41 -04007670 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007671 if (nai.numRequestNetworkRequests() != 0) {
7672 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7673 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007674 // Ignore listening and track default requests.
7675 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007676 loge("Dead network still had at least " + nr);
7677 break;
7678 }
Paul Jensenaf94b982014-09-30 15:37:41 -04007679 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007680 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04007681 }
7682
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007683 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7684 if (oldNetwork == null) {
7685 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7686 return;
7687 }
Chalard Jean49707572019-12-10 21:07:02 +09007688 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007689
7690 // If we get here it means that the last linger timeout for this network expired. So there
7691 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08007692 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007693
Lorenzo Colitti2666be82016-09-09 18:48:56 +09007694 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007695 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007696 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007697 } else {
junyulai0ac374f2020-12-14 18:41:52 +08007698 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007699 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007700 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007701 }
7702
James Mattise3ef1912020-12-20 11:09:58 -08007703 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7704 boolean isDefaultChanged = false;
7705 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7706 final NetworkReassignment.RequestReassignment reassignment =
7707 changes.getReassignment(defaultRequestInfo);
7708 if (null == reassignment) {
7709 continue;
7710 }
7711 // reassignment only contains those instances where the satisfying network changed.
7712 isDefaultChanged = true;
7713 // Notify system services of the new default.
7714 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7715 }
Chiachang Wang087fd272018-09-28 22:42:48 +08007716
James Mattise3ef1912020-12-20 11:09:58 -08007717 if (isDefaultChanged) {
7718 // Hold a wakelock for a short time to help apps in migrating to a new default.
7719 scheduleReleaseNetworkTransitionWakelock();
7720 }
7721 }
7722
7723 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7724 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7725 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7726 if (DBG) {
7727 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7728 }
Chalard Jean8e382112019-12-03 20:45:30 +09007729
James Mattisd31bdfa2020-12-23 16:37:26 -08007730 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7731 if (newDefaultNetwork != null) {
7732 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04007733 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09007734
James Mattisd31bdfa2020-12-23 16:37:26 -08007735 // Set an app level managed default and return since further processing only applies to the
7736 // default network.
7737 if (mDefaultRequest != nri) {
7738 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7739 return;
7740 }
7741
7742 makeDefaultNetwork(newDefaultNetwork);
7743
James Mattise3ef1912020-12-20 11:09:58 -08007744 if (oldDefaultNetwork != null) {
7745 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7746 }
7747 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08007748 handleApplyDefaultProxy(null != newDefaultNetwork
7749 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7750 updateTcpBufferSizes(null != newDefaultNetwork
7751 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09007752 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04007753 }
7754
James Mattisd31bdfa2020-12-23 16:37:26 -08007755 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7756 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7757 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7758 try {
7759 if (VDBG) {
7760 log("Setting default network for " + nri
7761 + " using UIDs " + nri.getUids()
7762 + " with old network " + (oldDefaultNetwork != null
7763 ? oldDefaultNetwork.network().getNetId() : "null")
7764 + " and new network " + (newDefaultNetwork != null
7765 ? newDefaultNetwork.network().getNetId() : "null"));
7766 }
7767 if (nri.getUids().isEmpty()) {
7768 throw new IllegalStateException("makeDefaultForApps called without specifying"
7769 + " any applications to set as the default." + nri);
7770 }
7771 if (null != newDefaultNetwork) {
7772 mNetd.networkAddUidRanges(
7773 newDefaultNetwork.network.getNetId(),
7774 toUidRangeStableParcels(nri.getUids()));
7775 }
7776 if (null != oldDefaultNetwork) {
7777 mNetd.networkRemoveUidRanges(
7778 oldDefaultNetwork.network.getNetId(),
7779 toUidRangeStableParcels(nri.getUids()));
7780 }
7781 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09007782 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08007783 }
7784 }
7785
7786 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7787 try {
7788 if (null != newDefaultNetwork) {
7789 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7790 } else {
7791 mNetd.networkClearDefault();
7792 }
7793 } catch (RemoteException | ServiceSpecificException e) {
7794 loge("Exception setting default network :" + e);
7795 }
7796 }
7797
Chalard Jean05cbe972019-12-09 11:50:38 +09007798 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007799 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09007800 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09007801 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09007802 processNewlySatisfiedListenRequests(nai);
7803 }
7804
7805 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08007806 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7807 if (nri.isMultilayerRequest()) {
7808 continue;
7809 }
7810 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007811 if (!nr.isListen()) continue;
7812 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08007813 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007814 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7815 }
7816 }
Chalard Jeancd397a22019-11-22 22:33:33 +09007817 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007818
Chalard Jeancd397a22019-11-22 22:33:33 +09007819 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08007820 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7821 if (nri.isMultilayerRequest()) {
7822 continue;
7823 }
7824 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007825 if (!nr.isListen()) continue;
7826 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7827 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09007828 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007829 }
7830 }
7831 }
7832
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007833 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007834 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007835 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08007836 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09007837 @Nullable public final NetworkRequest mOldNetworkRequest;
7838 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007839 @Nullable public final NetworkAgentInfo mOldNetwork;
7840 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08007841 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09007842 @Nullable final NetworkRequest oldNetworkRequest,
7843 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007844 @Nullable final NetworkAgentInfo oldNetwork,
7845 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08007846 mNetworkRequestInfo = networkRequestInfo;
7847 mOldNetworkRequest = oldNetworkRequest;
7848 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007849 mOldNetwork = oldNetwork;
7850 mNewNetwork = newNetwork;
7851 }
Chalard Jean49707572019-12-10 21:07:02 +09007852
7853 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09007854 final NetworkRequest requestToShow = null != mNewNetworkRequest
7855 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7856 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08007857 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7858 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09007859 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007860 }
7861
Chalard Jean46a62372019-12-10 21:25:24 +09007862 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007863
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007864 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09007865 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007866 }
7867
7868 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09007869 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09007870 // The code is never supposed to add two reassignments of the same request. Make
7871 // sure this stays true, but without imposing this expensive check on all
7872 // reassignments on all user devices.
7873 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08007874 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09007875 throw new IllegalStateException("Trying to reassign ["
7876 + reassignment + "] but already have ["
7877 + existing + "]");
7878 }
7879 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09007880 }
Chalard Jean46a62372019-12-10 21:25:24 +09007881 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007882 }
7883
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007884 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09007885 // the passed request.
7886 @Nullable
7887 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007888 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08007889 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007890 }
7891 return null;
7892 }
Chalard Jean49707572019-12-10 21:07:02 +09007893
7894 public String toString() {
7895 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7896 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09007897 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09007898 for (final RequestReassignment rr : getRequestReassignments()) {
7899 sj.add(rr.toString());
7900 }
7901 return sj.toString();
7902 }
7903
7904 public String debugString() {
7905 final StringBuilder sb = new StringBuilder();
7906 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09007907 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09007908 for (final RequestReassignment rr : getRequestReassignments()) {
7909 sb.append("\n ").append(rr);
7910 }
7911 return sb.append("\n").toString();
7912 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007913 }
7914
Chalard Jean24344d72019-12-04 13:32:31 +09007915 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09007916 @Nullable final NetworkRequest previousRequest,
7917 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09007918 @Nullable final NetworkAgentInfo previousSatisfier,
7919 @Nullable final NetworkAgentInfo newSatisfier,
7920 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08007921 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09007922 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09007923 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09007924 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007925 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09007926 }
James Mattisa076c532020-12-02 14:12:41 -08007927 previousSatisfier.removeRequest(previousRequest.requestId);
7928 previousSatisfier.lingerRequest(previousRequest.requestId, now, mLingerDelayMs);
Chalard Jean24344d72019-12-04 13:32:31 +09007929 } else {
7930 if (VDBG || DDBG) log(" accepting network in place of null");
7931 }
junyulai0ac374f2020-12-14 18:41:52 +08007932
7933 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7934 // and immediately satisfies a request then remove the timer. This will happen for
7935 // all networks except in the case of an underlying network for a VCN.
7936 if (newSatisfier.isNascent()) {
7937 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
7938 }
7939
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007940 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08007941 newSatisfier.unlingerRequest(newRequest.requestId);
7942 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007943 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08007944 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09007945 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09007946 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09007947 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007948 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08007949 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09007950 }
James Mattisa076c532020-12-02 14:12:41 -08007951 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09007952 }
James Mattisa076c532020-12-02 14:12:41 -08007953 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09007954 }
7955
James Mattisa076c532020-12-02 14:12:41 -08007956 /**
7957 * This function is triggered when something can affect what network should satisfy what
7958 * request, and it computes the network reassignment from the passed collection of requests to
7959 * network match to the one that the system should now have. That data is encoded in an
7960 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
7961 * satisfier.
7962 *
7963 * After the reassignment is computed, it is applied to the state objects.
7964 *
7965 * @param networkRequests the nri objects to evaluate for possible network reassignment
7966 * @return NetworkReassignment listing of proposed network assignment changes
7967 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09007968 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08007969 private NetworkReassignment computeNetworkReassignment(
7970 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09007971 final NetworkReassignment changes = new NetworkReassignment();
7972
7973 // Gather the list of all relevant agents and sort them by score.
7974 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007975 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08007976 if (!nai.everConnected) {
7977 continue;
7978 }
Chalard Jean857a1712019-12-10 21:08:07 +09007979 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09007980 }
Chalard Jean857a1712019-12-10 21:08:07 +09007981
James Mattisa076c532020-12-02 14:12:41 -08007982 for (final NetworkRequestInfo nri : networkRequests) {
7983 // Non-multilayer listen requests can be ignored.
7984 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
7985 continue;
7986 }
7987 NetworkAgentInfo bestNetwork = null;
7988 NetworkRequest bestRequest = null;
7989 for (final NetworkRequest req : nri.mRequests) {
7990 bestNetwork = mNetworkRanker.getBestNetwork(req, nais);
7991 // Stop evaluating as the highest possible priority request is satisfied.
7992 if (null != bestNetwork) {
7993 bestRequest = req;
7994 break;
7995 }
7996 }
James Mattisd31bdfa2020-12-23 16:37:26 -08007997 if (null == bestNetwork && isDefaultBlocked(nri)) {
7998 // Remove default networking if disallowed for managed default requests.
7999 bestNetwork = mNoServiceNetwork;
8000 }
8001 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008002 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008003 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008004 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008005 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008006 }
8007 return changes;
8008 }
8009
James Mattisa076c532020-12-02 14:12:41 -08008010 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8011 return new HashSet<>(mNetworkRequests.values());
8012 }
8013
Paul Jensenc88b39b2015-06-16 14:27:36 -04008014 /**
James Mattisa076c532020-12-02 14:12:41 -08008015 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008016 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008017 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008018 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008019 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8020 }
8021
8022 /**
8023 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8024 * being disconnected.
8025 */
8026 private void rematchNetworksAndRequests(
8027 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8028 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008029 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008030 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008031 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008032 if (VDBG || DDBG) {
8033 log(changes.debugString());
8034 } else if (DBG) {
8035 log(changes.toString()); // Shorter form, only one line of log
8036 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008037 applyNetworkReassignment(changes, now);
Chalard Jeand7f762d2019-12-10 19:01:29 +09008038 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008039
Chalard Jeand7f762d2019-12-10 19:01:29 +09008040 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008041 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008042 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008043
8044 // Since most of the time there are only 0 or 1 background networks, it would probably
8045 // be more efficient to just use an ArrayList here. TODO : measure performance
8046 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8047 for (final NetworkAgentInfo nai : nais) {
8048 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8049 }
8050
Chalard Jeand7f762d2019-12-10 19:01:29 +09008051 // First, update the lists of satisfied requests in the network agents. This is necessary
8052 // because some code later depends on this state to be correct, most prominently computing
8053 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008054 for (final NetworkReassignment.RequestReassignment event :
8055 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008056 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8057 event.mOldNetworkRequest, event.mNewNetworkRequest,
8058 event.mOldNetwork, event.mNewNetwork,
8059 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008060 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008061
James Mattise3ef1912020-12-20 11:09:58 -08008062 // Process default network changes if applicable.
8063 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008064
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008065 // Notify requested networks are available after the default net is switched, but
8066 // before LegacyTypeTracker sends legacy broadcasts
8067 for (final NetworkReassignment.RequestReassignment event :
8068 changes.getRequestReassignments()) {
Chalard Jean04bc8072019-12-03 21:35:40 +09008069 // Tell NetworkProviders about the new score, so they can stop
8070 // trying to connect if they know they cannot match it.
8071 // TODO - this could get expensive if there are a lot of outstanding requests for this
8072 // network. Think of a way to reduce this. Push netid->request mapping to each factory?
James Mattisa076c532020-12-02 14:12:41 -08008073 sendUpdatedScoreToFactories(event);
Chalard Jean04bc8072019-12-03 21:35:40 +09008074
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008075 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008076 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008077 } else {
James Mattisa076c532020-12-02 14:12:41 -08008078 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008079 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008080 }
8081 }
8082
junyulai0ac374f2020-12-14 18:41:52 +08008083 // Update the inactivity state before processing listen callbacks, because the background
8084 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008085 // just yet though, because they have to be sent after the listens are processed to keep
8086 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008087 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008088 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008089 // Rematching may have altered the inactivity state of some networks, so update all
8090 // inactivity timers. updateInactivityState reads the state from the network agent
8091 // and does nothing if the state has not changed : the source of truth is controlled
8092 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8093 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008094 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008095 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008096 }
8097 }
8098
Chalard Jeanb10ab412019-12-11 14:12:30 +09008099 for (final NetworkAgentInfo nai : nais) {
8100 if (!nai.everConnected) continue;
8101 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008102 // Process listen requests and update capabilities if the background state has
8103 // changed for this network. For consistency with previous behavior, send onLost
8104 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008105 processNewlyLostListenRequests(nai);
8106 if (oldBackground != nai.isBackgroundNetwork()) {
8107 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008108 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008109 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008110 }
8111
junyulai0ac374f2020-12-14 18:41:52 +08008112 for (final NetworkAgentInfo nai : inactiveNetworks) {
8113 // For nascent networks, if connecting with no foreground request, skip broadcasting
8114 // LOSING for backward compatibility. This is typical when mobile data connected while
8115 // wifi connected with mobile data always-on enabled.
8116 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008117 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008118 }
8119
James Mattise3ef1912020-12-20 11:09:58 -08008120 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008121
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008122 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008123 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008124 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008125 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008126 // This network has active linger timers and no requests, but is not
8127 // lingering. Linger it.
8128 //
8129 // One way (the only way?) this can happen if this network is unvalidated
8130 // and became unneeded due to another network improving its score to the
8131 // point where this network will no longer be able to satisfy any requests
8132 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008133 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008134 notifyNetworkLosing(nai, now);
8135 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008136 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008137 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008138 teardownUnneededNetwork(nai);
8139 }
8140 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008141 }
8142 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008143
Chalard Jean62edfd82019-12-02 18:39:29 +09008144 /**
8145 * Apply a change in background state resulting from rematching networks with requests.
8146 *
8147 * During rematch, a network may change background states by starting to satisfy or stopping
8148 * to satisfy a foreground request. Listens don't count for this. When a network changes
8149 * background states, its capabilities need to be updated and callbacks fired for the
8150 * capability change.
8151 *
8152 * @param nai The network that changed background states
8153 */
8154 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8155 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8156 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8157 updateNetworkPermissions(nai, newNc);
8158 nai.getAndSetNetworkCapabilities(newNc);
8159 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8160 }
8161
Chalard Jeanf0344532019-11-19 19:23:38 +09008162 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008163 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008164 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008165 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8166 changes.getReassignment(mDefaultRequest);
8167 final NetworkAgentInfo oldDefaultNetwork =
8168 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8169 final NetworkAgentInfo newDefaultNetwork =
8170 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008171
Chalard Jean5b409c72021-02-04 13:12:59 +09008172 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008173 // Maintain the illusion : since the legacy API only understands one network at a time,
8174 // if the default network changed, apps should see a disconnected broadcast for the
8175 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008176 if (oldDefaultNetwork != null) {
8177 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8178 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008179 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008180 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008181 // The new default network can be newly null if and only if the old default
8182 // network doesn't satisfy the default request any more because it lost a
8183 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008184 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008185 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008186 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008187 }
8188 }
8189
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008190 // Now that all the callbacks have been sent, send the legacy network broadcasts
8191 // as needed. This is necessary so that legacy requests correctly bind dns
8192 // requests to this network. The legacy users are listening for this broadcast
8193 // and will generally do a dns request so they can ensureRouteToHost and if
8194 // they do that before the callbacks happen they'll use the default network.
8195 //
8196 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8197 // callbacks, but if apps can receive the broadcast before the callback, they still might
8198 // have an inconsistent view of networking.
8199 //
8200 // This *does* introduce a race where if the user uses the new api
8201 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8202 // they may get old info. Reverse this after the old startUsing api is removed.
8203 // This is on top of the multiple intent sequencing referenced in the todo above.
8204 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008205 if (nai.everConnected) {
8206 addNetworkToLegacyTypeTracker(nai);
8207 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008208 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008209 }
8210
Chalard Jean61c79252019-11-07 23:07:32 +09008211 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8212 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8213 NetworkRequest nr = nai.requestAt(i);
8214 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8215 // legacy type tracker filters out repeat adds
8216 mLegacyTypeTracker.add(nr.legacyType, nai);
8217 }
8218 }
8219
8220 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008221 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008222 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8223 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8224 if (nai.isVPN()) {
8225 mLegacyTypeTracker.add(TYPE_VPN, nai);
8226 }
8227 }
8228
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008229 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008230 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008231 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008232 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008233 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008234 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008235
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008236 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008237 // Don't repeat publish.
8238 if (newInetCondition == mDefaultInetConditionPublished) return;
8239
8240 mDefaultInetConditionPublished = newInetCondition;
8241 sendInetConditionBroadcast(nai.networkInfo);
8242 }
8243
Chalard Jeand61375d2020-01-14 22:46:36 +09008244 @NonNull
8245 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8246 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008247 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008248 final boolean suspended =
8249 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8250 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8251 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8252 // state. This is because the network could have been suspended before connecting,
8253 // or it could be disconnecting while being suspended, and in both these cases
8254 // the state should not be overridden. Note that the only detailed state that
8255 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8256 // worry about multiple different substates of CONNECTED.
8257 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8258 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008259 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8260 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8261 // network agent is created, then goes to suspended, then goes out of suspended without
8262 // ever setting connected. Check if network agent is ever connected to update the state.
8263 newInfo.setDetailedState(nai.everConnected
8264 ? NetworkInfo.DetailedState.CONNECTED
8265 : NetworkInfo.DetailedState.CONNECTING,
8266 info.getReason(),
8267 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008268 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008269 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008270 return newInfo;
8271 }
8272
8273 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8274 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8275
Erik Kline99f301b2017-02-15 19:59:17 +09008276 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008277 NetworkInfo oldInfo = null;
8278 synchronized (networkAgent) {
8279 oldInfo = networkAgent.networkInfo;
8280 networkAgent.networkInfo = newInfo;
8281 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008282
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008283 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008284 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8285 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008286 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008287
Robin Leea8c0b6e2016-05-01 23:00:00 +01008288 if (!networkAgent.created
8289 && (state == NetworkInfo.State.CONNECTED
8290 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008291
8292 // A network that has just connected has zero requests and is thus a foreground network.
8293 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8294
Luke Huangfdd11f82019-04-09 18:41:49 +08008295 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008296 if (networkAgent.supportsUnderlyingNetworks()) {
8297 // Initialize the network's capabilities to their starting values according to the
8298 // underlying networks. This ensures that the capabilities are correct before
8299 // anything happens to the network.
8300 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008301 }
Paul Jensen74940202014-08-04 12:21:19 -04008302 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008303 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008304 }
8305
8306 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8307 networkAgent.everConnected = true;
8308
lucaslin45e639b2019-04-03 17:09:28 +08008309 // NetworkCapabilities need to be set before sending the private DNS config to
8310 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008311 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8312
Erik Kline9a62f012018-03-21 07:18:33 -07008313 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008314 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8315 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008316
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008317 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8318 // command must be sent after updating LinkProperties to maximize chances of
8319 // NetworkMonitor seeing the correct LinkProperties when starting.
8320 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008321 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008322 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008323 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008324 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008325 new LinkProperties(networkAgent.linkProperties,
8326 true /* parcelSensitiveFields */),
8327 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008328 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008329
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008330 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8331 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8332 // capabilities, so it only needs to be done once on initial connect, not every time the
8333 // network's capabilities change. Note that we do this before rematching the network,
8334 // so we could decide to tear it down immediately afterwards. That's fine though - on
8335 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8336 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008337 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008338
junyulai0ac374f2020-12-14 18:41:52 +08008339 // Before first rematching networks, put an inactivity timer without any request, this
8340 // allows {@code updateInactivityState} to update the state accordingly and prevent
8341 // tearing down for any {@code unneeded} evaluation in this period.
8342 // Note that the timer will not be rescheduled since the expiry time is
8343 // fixed after connection regardless of the network satisfying other requests or not.
8344 // But it will be removed as soon as the network satisfies a request for the first time.
8345 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8346 SystemClock.elapsedRealtime(), mNascentDelayMs);
8347
Paul Jensen05e85ee2014-09-11 11:00:39 -04008348 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008349 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008350
8351 // This has to happen after matching the requests, because callbacks are just requests.
8352 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008353 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008354 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008355 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008356 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008357 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008358 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008359 if (networkAgent.isVPN()) {
8360 // As the active or bound network changes for apps, broadcast the default proxy, as
8361 // apps may need to update their proxy data. This is called after disconnecting from
8362 // VPN to make sure we do not broadcast the old proxy data.
8363 // TODO(b/122649188): send the broadcast only to VPN users.
8364 mProxyTracker.sendProxyBroadcast();
8365 }
Yintang Gu5014b522019-06-18 14:24:32 +08008366 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8367 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008368 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008369 }
8370 }
8371
Chalard Jean28018572020-12-21 18:36:52 +09008372 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008373 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8374 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008375 rematchAllNetworksAndRequests();
Paul Jensenaf94b982014-09-30 15:37:41 -04008376 sendUpdatedScoreToFactories(nai);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008377 }
8378
Erik Kline99f301b2017-02-15 19:59:17 +09008379 // Notify only this one new request of the current state. Transfer all the
8380 // current state by calling NetworkCapabilities and LinkProperties callbacks
8381 // so that callers can be guaranteed to have as close to atomicity in state
8382 // transfer as can be supported by this current API.
8383 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008384 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008385 if (nri.mPendingIntent != null) {
8386 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8387 // Attempt no subsequent state pushes where intents are involved.
8388 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008389 }
Erik Kline99f301b2017-02-15 19:59:17 +09008390
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008391 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008392 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008393 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8394 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8395 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008396 }
8397
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008398 // Notify the requests on this NAI that the network is now lingered.
8399 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008400 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008401 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8402 }
8403
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008404 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8405 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8406 return vpnBlocked
8407 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8408 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8409 }
8410
8411 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8412 if (blockedReasons == BLOCKED_REASON_NONE) {
8413 mUidBlockedReasons.delete(uid);
8414 } else {
8415 mUidBlockedReasons.put(uid, blockedReasons);
8416 }
8417 }
8418
junyulaif2c67e42018-08-07 19:50:45 +08008419 /**
8420 * Notify of the blocked state apps with a registered callback matching a given NAI.
8421 *
8422 * Unlike other callbacks, blocked status is different between each individual uid. So for
8423 * any given nai, all requests need to be considered according to the uid who filed it.
8424 *
8425 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008426 * @param oldMetered True if the previous network capabilities were metered.
8427 * @param newMetered True if the current network capabilities are metered.
8428 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8429 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008430 */
8431 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008432 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8433 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008434
8435 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8436 NetworkRequest nr = nai.requestAt(i);
8437 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008438
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008439 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8440 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8441 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008442 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008443 : oldVpnBlocked;
8444
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008445 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8446 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8447 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008448 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008449 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008450 }
8451 }
8452 }
8453
8454 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008455 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008456 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008457 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008458 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008459 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008460 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008461 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008462 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008463
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008464 final int oldBlockedState = getBlockedState(
8465 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8466 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8467 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008468 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008469 }
junyulaif2c67e42018-08-07 19:50:45 +08008470 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8471 NetworkRequest nr = nai.requestAt(i);
8472 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008473 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008474 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8475 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008476 }
8477 }
8478 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008479 }
8480
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008481 @VisibleForTesting
8482 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008483 // The NetworkInfo we actually send out has no bearing on the real
8484 // state of affairs. For example, if the default connection is mobile,
8485 // and a request for HIPRI has just gone away, we need to pretend that
8486 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8487 // the state to DISCONNECTED, even though the network is of type MOBILE
8488 // and is still connected.
8489 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8490 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008491 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008492 if (state != DetailedState.DISCONNECTED) {
8493 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008494 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008495 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008496 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008497 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8498 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8499 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8500 if (info.isFailover()) {
8501 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8502 nai.networkInfo.setFailover(false);
8503 }
8504 if (info.getReason() != null) {
8505 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8506 }
8507 if (info.getExtraInfo() != null) {
8508 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8509 }
8510 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008511 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008512 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008513 if (newDefaultAgent != null) {
8514 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8515 newDefaultAgent.networkInfo);
8516 } else {
8517 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8518 }
8519 }
8520 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8521 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008522 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008523 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008524 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008525 }
8526 }
8527 }
8528
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008529 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008530 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008531 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008532 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008533 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008534 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8535 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008536 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8537 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008538 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008539 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008540 } else {
8541 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8542 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008543 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008544 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008545
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008546 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8547 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8548 }
8549
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008550 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008551 * Returns the list of all interfaces that could be used by network traffic that does not
8552 * explicitly specify a network. This includes the default network, but also all VPNs that are
8553 * currently connected.
8554 *
8555 * Must be called on the handler thread.
8556 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008557 @NonNull
8558 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008559 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008560 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008561 final Set<Integer> activeNetIds = new ArraySet<>();
8562 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8563 if (nri.isBeingSatisfied()) {
8564 activeNetIds.add(nri.getSatisfier().network().netId);
8565 }
8566 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008567 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008568 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008569 defaultNetworks.add(nai.network);
8570 }
8571 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008572 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008573 }
8574
8575 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09008576 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8577 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008578 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08008579 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008580 ensureRunningOnConnectivityServiceThread();
8581 String activeIface = null;
8582 LinkProperties activeLinkProperties = getActiveLinkProperties();
8583 if (activeLinkProperties != null) {
8584 activeIface = activeLinkProperties.getInterfaceName();
8585 }
Benedict Wong9308cd32019-06-12 17:46:31 +00008586
junyulai2050bed2021-01-23 09:46:34 +08008587 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008588 try {
junyulaide41fc22021-01-22 22:46:01 +08008589 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08008590 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08008591 snapshots.add(snapshot);
8592 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008593 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8594 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008595 } catch (Exception ignored) {
8596 }
8597 }
8598
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07008599 @Override
Udam Sainicd645462016-01-04 12:16:14 -08008600 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08008601 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008602 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008603 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008604
8605 if (!TextUtils.isEmpty(settingUrl)) {
8606 return settingUrl;
8607 }
8608
8609 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08008610 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008611 if (!TextUtils.isEmpty(settingUrl)) {
8612 return settingUrl;
8613 }
8614
8615 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08008616 }
8617
8618 @Override
junyulai070f9ff2019-01-16 20:23:34 +08008619 public void startNattKeepalive(Network network, int intervalSeconds,
8620 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008621 enforceKeepalivePermission();
8622 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08008623 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08008624 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08008625 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008626 }
8627
8628 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08008629 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08008630 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08008631 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07008632 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08008633 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07008634 mKeepaliveTracker.startNattKeepalive(
8635 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8636 intervalSeconds, cb,
8637 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8638 } finally {
8639 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8640 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08008641 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8642 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07008643 }
8644 }
junyulaid05a1922019-01-15 11:32:44 +08008645 }
8646
8647 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08008648 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08008649 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07008650 try {
8651 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08008652 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07008653 mKeepaliveTracker.startTcpKeepalive(
8654 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8655 } finally {
8656 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8657 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08008658 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8659 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07008660 }
8661 }
junyulai0835a1e2019-01-08 20:04:33 +08008662 }
8663
8664 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008665 public void stopKeepalive(Network network, int slot) {
8666 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08008667 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008668 }
8669
8670 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07008671 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08008672 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07008673
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08008674 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08008675 final long token = Binder.clearCallingIdentity();
8676 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08008677 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
8678 UserHandle.getUserHandleForUid(uid))) {
8679 return;
8680 }
8681
Heemin Seogdb8489d2019-06-12 09:21:44 -07008682 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8683 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08008684
8685 // Turn airplane mode off
8686 setAirplaneMode(false);
8687
8688 // restore private DNS settings to default mode (opportunistic)
8689 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
8690 UserHandle.getUserHandleForUid(uid))) {
8691 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
8692 PRIVATE_DNS_MODE_OPPORTUNISTIC);
8693 }
8694
8695 Settings.Global.putString(mContext.getContentResolver(),
8696 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08008697 } finally {
8698 Binder.restoreCallingIdentity(token);
8699 }
Stuart Scottd5463642015-04-02 18:00:02 -07008700 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04008701
Ricky Wai7097cc92018-01-23 04:09:45 +00008702 @Override
8703 public byte[] getNetworkWatchlistConfigHash() {
8704 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8705 if (nwm == null) {
8706 loge("Unable to get NetworkWatchlistManager");
8707 return null;
8708 }
8709 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8710 return nwm.getWatchlistConfigHash();
8711 }
8712
Hugo Benichibe0c7652016-05-31 16:28:06 +09008713 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09008714 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08008715 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09008716 }
Hugo Benichif4210292017-04-21 15:07:12 +09008717
8718 private static boolean toBool(int encodedBoolean) {
8719 return encodedBoolean != 0; // Only 0 means false.
8720 }
8721
8722 private static int encodeBool(boolean b) {
8723 return b ? 1 : 0;
8724 }
mswest4632928412018-03-12 10:34:34 -07008725
8726 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08008727 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8728 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8729 @NonNull String[] args) {
8730 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8731 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07008732 }
8733
Chiachang Wang77ae8a02020-10-12 15:20:07 +08008734 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07008735 @Override
8736 public int onCommand(String cmd) {
8737 if (cmd == null) {
8738 return handleDefaultCommands(cmd);
8739 }
8740 final PrintWriter pw = getOutPrintWriter();
8741 try {
8742 switch (cmd) {
8743 case "airplane-mode":
8744 final String action = getNextArg();
8745 if ("enable".equals(action)) {
8746 setAirplaneMode(true);
8747 return 0;
8748 } else if ("disable".equals(action)) {
8749 setAirplaneMode(false);
8750 return 0;
8751 } else if (action == null) {
8752 final ContentResolver cr = mContext.getContentResolver();
8753 final int enabled = Settings.Global.getInt(cr,
8754 Settings.Global.AIRPLANE_MODE_ON);
8755 pw.println(enabled == 0 ? "disabled" : "enabled");
8756 return 0;
8757 } else {
8758 onHelp();
8759 return -1;
8760 }
8761 default:
8762 return handleDefaultCommands(cmd);
8763 }
8764 } catch (Exception e) {
8765 pw.println(e);
8766 }
8767 return -1;
8768 }
8769
8770 @Override
8771 public void onHelp() {
8772 PrintWriter pw = getOutPrintWriter();
8773 pw.println("Connectivity service commands:");
8774 pw.println(" help");
8775 pw.println(" Print this help text.");
8776 pw.println(" airplane-mode [enable|disable]");
8777 pw.println(" Turn airplane mode on or off.");
8778 pw.println(" airplane-mode");
8779 pw.println(" Get airplane mode.");
8780 }
8781 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008782
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09008783 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09008784 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8785 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8786 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08008787 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008788 }
8789
8790 /**
8791 * @param connectionInfo the connection to resolve.
8792 * @return {@code uid} if the connection is found and the app has permission to observe it
8793 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8794 * connection is not found.
8795 */
8796 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008797 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8798 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8799 }
8800
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09008801 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008802 connectionInfo.local, connectionInfo.remote);
8803
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09008804 if (uid == INVALID_UID) return uid; // Not found.
8805
8806 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8807 // VPN, if any, that applies to the UID that owns the connection.
8808 if (checkNetworkStackPermission()) return uid;
8809
8810 final NetworkAgentInfo vpn = getVpnForUid(uid);
8811 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008812 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008813 return INVALID_UID;
8814 }
8815
8816 return uid;
8817 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00008818
Benedict Wong493e04b2018-11-09 14:45:34 -08008819 /**
8820 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8821 *
8822 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8823 */
8824 @Override
8825 public IBinder startOrGetTestNetworkService() {
8826 synchronized (mTNSLock) {
8827 TestNetworkService.enforceTestNetworkPermissions(mContext);
8828
8829 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08008830 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08008831 }
8832
8833 return mTNS;
8834 }
8835 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08008836
Cody Kesting73708bf2019-12-18 10:57:50 -08008837 /**
8838 * Handler used for managing all Connectivity Diagnostics related functions.
8839 *
8840 * @see android.net.ConnectivityDiagnosticsManager
8841 *
8842 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8843 */
8844 @VisibleForTesting
8845 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08008846 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8847
Cody Kesting73708bf2019-12-18 10:57:50 -08008848 /**
8849 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8850 * android.net.ConnectivityDiagnosticsManager}.
8851 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8852 * NetworkRequestInfo to be registered
8853 */
8854 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8855
8856 /**
8857 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
8858 * android.net.ConnectivityDiagnosticsManager}.
8859 * obj = the IConnectivityDiagnosticsCallback to be unregistered
8860 * arg1 = the uid of the caller
8861 */
8862 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
8863
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008864 /**
8865 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
8866 * after processing {@link #EVENT_NETWORK_TESTED} events.
8867 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
8868 * NetworkMonitor.
8869 * data = PersistableBundle of extras passed from NetworkMonitor.
8870 *
8871 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
8872 */
8873 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
8874
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008875 /**
8876 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
8877 * been detected on the network.
8878 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
8879 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
8880 * arg2 = NetID.
8881 * data = PersistableBundle of extras passed from NetworkMonitor.
8882 */
8883 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
8884
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08008885 /**
8886 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
8887 * the platform. This event will invoke {@link
8888 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
8889 * callbacks.
8890 * obj = Network that was reported on
8891 * arg1 = boolint for the quality reported
8892 */
8893 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
8894
Cody Kesting73708bf2019-12-18 10:57:50 -08008895 private ConnectivityDiagnosticsHandler(Looper looper) {
8896 super(looper);
8897 }
8898
8899 @Override
8900 public void handleMessage(Message msg) {
8901 switch (msg.what) {
8902 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8903 handleRegisterConnectivityDiagnosticsCallback(
8904 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
8905 break;
8906 }
8907 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8908 handleUnregisterConnectivityDiagnosticsCallback(
8909 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
8910 break;
8911 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008912 case EVENT_NETWORK_TESTED: {
8913 final ConnectivityReportEvent reportEvent =
8914 (ConnectivityReportEvent) msg.obj;
8915
Aaron Huang959d3642021-01-21 15:47:41 +08008916 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008917 break;
8918 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008919 case EVENT_DATA_STALL_SUSPECTED: {
8920 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08008921 final Pair<Long, PersistableBundle> arg =
8922 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008923 if (nai == null) break;
8924
Aaron Huang959d3642021-01-21 15:47:41 +08008925 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008926 break;
8927 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08008928 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
8929 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
8930 break;
8931 }
8932 default: {
8933 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
8934 }
Cody Kesting73708bf2019-12-18 10:57:50 -08008935 }
8936 }
8937 }
8938
8939 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
8940 @VisibleForTesting
8941 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
8942 @NonNull private final IConnectivityDiagnosticsCallback mCb;
8943 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008944 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08008945
8946 @VisibleForTesting
8947 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008948 @NonNull IConnectivityDiagnosticsCallback cb,
8949 @NonNull NetworkRequestInfo nri,
8950 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008951 mCb = cb;
8952 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008953 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08008954 }
8955
8956 @Override
8957 public void binderDied() {
8958 log("ConnectivityDiagnosticsCallback IBinder died.");
8959 unregisterConnectivityDiagnosticsCallback(mCb);
8960 }
8961 }
8962
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008963 /**
8964 * Class used for sending information from {@link
8965 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
8966 */
8967 private static class NetworkTestedResults {
8968 private final int mNetId;
8969 private final int mTestResult;
8970 private final long mTimestampMillis;
8971 @Nullable private final String mRedirectUrl;
8972
8973 private NetworkTestedResults(
8974 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
8975 mNetId = netId;
8976 mTestResult = testResult;
8977 mTimestampMillis = timestampMillis;
8978 mRedirectUrl = redirectUrl;
8979 }
8980 }
8981
8982 /**
8983 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
8984 * ConnectivityDiagnosticsHandler}.
8985 */
8986 private static class ConnectivityReportEvent {
8987 private final long mTimestampMillis;
8988 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08008989 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008990
Aaron Huang959d3642021-01-21 15:47:41 +08008991 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
8992 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008993 mTimestampMillis = timestampMillis;
8994 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08008995 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008996 }
8997 }
8998
Cody Kesting73708bf2019-12-18 10:57:50 -08008999 private void handleRegisterConnectivityDiagnosticsCallback(
9000 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9001 ensureRunningOnConnectivityServiceThread();
9002
9003 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009004 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009005 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9006
James Mattis64b8b0f2020-11-24 17:40:49 -08009007 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9008 // confusing for these networks to change when an NRI is satisfied in another layer.
9009 if (nri.isMultilayerRequest()) {
9010 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9011 + "network requests.");
9012 }
9013
Cody Kesting73708bf2019-12-18 10:57:50 -08009014 // This means that the client registered the same callback multiple times. Do
9015 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009016 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009017 if (VDBG) log("Diagnostics callback is already registered");
9018
9019 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9020 // incremented when the NetworkRequestInfo is created as part of
9021 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009022 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009023 return;
9024 }
9025
Cody Kesting31f1ff62020-03-05 10:46:02 -08009026 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009027
9028 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009029 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009030 } catch (RemoteException e) {
9031 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009032 return;
9033 }
9034
9035 // Once registered, provide ConnectivityReports for matching Networks
9036 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9037 synchronized (mNetworkForNetId) {
9038 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9039 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009040 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9041 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009042 matchingNetworks.add(nai);
9043 }
9044 }
9045 }
9046 for (final NetworkAgentInfo nai : matchingNetworks) {
9047 final ConnectivityReport report = nai.getConnectivityReport();
9048 if (report == null) {
9049 continue;
9050 }
9051 if (!checkConnectivityDiagnosticsPermissions(
9052 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9053 continue;
9054 }
9055
9056 try {
9057 cb.onConnectivityReportAvailable(report);
9058 } catch (RemoteException e) {
9059 // Exception while sending the ConnectivityReport. Move on to the next network.
9060 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009061 }
9062 }
9063
9064 private void handleUnregisterConnectivityDiagnosticsCallback(
9065 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9066 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009067 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009068
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009069 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9070 mConnectivityDiagnosticsCallbacks.remove(iCb);
9071 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009072 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9073 return;
9074 }
9075
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009076 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009077
Cody Kesting70fa2b22020-12-02 12:16:56 -08009078 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9079 // (if the Binder died)
9080 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9081 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009082 return;
9083 }
9084
Cody Kesting46cb1672020-03-04 13:35:20 -08009085 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9086 // incremented when the NetworkRequestInfo is created as part of
9087 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009088 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009089
Cody Kesting31f1ff62020-03-05 10:46:02 -08009090 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009091 }
9092
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009093 private void handleNetworkTestedWithExtras(
9094 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9095 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009096 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009097 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009098 final ConnectivityReport report =
9099 new ConnectivityReport(
9100 reportEvent.mNai.network,
9101 reportEvent.mTimestampMillis,
9102 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009103 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009104 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009105 nai.setConnectivityReport(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009106 final List<IConnectivityDiagnosticsCallback> results =
9107 getMatchingPermissionedCallbacks(nai);
9108 for (final IConnectivityDiagnosticsCallback cb : results) {
9109 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009110 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009111 } catch (RemoteException ex) {
9112 loge("Error invoking onConnectivityReport", ex);
9113 }
9114 }
9115 }
9116
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009117 private void handleDataStallSuspected(
9118 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9119 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009120 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009121 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009122 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009123 new DataStallReport(
9124 nai.network,
9125 timestampMillis,
9126 detectionMethod,
9127 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009128 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009129 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009130 final List<IConnectivityDiagnosticsCallback> results =
9131 getMatchingPermissionedCallbacks(nai);
9132 for (final IConnectivityDiagnosticsCallback cb : results) {
9133 try {
9134 cb.onDataStallSuspected(report);
9135 } catch (RemoteException ex) {
9136 loge("Error invoking onDataStallSuspected", ex);
9137 }
9138 }
9139 }
9140
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009141 private void handleNetworkConnectivityReported(
9142 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9143 final List<IConnectivityDiagnosticsCallback> results =
9144 getMatchingPermissionedCallbacks(nai);
9145 for (final IConnectivityDiagnosticsCallback cb : results) {
9146 try {
9147 cb.onNetworkConnectivityReported(nai.network, connectivity);
9148 } catch (RemoteException ex) {
9149 loge("Error invoking onNetworkConnectivityReported", ex);
9150 }
9151 }
9152 }
9153
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009154 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009155 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9156 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009157 sanitized.setUids(null);
9158 sanitized.setAdministratorUids(new int[0]);
9159 sanitized.setOwnerUid(Process.INVALID_UID);
9160 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009161 }
9162
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009163 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9164 @NonNull NetworkAgentInfo nai) {
9165 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009166 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009167 mConnectivityDiagnosticsCallbacks.entrySet()) {
9168 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9169 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
James Mattis64b8b0f2020-11-24 17:40:49 -08009170 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9171 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009172 if (checkConnectivityDiagnosticsPermissions(
9173 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009174 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009175 }
9176 }
9177 }
9178 return results;
9179 }
9180
Cody Kesting160ef392021-05-05 13:17:22 -07009181 private boolean hasLocationPermission(String packageName, int uid) {
9182 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9183 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9184 // call in a try-catch.
9185 try {
9186 if (!mLocationPermissionChecker.checkLocationPermission(
9187 packageName, null /* featureId */, uid, null /* message */)) {
9188 return false;
9189 }
9190 } catch (SecurityException e) {
9191 return false;
9192 }
9193
9194 return true;
9195 }
9196
9197 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9198 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
9199 if (virtual.supportsUnderlyingNetworks()
9200 && virtual.networkCapabilities.getOwnerUid() == uid
9201 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9202 return true;
9203 }
9204 }
9205
9206 return false;
9207 }
9208
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009209 @VisibleForTesting
9210 boolean checkConnectivityDiagnosticsPermissions(
9211 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9212 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9213 return true;
9214 }
9215
Cody Kesting160ef392021-05-05 13:17:22 -07009216 // Administrator UIDs also contains the Owner UID
9217 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9218 if (!CollectionUtils.contains(administratorUids, callbackUid)
9219 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009220 return false;
9221 }
9222
Cody Kesting160ef392021-05-05 13:17:22 -07009223 return hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009224 }
9225
Cody Kestingd199a9d2019-12-17 12:55:28 -08009226 @Override
9227 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009228 @NonNull IConnectivityDiagnosticsCallback callback,
9229 @NonNull NetworkRequest request,
9230 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009231 if (request.legacyType != TYPE_NONE) {
9232 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9233 + " Please use NetworkCapabilities instead.");
9234 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009235 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009236 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009237
9238 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9239 // and administrator uids to be safe.
9240 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009241 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009242
9243 final NetworkRequest requestWithId =
9244 new NetworkRequest(
9245 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9246
9247 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9248 //
9249 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9250 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9251 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009252 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009253 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009254 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009255
9256 mConnectivityDiagnosticsHandler.sendMessage(
9257 mConnectivityDiagnosticsHandler.obtainMessage(
9258 ConnectivityDiagnosticsHandler
9259 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9260 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009261 }
9262
9263 @Override
9264 public void unregisterConnectivityDiagnosticsCallback(
9265 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009266 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009267 mConnectivityDiagnosticsHandler.sendMessage(
9268 mConnectivityDiagnosticsHandler.obtainMessage(
9269 ConnectivityDiagnosticsHandler
9270 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009271 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009272 0,
9273 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009274 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009275
9276 @Override
9277 public void simulateDataStall(int detectionMethod, long timestampMillis,
9278 @NonNull Network network, @NonNull PersistableBundle extras) {
9279 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9280 android.Manifest.permission.NETWORK_STACK);
9281 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9282 if (!nc.hasTransport(TRANSPORT_TEST)) {
9283 throw new SecurityException("Data Stall simluation is only possible for test networks");
9284 }
9285
9286 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009287 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009288 throw new SecurityException("Data Stall simulation is only possible for network "
9289 + "creators");
9290 }
9291
Cody Kesting652e3ec2020-05-21 12:08:21 -07009292 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9293 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9294 // Data Stall information as a DataStallReportParcelable and passing to
9295 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9296 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009297 final DataStallReportParcelable p = new DataStallReportParcelable();
9298 p.timestampMillis = timestampMillis;
9299 p.detectionMethod = detectionMethod;
9300
9301 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9302 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9303 }
9304 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9305 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9306 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9307 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9308 }
9309
Serik Beketayevec8ad212020-12-07 22:43:07 -08009310 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009311 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009312
lucaslin66f44212021-02-23 01:12:55 +08009313 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9314 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009315 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009316 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009317 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009318 }
lucaslin37a16d92021-01-21 19:48:09 +08009319
9320 @Override
9321 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009322 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009323 nai.clatd.interfaceLinkStateChanged(iface, up);
9324 }
9325 }
9326
9327 @Override
9328 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009329 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009330 nai.clatd.interfaceRemoved(iface);
9331 }
lucaslin66f44212021-02-23 01:12:55 +08009332 }
9333 }
9334
lucaslin1a8b4c62021-01-21 02:02:55 +08009335 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9336
9337 /**
9338 * Class used for updating network activity tracking with netd and notify network activity
9339 * changes.
9340 */
9341 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009342 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009343 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009344 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009345 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9346 new RemoteCallbackList<>();
9347 // Indicate the current system default network activity is active or not.
9348 @GuardedBy("mActiveIdleTimers")
9349 private boolean mNetworkActive;
9350 @GuardedBy("mActiveIdleTimers")
9351 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9352 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009353
lucaslin1193a5d2021-01-21 02:04:15 +08009354 private class IdleTimerParams {
9355 public final int timeout;
9356 public final int transportType;
9357
9358 IdleTimerParams(int timeout, int transport) {
9359 this.timeout = timeout;
9360 this.transportType = transport;
9361 }
9362 }
9363
9364 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009365 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009366 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009367 mNetd = netd;
9368 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009369 }
9370
lucaslin66f44212021-02-23 01:12:55 +08009371 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9372 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9373 synchronized (mActiveIdleTimers) {
9374 mNetworkActive = active;
9375 // If there are no idle timers, it means that system is not monitoring
9376 // activity, so the system default network for those default network
9377 // unspecified apps is always considered active.
9378 //
9379 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9380 // any network activity change event. Whenever this event is received,
9381 // the mActiveIdleTimers should be always not empty. The legacy behavior
9382 // is no-op. Remove to refer to mNetworkActive only.
9383 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9384 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9385 }
9386 }
9387 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009388
lucaslin1193a5d2021-01-21 02:04:15 +08009389 // The network activity should only be updated from ConnectivityService handler thread
9390 // when mActiveIdleTimers lock is held.
9391 @GuardedBy("mActiveIdleTimers")
9392 private void reportNetworkActive() {
9393 final int length = mNetworkActivityListeners.beginBroadcast();
9394 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9395 try {
9396 for (int i = 0; i < length; i++) {
9397 try {
9398 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9399 } catch (RemoteException | RuntimeException e) {
9400 loge("Fail to send network activie to listener " + e);
9401 }
9402 }
9403 } finally {
9404 mNetworkActivityListeners.finishBroadcast();
9405 }
9406 }
9407
9408 @GuardedBy("mActiveIdleTimers")
9409 public void handleReportNetworkActivity() {
9410 synchronized (mActiveIdleTimers) {
9411 reportNetworkActive();
9412 }
9413 }
9414
lucaslin1a8b4c62021-01-21 02:02:55 +08009415 // This is deprecated and only to support legacy use cases.
9416 private int transportTypeToLegacyType(int type) {
9417 switch (type) {
9418 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009419 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009420 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009421 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009422 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009423 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009424 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009425 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009426 default:
9427 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9428 }
9429 return ConnectivityManager.TYPE_NONE;
9430 }
9431
9432 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9433 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9434 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9435 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9436 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9437 final long ident = Binder.clearCallingIdentity();
9438 try {
9439 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9440 RECEIVE_DATA_ACTIVITY_CHANGE,
9441 null /* resultReceiver */,
9442 null /* scheduler */,
9443 0 /* initialCode */,
9444 null /* initialData */,
9445 null /* initialExtra */);
9446 } finally {
9447 Binder.restoreCallingIdentity(ident);
9448 }
9449 }
9450
9451 /**
9452 * Setup data activity tracking for the given network.
9453 *
9454 * Every {@code setupDataActivityTracking} should be paired with a
9455 * {@link #removeDataActivityTracking} for cleanup.
9456 */
9457 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9458 final String iface = networkAgent.linkProperties.getInterfaceName();
9459
9460 final int timeout;
9461 final int type;
9462
9463 if (networkAgent.networkCapabilities.hasTransport(
9464 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9465 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009466 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009467 10);
9468 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9469 } else if (networkAgent.networkCapabilities.hasTransport(
9470 NetworkCapabilities.TRANSPORT_WIFI)) {
9471 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009472 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009473 15);
9474 type = NetworkCapabilities.TRANSPORT_WIFI;
9475 } else {
9476 return; // do not track any other networks
9477 }
9478
lucaslinb961efc2021-01-21 02:03:17 +08009479 updateRadioPowerState(true /* isActive */, type);
9480
lucaslin1a8b4c62021-01-21 02:02:55 +08009481 if (timeout > 0 && iface != null) {
9482 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009483 synchronized (mActiveIdleTimers) {
9484 // Networks start up.
9485 mNetworkActive = true;
9486 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9487 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9488 reportNetworkActive();
9489 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009490 } catch (Exception e) {
9491 // You shall not crash!
9492 loge("Exception in setupDataActivityTracking " + e);
9493 }
9494 }
9495 }
9496
9497 /**
9498 * Remove data activity tracking when network disconnects.
9499 */
9500 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9501 final String iface = networkAgent.linkProperties.getInterfaceName();
9502 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9503
lucaslinb961efc2021-01-21 02:03:17 +08009504 if (iface == null) return;
9505
9506 final int type;
9507 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9508 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9509 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9510 type = NetworkCapabilities.TRANSPORT_WIFI;
9511 } else {
9512 return; // do not track any other networks
9513 }
9514
9515 try {
9516 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +08009517 synchronized (mActiveIdleTimers) {
9518 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9519 // The call fails silently if no idle timer setup for this interface
9520 mNetd.idletimerRemoveInterface(iface, params.timeout,
9521 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +08009522 }
lucaslinb961efc2021-01-21 02:03:17 +08009523 } catch (Exception e) {
9524 // You shall not crash!
9525 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +08009526 }
9527 }
9528
9529 /**
9530 * Update data activity tracking when network state is updated.
9531 */
9532 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9533 NetworkAgentInfo oldNetwork) {
9534 if (newNetwork != null) {
9535 setupDataActivityTracking(newNetwork);
9536 }
9537 if (oldNetwork != null) {
9538 removeDataActivityTracking(oldNetwork);
9539 }
9540 }
lucaslinb961efc2021-01-21 02:03:17 +08009541
9542 private void updateRadioPowerState(boolean isActive, int transportType) {
9543 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9544 switch (transportType) {
9545 case NetworkCapabilities.TRANSPORT_CELLULAR:
9546 bs.reportMobileRadioPowerState(isActive, NO_UID);
9547 break;
9548 case NetworkCapabilities.TRANSPORT_WIFI:
9549 bs.reportWifiRadioPowerState(isActive, NO_UID);
9550 break;
9551 default:
9552 logw("Untracked transport type:" + transportType);
9553 }
9554 }
lucaslin1193a5d2021-01-21 02:04:15 +08009555
9556 public boolean isDefaultNetworkActive() {
9557 synchronized (mActiveIdleTimers) {
9558 // If there are no idle timers, it means that system is not monitoring activity,
9559 // so the default network is always considered active.
9560 //
9561 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9562 // tracking is disabled (negative idle timer value configured), or no active default
9563 // network. In the latter case, this reports active but it should report inactive.
9564 return mNetworkActive || mActiveIdleTimers.isEmpty();
9565 }
9566 }
9567
9568 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9569 mNetworkActivityListeners.register(l);
9570 }
9571
9572 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9573 mNetworkActivityListeners.unregister(l);
9574 }
lucaslin012f7a12021-01-21 02:04:35 +08009575
9576 public void dump(IndentingPrintWriter pw) {
9577 synchronized (mActiveIdleTimers) {
9578 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9579 pw.println("Idle timers:");
9580 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9581 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9582 final IdleTimerParams params = ent.getValue();
9583 pw.print(" timeout="); pw.print(params.timeout);
9584 pw.print(" type="); pw.println(params.transportType);
9585 }
9586 }
9587 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009588 }
James Mattis47db0582021-01-01 14:13:35 -08009589
Daniel Brightf9e945b2020-06-15 16:10:01 -07009590 /**
9591 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9592 *
9593 * @param socketInfo the socket information
9594 * @param callback the callback to register
9595 */
9596 @Override
9597 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9598 @NonNull final IQosCallback callback) {
9599 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9600 if (nai == null || nai.networkCapabilities == null) {
9601 try {
9602 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9603 } catch (final RemoteException ex) {
9604 loge("registerQosCallbackInternal: RemoteException", ex);
9605 }
9606 return;
9607 }
9608 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9609 }
9610
9611 /**
9612 * Register a {@link IQosCallback} with base {@link QosFilter}.
9613 *
9614 * @param filter the filter to register
9615 * @param callback the callback to register
9616 * @param nai the agent information related to the filter's network
9617 */
9618 @VisibleForTesting
9619 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9620 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9621 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9622 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9623
9624 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9625 enforceConnectivityRestrictedNetworksPermission();
9626 }
9627 mQosCallbackTracker.registerCallback(callback, filter, nai);
9628 }
9629
9630 /**
9631 * Unregisters the given callback.
9632 *
9633 * @param callback the callback to unregister
9634 */
9635 @Override
9636 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009637 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07009638 mQosCallbackTracker.unregisterCallback(callback);
9639 }
James Mattis47db0582021-01-01 14:13:35 -08009640
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009641 // Network preference per-profile and OEM network preferences can't be set at the same
9642 // time, because it is unclear what should happen if both preferences are active for
9643 // one given UID. To make it possible, the stack would have to clarify what would happen
9644 // in case both are active at the same time. The implementation may have to be adjusted
9645 // to implement the resulting rules. For example, a priority could be defined between them,
9646 // where the OEM preference would be considered less or more important than the enterprise
9647 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9648 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9649 // are set at the right level. Other solutions are possible, e.g. merging of the
9650 // preferences for the relevant UIDs.
9651 private static void throwConcurrentPreferenceException() {
9652 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9653 + "set OemNetworkPreference at the same time");
James Mattis45d81842021-01-10 14:24:24 -08009654 }
9655
9656 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +09009657 * Request that a user profile is put by default on a network matching a given preference.
9658 *
9659 * See the documentation for the individual preferences for a description of the supported
9660 * behaviors.
9661 *
9662 * @param profile the profile concerned.
9663 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9664 * constants.
9665 * @param listener an optional listener to listen for completion of the operation.
9666 */
9667 @Override
9668 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9669 @ConnectivityManager.ProfileNetworkPreference final int preference,
9670 @Nullable final IOnCompleteListener listener) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009671 Objects.requireNonNull(profile);
9672 PermissionUtils.enforceNetworkStackPermission(mContext);
9673 if (DBG) {
9674 log("setProfileNetworkPreference " + profile + " to " + preference);
9675 }
9676 if (profile.getIdentifier() < 0) {
9677 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9678 + "UserHandle.CURRENT not supported)");
9679 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +09009680 final UserManager um = mContext.getSystemService(UserManager.class);
9681 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009682 throw new IllegalArgumentException("Profile must be a managed profile");
9683 }
9684 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9685 // handler thread. However it is an immutable object, so reading the reference is
9686 // safe - it's just possible the value is slightly outdated. For the final check,
9687 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9688 // lot easier to understand, so opportunistically check it.
9689 if (!mOemNetworkPreferences.isEmpty()) {
9690 throwConcurrentPreferenceException();
9691 }
9692 final NetworkCapabilities nc;
9693 switch (preference) {
9694 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9695 nc = null;
9696 break;
9697 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9698 final UidRange uids = UidRange.createForUser(profile);
9699 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9700 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9701 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9702 break;
9703 default:
9704 throw new IllegalArgumentException(
9705 "Invalid preference in setProfileNetworkPreference");
9706 }
9707 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9708 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9709 }
9710
9711 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9712 @Nullable final NetworkCapabilities nc) {
9713 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9714 ensureRequestableCapabilities(nc);
9715 }
9716
9717 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9718 @NonNull final ProfileNetworkPreferences prefs) {
9719 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9720 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9721 // The NRI for a user should be comprised of two layers:
9722 // - The request for the capabilities
9723 // - The request for the default network, for fallback. Create an image of it to
9724 // have the correct UIDs in it (also a request can only be part of one NRI, because
9725 // of lookups in 1:1 associations like mNetworkRequests).
9726 // Note that denying a fallback can be implemented simply by not adding the second
9727 // request.
9728 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9729 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
James Mattisa117e282021-04-20 17:26:30 -07009730 nrs.add(createDefaultInternetRequestForTransport(
9731 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009732 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009733 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009734 result.add(nri);
9735 }
9736 return result;
9737 }
9738
9739 private void handleSetProfileNetworkPreference(
9740 @NonNull final ProfileNetworkPreferences.Preference preference,
9741 @Nullable final IOnCompleteListener listener) {
9742 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9743 // particular because it's not clear what preference should win in case both apply
9744 // to the same app.
9745 // The binder call has already checked this, but as mOemNetworkPreferences is only
9746 // touched on the handler thread, it's theoretically not impossible that it has changed
9747 // since.
9748 if (!mOemNetworkPreferences.isEmpty()) {
Chalard Jean0f57a492021-03-09 21:09:20 +09009749 // This may happen on a device with an OEM preference set when a user is removed.
9750 // In this case, it's safe to ignore. In particular this happens in the tests.
9751 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009752 return;
9753 }
9754
9755 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9756
9757 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
James Mattis20a4a8b2021-03-28 17:41:09 -07009758 mSystemNetworkRequestCounter.transact(
9759 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9760 () -> {
9761 final ArraySet<NetworkRequestInfo> nris =
9762 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9763 replaceDefaultNetworkRequestsForPreference(nris);
9764 });
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009765 // Finally, rematch.
9766 rematchAllNetworksAndRequests();
9767
9768 if (null != listener) {
9769 try {
9770 listener.onComplete();
9771 } catch (RemoteException e) {
9772 loge("Listener for setProfileNetworkPreference has died");
9773 }
9774 }
9775 }
9776
James Mattis45d81842021-01-10 14:24:24 -08009777 private void enforceAutomotiveDevice() {
9778 final boolean isAutomotiveDevice =
9779 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9780 if (!isAutomotiveDevice) {
9781 throw new UnsupportedOperationException(
9782 "setOemNetworkPreference() is only available on automotive devices.");
9783 }
9784 }
9785
9786 /**
9787 * Used by automotive devices to set the network preferences used to direct traffic at an
9788 * application level as per the given OemNetworkPreferences. An example use-case would be an
9789 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9790 * vehicle via a particular network.
9791 *
9792 * Calling this will overwrite the existing preference.
9793 *
James Mattisda32cfe2021-01-26 16:23:52 -08009794 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +09009795 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -08009796 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -08009797 */
James Mattis47db0582021-01-01 14:13:35 -08009798 @Override
James Mattis45d81842021-01-10 14:24:24 -08009799 public void setOemNetworkPreference(
9800 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +09009801 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -08009802
James Mattis45d81842021-01-10 14:24:24 -08009803 enforceAutomotiveDevice();
James Mattisda32cfe2021-01-26 16:23:52 -08009804 enforceOemNetworkPreferencesPermission();
James Mattis45d81842021-01-10 14:24:24 -08009805
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009806 if (!mProfileNetworkPreferences.isEmpty()) {
9807 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9808 // handler thread. However it is an immutable object, so reading the reference is
9809 // safe - it's just possible the value is slightly outdated. For the final check,
9810 // see #handleSetOemPreference. But if this can be caught here it is a
9811 // lot easier to understand, so opportunistically check it.
9812 throwConcurrentPreferenceException();
9813 }
9814
James Mattis45d81842021-01-10 14:24:24 -08009815 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9816 validateOemNetworkPreferences(preference);
9817 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9818 new Pair<>(preference, listener)));
9819 }
9820
9821 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9822 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9823 : preference.getNetworkPreferences().values()) {
9824 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9825 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9826 throw new IllegalArgumentException(msg);
9827 }
9828 }
9829 }
9830
9831 private void handleSetOemNetworkPreference(
9832 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +09009833 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -08009834 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9835 if (DBG) {
9836 log("set OEM network preferences :" + preference.toString());
9837 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009838 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9839 // particular because it's not clear what preference should win in case both apply
9840 // to the same app.
9841 // The binder call has already checked this, but as mOemNetworkPreferences is only
9842 // touched on the handler thread, it's theoretically not impossible that it has changed
9843 // since.
9844 if (!mProfileNetworkPreferences.isEmpty()) {
9845 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9846 return;
9847 }
9848
James Mattiscb1e0362021-04-06 17:07:42 -07009849 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
James Mattis20a4a8b2021-03-28 17:41:09 -07009850 final int uniquePreferenceCount = new ArraySet<>(
9851 preference.getNetworkPreferences().values()).size();
9852 mSystemNetworkRequestCounter.transact(
9853 mDeps.getCallingUid(), uniquePreferenceCount,
9854 () -> {
9855 final ArraySet<NetworkRequestInfo> nris =
9856 new OemNetworkRequestFactory()
9857 .createNrisFromOemNetworkPreferences(preference);
9858 replaceDefaultNetworkRequestsForPreference(nris);
9859 });
James Mattis45d81842021-01-10 14:24:24 -08009860 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -08009861
9862 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009863 try {
9864 listener.onComplete();
9865 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -08009866 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009867 }
James Mattis45d81842021-01-10 14:24:24 -08009868 }
9869 }
9870
Chalard Jean17215832021-03-01 14:06:28 +09009871 private void replaceDefaultNetworkRequestsForPreference(
James Mattis3ce3d3c2021-02-09 18:18:28 -08009872 @NonNull final Set<NetworkRequestInfo> nris) {
James Mattisc12c1f12021-02-20 14:40:51 -08009873 // Pass in a defensive copy as this collection will be updated on remove.
9874 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
James Mattis3ce3d3c2021-02-09 18:18:28 -08009875 addPerAppDefaultNetworkRequests(nris);
James Mattis45d81842021-01-10 14:24:24 -08009876 }
9877
James Mattis3ce3d3c2021-02-09 18:18:28 -08009878 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9879 ensureRunningOnConnectivityServiceThread();
9880 mDefaultNetworkRequests.addAll(nris);
9881 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9882 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -08009883 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
James Mattis20a4a8b2021-03-28 17:41:09 -07009884 mSystemNetworkRequestCounter.transact(
9885 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9886 () -> {
9887 nrisToRegister.addAll(
9888 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9889 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9890 handleRegisterNetworkRequests(nrisToRegister);
9891 });
James Mattis3ce3d3c2021-02-09 18:18:28 -08009892 }
9893
9894 /**
9895 * All current requests that are tracking the default network need to be assessed as to whether
9896 * or not the current set of per-application default requests will be changing their default
9897 * network. If so, those requests will need to be updated so that they will send callbacks for
9898 * default network changes at the appropriate time. Additionally, those requests tracking the
9899 * default that were previously updated by this flow will need to be reassessed.
9900 * @return the nris which will need to be updated.
9901 */
9902 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9903 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9904 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9905 // same nri in the map's values for each of its NetworkRequest objects.
9906 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -08009907 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009908 // Include this nri if it is currently being tracked.
9909 if (isPerAppTrackedNri(nri)) {
9910 defaultCallbackRequests.add(nri);
9911 continue;
9912 }
9913 // We only track callbacks for requests tracking the default.
9914 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9915 continue;
9916 }
9917 // Include this nri if it will be tracked by the new per-app default requests.
9918 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009919 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08009920 if (isNriGoingToBeTracked) {
9921 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -08009922 }
9923 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08009924 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -08009925 }
9926
James Mattis3ce3d3c2021-02-09 18:18:28 -08009927 /**
9928 * Create nris for those network requests that are currently tracking the default network that
9929 * are being controlled by a per-application default.
9930 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
9931 * foundation when creating the nri. Important items include the calling uid's original
9932 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
9933 * requests are assumed to have already been validated as needing to be updated.
9934 * @return the Set of nris to use when registering network requests.
9935 */
9936 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
9937 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
9938 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
9939 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
9940 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009941 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08009942
9943 // If this nri is not being tracked, the change it back to an untracked nri.
9944 if (trackingNri == mDefaultRequest) {
9945 callbackRequestsToRegister.add(new NetworkRequestInfo(
9946 callbackRequest,
9947 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
9948 continue;
9949 }
9950
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009951 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -08009952 callbackRequestsToRegister.add(new NetworkRequestInfo(
9953 callbackRequest,
9954 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009955 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09009956 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -08009957 }
9958 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -08009959 }
9960
Chalard Jean17215832021-03-01 14:06:28 +09009961 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
9962 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +09009963 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009964 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +09009965 }
9966 }
9967
James Mattis45d81842021-01-10 14:24:24 -08009968 /**
9969 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
9970 */
9971 @VisibleForTesting
9972 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009973 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -08009974 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009975 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -08009976 final SparseArray<Set<Integer>> uids =
9977 createUidsFromOemNetworkPreferences(preference);
9978 for (int i = 0; i < uids.size(); i++) {
9979 final int key = uids.keyAt(i);
9980 final Set<Integer> value = uids.valueAt(i);
9981 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
9982 // No need to add an nri without any requests.
9983 if (0 == nri.mRequests.size()) {
9984 continue;
9985 }
9986 nris.add(nri);
9987 }
9988
9989 return nris;
9990 }
9991
9992 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
9993 @NonNull final OemNetworkPreferences preference) {
9994 final SparseArray<Set<Integer>> uids = new SparseArray<>();
9995 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -08009996 final List<UserHandle> users =
9997 mContext.getSystemService(UserManager.class).getUserHandles(true);
9998 if (null == users || users.size() == 0) {
9999 if (VDBG || DDBG) {
10000 log("No users currently available for setting the OEM network preference.");
10001 }
10002 return uids;
10003 }
James Mattis45d81842021-01-10 14:24:24 -080010004 for (final Map.Entry<String, Integer> entry :
10005 preference.getNetworkPreferences().entrySet()) {
10006 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
10007 try {
10008 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
10009 if (!uids.contains(pref)) {
10010 uids.put(pref, new ArraySet<>());
10011 }
James Mattisae9aeb02021-03-01 17:09:11 -080010012 for (final UserHandle ui : users) {
10013 // Add the rules for all users as this policy is device wide.
Chiachang Wang612cc032021-04-08 11:10:51 +080010014 uids.get(pref).add(ui.getUid(uid));
James Mattisae9aeb02021-03-01 17:09:11 -080010015 }
James Mattis45d81842021-01-10 14:24:24 -080010016 } catch (PackageManager.NameNotFoundException e) {
10017 // Although this may seem like an error scenario, it is ok that uninstalled
10018 // packages are sent on a network preference as the system will watch for
10019 // package installations associated with this network preference and update
10020 // accordingly. This is done so as to minimize race conditions on app install.
James Mattis45d81842021-01-10 14:24:24 -080010021 continue;
10022 }
10023 }
10024 return uids;
10025 }
10026
10027 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10028 @OemNetworkPreferences.OemNetworkPreference final int preference,
10029 @NonNull final Set<Integer> uids) {
10030 final List<NetworkRequest> requests = new ArrayList<>();
10031 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10032 switch (preference) {
10033 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10034 requests.add(createUnmeteredNetworkRequest());
10035 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010036 requests.add(createDefaultInternetRequestForTransport(
10037 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010038 break;
10039 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10040 requests.add(createUnmeteredNetworkRequest());
10041 requests.add(createOemPaidNetworkRequest());
10042 break;
10043 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10044 requests.add(createOemPaidNetworkRequest());
10045 break;
10046 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10047 requests.add(createOemPrivateNetworkRequest());
10048 break;
10049 default:
10050 // This should never happen.
10051 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10052 + " called with invalid preference of " + preference);
10053 }
10054
Chalard Jean17215832021-03-01 14:06:28 +090010055 final ArraySet ranges = new ArraySet<Integer>();
10056 for (final int uid : uids) {
10057 ranges.add(new UidRange(uid, uid));
10058 }
10059 setNetworkRequestUids(requests, ranges);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010060 return new NetworkRequestInfo(Process.myUid(), requests);
James Mattis45d81842021-01-10 14:24:24 -080010061 }
10062
10063 private NetworkRequest createUnmeteredNetworkRequest() {
10064 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10065 .addCapability(NET_CAPABILITY_NOT_METERED)
10066 .addCapability(NET_CAPABILITY_VALIDATED);
10067 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10068 }
10069
10070 private NetworkRequest createOemPaidNetworkRequest() {
10071 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10072 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10073 .addCapability(NET_CAPABILITY_OEM_PAID)
10074 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10075 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10076 }
10077
10078 private NetworkRequest createOemPrivateNetworkRequest() {
10079 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10080 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10081 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10082 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10083 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10084 }
10085
10086 private NetworkCapabilities createDefaultPerAppNetCap() {
10087 final NetworkCapabilities netCap = new NetworkCapabilities();
10088 netCap.addCapability(NET_CAPABILITY_INTERNET);
10089 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10090 return netCap;
10091 }
James Mattis47db0582021-01-01 14:13:35 -080010092 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010093}