blob: 051a00bde43e5fb027f2976c73820a98fd961102 [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;
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -080090import android.annotation.BoolRes;
Lorenzo Colittibad9d912019-04-12 10:48:06 +000091import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -080092import android.annotation.Nullable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080093import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -080094import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -070095import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +080096import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070097import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +080098import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -080099import android.content.ContentResolver;
100import android.content.Context;
101import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700102import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800103import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700104import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900105import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900106import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700107import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800108import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800109import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800110import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900111import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800112import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900113import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900114import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800115import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900116import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800117import android.net.DnsResolverServiceManager;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900118import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800119import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800121import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800122import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800123import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900124import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900125import android.net.INetworkMonitor;
126import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900127import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900128import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700129import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800130import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900131import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900132import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900133import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800134import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100135import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800136import android.net.NativeNetworkConfig;
137import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800138import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700139import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700140import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900141import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700142import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800143import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700144import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900145import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900146import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000147import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900148import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700149import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900150import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700151import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900152import android.net.NetworkStack;
Remi NGUYEN VANef59a212019-02-14 18:04:20 +0900153import android.net.NetworkStackClient;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700154import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800155import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900156import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700157import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000158import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800159import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900160import android.net.PrivateDnsConfigParcel;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400161import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700162import android.net.QosCallbackException;
163import android.net.QosFilter;
164import android.net.QosSocketFilter;
165import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700166import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800167import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800168import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800169import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900170import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400171import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800172import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800173import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400174import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800175import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900176import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900177import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900178import android.net.metrics.NetworkEvent;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700179import android.net.netlink.InetDiagMessage;
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;
Remi NGUYEN VAN6e82be42019-01-29 15:38:52 +0900186import android.net.util.NetdService;
lucaslinb961efc2021-01-21 02:03:17 +0800187import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800188import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800189import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700190import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800191import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700192import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700193import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800194import android.os.Looper;
195import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700196import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700197import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900198import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800199import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700200import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700201import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800202import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700203import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900204import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900205import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700206import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700207import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400208import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800209import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900210import android.sysprop.NetworkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -0700211import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700212import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800213import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900214import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000215import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600216import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900217import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700218import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700219import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900221import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400222import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400223import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700224import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900225import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800226import com.android.modules.utils.BasicShellCommandHandler;
lucaslin66f44212021-02-23 01:12:55 +0800227import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900228import com.android.net.module.util.CollectionUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900229import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
230import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900231import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800232import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800233import com.android.net.module.util.PermissionUtils;
Chalard Jean7284daa2019-05-30 14:58:29 +0900234import com.android.server.connectivity.AutodestructReference;
Erik Kline32120082017-12-13 19:40:49 +0900235import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500236import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900237import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900238import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100239import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700240import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700241import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600242import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900243import com.android.server.connectivity.NetworkNotificationManager;
244import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900245import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900246import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700247import com.android.server.connectivity.PermissionMonitor;
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900248import com.android.server.connectivity.ProfileNetworkPreferences;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900249import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700250import com.android.server.connectivity.QosCallbackTracker;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600251
Josh Gao461a1222020-06-16 15:58:11 -0700252import libcore.io.IoUtils;
253
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254import java.io.FileDescriptor;
255import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700256import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700257import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900258import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700259import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700260import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700261import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700262import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800263import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900264import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800265import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700266import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700267import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700268import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700269import java.util.Map;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700270import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900271import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600272import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900273import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600274import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900275import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800276
277/**
278 * @hide
279 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800280public class ConnectivityService extends IConnectivityManager.Stub
281 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900282 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800283
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900284 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900285 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900286 private static final String NETWORK_ARG = "networks";
287 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900288
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900289 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900290 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
291 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800292
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900293 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700294
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100295 /**
296 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
297 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800298 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100299 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
300 * (preferably via runtime resource overlays).
301 */
302 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
303 "http://connectivitycheck.gstatic.com/generate_204";
304
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700305 // TODO: create better separation between radio types and network types
306
Robert Greenwalt2034b912009-08-12 16:08:25 -0700307 // how long to wait before switching back to a radio's default network
308 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
309 // system property that can override the above value
310 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
311 "android.telephony.apn-restore";
312
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900313 // How long to wait before putting up a "This network doesn't have an Internet connection,
314 // connect anyway?" dialog after the user selects a network that doesn't validate.
315 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
316
junyulai0ac374f2020-12-14 18:41:52 +0800317 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900318 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
319 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800320 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700321
322 // The maximum number of network request allowed per uid before an exception is thrown.
323 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
324
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900325 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700326 @VisibleForTesting
327 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900328
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900329 @VisibleForTesting
330 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800331 @VisibleForTesting
332 protected int mNascentDelayMs;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900333
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800334 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800335 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800336 private final int mReleasePendingIntentDelayMs;
337
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900338 private MockableSystemProperties mSystemProperties;
339
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000340 @VisibleForTesting
341 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700342
Daniel Brightf9e945b2020-06-15 16:10:01 -0700343 private final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700344 @VisibleForTesting
345 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700346
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900347 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700348
junyulaif2c67e42018-08-07 19:50:45 +0800349 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000350 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
351 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800352 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000353 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800354
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900355 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900356 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000357 // The Context is created for UserHandle.ALL.
358 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900359 private final Dependencies mDeps;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700360 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700361 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800362
Chenbo Feng15416292018-11-08 17:36:21 -0800363 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800364 protected IDnsResolver mDnsResolver;
365 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800366 protected INetd mNetd;
junyulaie7c7d2a2021-01-26 15:29:15 +0800367 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800368 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800369 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700370
Benedict Wong493e04b2018-11-09 14:45:34 -0800371 /**
372 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
373 * instances.
374 */
375 @GuardedBy("mTNSLock")
376 private TestNetworkService mTNS;
377
378 private final Object mTNSLock = new Object();
379
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700380 private String mCurrentTcpBufferSizes;
381
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900382 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800383 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900384
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500385 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400386 // Tear down networks that have no chance (e.g. even if validated) of becoming
387 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500388 // all networks have been rematched against all NetworkRequests.
389 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400390 // Don't reap networks. This should be passed when some networks have not yet been
391 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500392 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900393 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500394
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900395 private enum UnneededFor {
396 LINGER, // Determine whether this network is unneeded and should be lingered.
397 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
398 }
399
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700400 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700401 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700402 * from one net to another. Clear happens when we get a new
403 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
404 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700405 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700406 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700407
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700408 /**
409 * used internally to reload global proxy settings
410 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700411 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700412
Robert Greenwalt34848c02011-03-25 13:09:25 -0700413 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400414 * PAC manager has received new port.
415 */
416 private static final int EVENT_PROXY_HAS_CHANGED = 16;
417
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700418 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900419 * used internally when registering NetworkProviders
420 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700421 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900422 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700423
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700424 /**
425 * used internally when registering NetworkAgents
426 * obj = Messenger
427 */
428 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
429
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700430 /**
431 * used to add a network request
432 * includes a NetworkRequestInfo
433 */
434 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
435
436 /**
437 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900438 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700439 * cancel it.
440 * includes a NetworkRequestInfo
441 */
442 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
443
444 /**
445 * used to add a network listener - no request
446 * includes a NetworkRequestInfo
447 */
448 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
449
450 /**
451 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400452 * arg1 = UID of caller
453 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700454 */
455 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
456
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700457 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900458 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700459 * obj = Messenger
460 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900461 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700462
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700463 /**
464 * used internally to expire a wakelock when transitioning
465 * from one net to another. Expire happens when we fail to find
466 * a new network (typically after 1 minute) -
467 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
468 * a replacement network.
469 */
470 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
471
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700472 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800473 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400474 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800475 */
476 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
477
478 /**
479 * used to remove a pending intent and its associated network request.
480 * arg1 = UID of caller
481 * obj = PendingIntent
482 */
483 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
484
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900485 /**
486 * used to specify whether a network should be used even if unvalidated.
487 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
488 * arg2 = whether to remember this choice in the future (1 or 0)
489 * obj = network
490 */
491 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
492
493 /**
494 * used to ask the user to confirm a connection to an unvalidated network.
495 * obj = network
496 */
497 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700498
Erik Kline05f2b402015-04-30 12:58:40 +0900499 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700500 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900501 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700502 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900503
Paul Jensenc8873fc2015-06-17 14:15:39 -0400504 /**
505 * used to add a network listener with a pending intent
506 * obj = NetworkRequestInfo
507 */
508 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
509
Hugo Benichid6b510a2017-04-06 17:22:18 +0900510 /**
511 * used to specify whether a network should not be penalized when it becomes unvalidated.
512 */
513 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
514
515 /**
516 * used to trigger revalidation of a network.
517 */
518 private static final int EVENT_REVALIDATE_NETWORK = 36;
519
Erik Kline31b4a9e2018-01-11 21:07:29 +0900520 // Handle changes in Private DNS settings.
521 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
522
dalyk1720e542018-03-05 12:42:22 -0500523 // Handle private DNS validation status updates.
524 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
525
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900526 /**
527 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
528 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800529 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
530 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
531 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900532 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900533 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900534
535 /**
536 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
537 * config was resolved.
538 * obj = PrivateDnsConfig
539 * arg2 = netid
540 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900541 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900542
543 /**
544 * Request ConnectivityService display provisioning notification.
545 * arg1 = Whether to make the notification visible.
546 * arg2 = NetID.
547 * obj = Intent to be launched when notification selected by user, null if !arg1.
548 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900549 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900550
551 /**
lucaslin2240ef62019-03-12 13:08:03 +0800552 * Used to specify whether a network should be used even if connectivity is partial.
553 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
554 * false)
555 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
556 * obj = network
557 */
lucaslin444d43a2020-02-20 16:56:59 +0800558 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800559
560 /**
lucasline117e2e2019-10-22 18:27:33 +0800561 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
562 * Both of the arguments are bitmasks, and the value of bits come from
563 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
564 * arg1 = A bitmask to describe which probes are completed.
565 * arg2 = A bitmask to describe which probes are successful.
566 */
lucaslin444d43a2020-02-20 16:56:59 +0800567 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800568
569 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900570 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
571 * arg1 = unused
572 * arg2 = netId
573 * obj = captive portal data
574 */
lucaslin444d43a2020-02-20 16:56:59 +0800575 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900576
577 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900578 * Used by setRequireVpnForUids.
579 * arg1 = whether the specified UID ranges are required to use a VPN.
580 * obj = Array of UidRange objects.
581 */
582 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
583
584 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900585 * Used internally when setting the default networks for OemNetworkPreferences.
586 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800587 */
588 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
589
590 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800591 * Used to indicate the system default network becomes active.
592 */
593 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
594
595 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900596 * Used internally when setting a network preference for a user profile.
597 * obj = Pair<ProfileNetworkPreference, Listener>
598 */
599 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
600
601 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000602 * Event to specify that reasons for why an uid is blocked changed.
603 * arg1 = uid
604 * arg2 = blockedReasons
605 */
606 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
607
608 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900609 * Event to register a new network offer
610 * obj = NetworkOffer
611 */
612 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
613
614 /**
615 * Event to unregister an existing network offer
616 * obj = INetworkOfferCallback
617 */
618 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
619
620 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900621 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
622 * should be shown.
623 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900624 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900625
626 /**
627 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
628 * should be hidden.
629 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900630 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900631
Hugo Benichi47011212017-03-30 10:46:05 +0900632 private static String eventName(int what) {
633 return sMagicDecoderRing.get(what, Integer.toString(what));
634 }
635
paulhua10d8212020-11-10 15:32:56 +0800636 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900637 final DnsResolverServiceManager dsm = context.getSystemService(
638 DnsResolverServiceManager.class);
639 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800640 }
641
Cody Kesting73708bf2019-12-18 10:57:50 -0800642 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900643 @VisibleForTesting
644 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700645 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700646 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700647 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700648 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800649 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
650 @VisibleForTesting
651 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
652
Erik Kline32120082017-12-13 19:40:49 +0900653 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900654 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700655
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400656 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800657 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400658
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700659 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800660 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700661
Chalard Jean5d70ba42018-06-07 16:44:04 +0900662 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
663 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000664 @VisibleForTesting
665 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400666
Erik Kline05f2b402015-04-30 12:58:40 +0900667 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700668
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400669 private UserManager mUserManager;
670
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700671 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900672 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700673
Valentin Iftime9fa35092019-09-24 13:32:13 +0200674 private Set<String> mWolSupportedInterfaces;
675
Roshan Pius08c94fb2020-01-16 12:17:17 -0800676 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800677 private final AppOpsManager mAppOpsManager;
678
679 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400680
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900681 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700682 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900683 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900684 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900685
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700686 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800687 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700688
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900689 // Sequence number for NetworkProvider IDs.
690 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
691 NetworkProvider.FIRST_PROVIDER_ID);
692
Erik Klineedf878b2015-07-09 18:24:03 +0900693 // NetworkRequest activity String log entries.
694 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
695 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
696
Hugo Benichid159fdd2016-07-11 11:05:12 +0900697 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900698 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900699 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
700
Hugo Benichi47011212017-03-30 10:46:05 +0900701 private static final int MAX_WAKELOCK_LOGS = 20;
702 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900703 private int mTotalWakelockAcquisitions = 0;
704 private int mTotalWakelockReleases = 0;
705 private long mTotalWakelockDurationMs = 0;
706 private long mMaxWakelockDurationMs = 0;
707 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900708
Hugo Benichi208c0102016-07-28 17:53:06 +0900709 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900710
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700711 @GuardedBy("mBandwidthRequests")
712 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
713
Erik Kline95ecfee2016-10-02 18:02:14 +0900714 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900715 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900716
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900717 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800718 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
719 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800720
Robert Greenwalt802c1102014-06-02 15:32:02 -0700721 /**
722 * Implements support for the legacy "one network per network type" model.
723 *
724 * We used to have a static array of NetworkStateTrackers, one for each
725 * network type, but that doesn't work any more now that we can have,
726 * for example, more that one wifi network. This class stores all the
727 * NetworkAgentInfo objects that support a given type, but the legacy
728 * API will only see the first one.
729 *
730 * It serves two main purposes:
731 *
732 * 1. Provide information about "the network for a given type" (since this
733 * API only supports one).
734 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
735 * the first network for a given type changes, or if the default network
736 * changes.
737 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900738 @VisibleForTesting
739 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900740
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900741 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900742 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900743
Robert Greenwalt802c1102014-06-02 15:32:02 -0700744 /**
745 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
746 * Each list holds references to all NetworkAgentInfos that are used to
747 * satisfy requests for that network type.
748 *
749 * This array is built out at startup such that an unsupported network
750 * doesn't get an ArrayList instance, making this a tristate:
751 * unsupported, supported but not active and active.
752 *
753 * The actual lists are populated when we scan the network types that
754 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900755 *
756 * Threading model:
757 * - addSupportedType() is only called in the constructor
758 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
759 * They are therefore not thread-safe with respect to each other.
760 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
761 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900762 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900763 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700764 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900765 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900766 @NonNull
767 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700768
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900769 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
770 // an entry have no timer (equivalent to -1). Lazily loaded.
771 @NonNull
772 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
773
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900774 LegacyTypeTracker(@NonNull ConnectivityService service) {
775 mService = service;
776 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700777 }
778
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900779 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
780 final PackageManager pm = ctx.getPackageManager();
781 if (pm.hasSystemFeature(FEATURE_WIFI)) {
782 addSupportedType(TYPE_WIFI);
783 }
784 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
785 addSupportedType(TYPE_WIFI_P2P);
786 }
787 if (tm.isDataCapable()) {
788 // Telephony does not have granular support for these types: they are either all
789 // supported, or none is supported
790 addSupportedType(TYPE_MOBILE);
791 addSupportedType(TYPE_MOBILE_MMS);
792 addSupportedType(TYPE_MOBILE_SUPL);
793 addSupportedType(TYPE_MOBILE_DUN);
794 addSupportedType(TYPE_MOBILE_HIPRI);
795 addSupportedType(TYPE_MOBILE_FOTA);
796 addSupportedType(TYPE_MOBILE_IMS);
797 addSupportedType(TYPE_MOBILE_CBS);
798 addSupportedType(TYPE_MOBILE_IA);
799 addSupportedType(TYPE_MOBILE_EMERGENCY);
800 }
801 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
802 addSupportedType(TYPE_BLUETOOTH);
803 }
804 if (pm.hasSystemFeature(FEATURE_WATCH)) {
805 // TYPE_PROXY is only used on Wear
806 addSupportedType(TYPE_PROXY);
807 }
808 // Ethernet is often not specified in the configs, although many devices can use it via
809 // USB host adapters. Add it as long as the ethernet service is here.
810 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
811 addSupportedType(TYPE_ETHERNET);
812 }
813
814 // Always add TYPE_VPN as a supported type
815 addSupportedType(TYPE_VPN);
816 }
817
818 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700819 if (mTypeLists[type] != null) {
820 throw new IllegalStateException(
821 "legacy list for type " + type + "already initialized");
822 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900823 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700824 }
825
Robert Greenwalt802c1102014-06-02 15:32:02 -0700826 public boolean isTypeSupported(int type) {
827 return isNetworkTypeValid(type) && mTypeLists[type] != null;
828 }
829
830 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900831 synchronized (mTypeLists) {
832 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
833 return mTypeLists[type].get(0);
834 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700835 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900836 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700837 }
838
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900839 public int getRestoreTimerForType(int type) {
840 synchronized (mTypeLists) {
841 if (mRestoreTimers == null) {
842 mRestoreTimers = loadRestoreTimers();
843 }
844 return mRestoreTimers.getOrDefault(type, -1);
845 }
846 }
847
848 private ArrayMap<Integer, Integer> loadRestoreTimers() {
849 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900850 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900851 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
852 for (final String config : configs) {
853 final String[] splits = TextUtils.split(config, ",");
854 if (splits.length != 2) {
855 logwtf("Invalid restore timer token count: " + config);
856 continue;
857 }
858 try {
859 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
860 } catch (NumberFormatException e) {
861 logwtf("Invalid restore timer number format: " + config, e);
862 }
863 }
864 return ret;
865 }
866
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700867 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900868 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900869 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900870 log("Sending " + state
871 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900872 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900873 }
874 }
875
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900876 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
877 // network type, to preserve previous behaviour.
878 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
879 if (vpnNai != mService.getLegacyLockdownNai()) return;
880
881 if (vpnNai.declaredUnderlyingNetworks == null
882 || vpnNai.declaredUnderlyingNetworks.length != 1) {
883 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
884 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
885 return;
886 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900887 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900888 vpnNai.declaredUnderlyingNetworks[0]);
889 if (underlyingNai == null) return;
890
891 final int type = underlyingNai.networkInfo.getType();
892 final DetailedState state = DetailedState.CONNECTED;
893 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
894 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
895 }
896
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900897 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700898 public void add(int type, NetworkAgentInfo nai) {
899 if (!isTypeSupported(type)) {
900 return; // Invalid network type.
901 }
902 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
903
904 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
905 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700906 return;
907 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900908 synchronized (mTypeLists) {
909 list.add(nai);
910 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +0900911
Chalard Jean5b409c72021-02-04 13:12:59 +0900912 // Send a broadcast if this is the first network of its type or if it's the default.
913 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900914
915 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
916 // to preserve previous behaviour.
917 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +0900918 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900919 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
920 mService.sendLegacyNetworkBroadcast(nai, state, type);
921 }
922
923 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
924 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -0700925 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700926 }
927
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900928 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +0900929 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900930 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
931 if (list == null || list.isEmpty()) {
932 return;
933 }
Lorenzo Colitti49767722015-05-01 00:30:10 +0900934 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900935
Hugo Benichi389633f2016-06-21 09:48:07 +0900936 synchronized (mTypeLists) {
937 if (!list.remove(nai)) {
938 return;
939 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900940 }
941
Lorenzo Colitti49767722015-05-01 00:30:10 +0900942 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +0900943 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
944 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900945 }
946
947 if (!list.isEmpty() && wasFirstNetwork) {
948 if (DBG) log("Other network available for type " + type +
949 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +0900950 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +0900951 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900952 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +0900953 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900954 }
955 }
956
957 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +0900958 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
959 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -0700960 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +0900961 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -0700962 }
963 }
Robert Greenwalt94e22142014-07-30 16:31:24 -0700964
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700965 // send out another legacy broadcast - currently only used for suspend/unsuspend
966 // toggle
967 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +0900968 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700969 final DetailedState state = nai.networkInfo.getDetailedState();
970 for (int type = 0; type < mTypeLists.length; type++) {
971 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -0700972 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +0900973 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +0900974 if (isFirst || contains && isDefault) {
975 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900976 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700977 }
978 }
979 }
980
Robert Greenwalt94e22142014-07-30 16:31:24 -0700981 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900982 pw.println("mLegacyTypeTracker:");
983 pw.increaseIndent();
984 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -0700985 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900986 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -0700987 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900988 pw.println();
989 pw.println("Current state:");
990 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +0900991 synchronized (mTypeLists) {
992 for (int type = 0; type < mTypeLists.length; type++) {
993 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
994 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +0900995 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +0900996 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +0900997 }
998 }
999 pw.decreaseIndent();
1000 pw.decreaseIndent();
1001 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001002 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001003 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001004 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001005
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001006 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001007 /**
1008 * Helper class which parses out priority arguments and dumps sections according to their
1009 * priority. If priority arguments are omitted, function calls the legacy dump command.
1010 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001011 private class LocalPriorityDump {
1012 private static final String PRIORITY_ARG = "--dump-priority";
1013 private static final String PRIORITY_ARG_HIGH = "HIGH";
1014 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1015
1016 LocalPriorityDump() {}
1017
1018 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1019 doDump(fd, pw, new String[] {DIAG_ARG});
1020 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001021 }
1022
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001023 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1024 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001025 }
1026
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001027 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1028 if (args == null) {
1029 dumpNormal(fd, pw, args);
1030 return;
1031 }
1032
1033 String priority = null;
1034 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1035 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1036 argIndex++;
1037 priority = args[argIndex];
1038 }
1039 }
1040
1041 if (PRIORITY_ARG_HIGH.equals(priority)) {
1042 dumpHigh(fd, pw);
1043 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1044 dumpNormal(fd, pw, args);
1045 } else {
1046 // ConnectivityService publishes binder service using publishBinderService() with
1047 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
1048 // "--dump-priority" arguments to the service. Thus, dump both NORMAL and HIGH to
1049 // align the legacy design.
1050 // TODO: Integrate into signal dump.
1051 dumpNormal(fd, pw, args);
1052 pw.println();
1053 pw.println("DUMP OF SERVICE HIGH connectivity");
1054 pw.println();
1055 dumpHigh(fd, pw);
1056 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001057 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001058 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001059
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001060 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001061 * Keeps track of the number of requests made under different uids.
1062 */
1063 public static class PerUidCounter {
1064 private final int mMaxCountPerUid;
1065
1066 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001067 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001068 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001069 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001070
1071 /**
1072 * Constructor
1073 *
1074 * @param maxCountPerUid the maximum count per uid allowed
1075 */
1076 public PerUidCounter(final int maxCountPerUid) {
1077 mMaxCountPerUid = maxCountPerUid;
1078 }
1079
1080 /**
1081 * Increments the request count of the given uid. Throws an exception if the number
1082 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1083 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1084 *
1085 * @throws ServiceSpecificException with
1086 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1087 * the uid exceed the allowed number.
1088 *
1089 * @param uid the uid that the request was made under
1090 */
1091 public void incrementCountOrThrow(final int uid) {
1092 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001093 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001094 }
1095 }
1096
James Mattis20a4a8b2021-03-28 17:41:09 -07001097 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1098 final int newRequestCount =
1099 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1100 if (newRequestCount >= mMaxCountPerUid) {
1101 throw new ServiceSpecificException(
1102 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1103 }
1104 mUidToNetworkRequestCount.put(uid, newRequestCount);
1105 }
1106
Daniel Brightf9e945b2020-06-15 16:10:01 -07001107 /**
1108 * Decrements the request count of the given uid.
1109 *
1110 * @param uid the uid that the request was made under
1111 */
1112 public void decrementCount(final int uid) {
1113 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001114 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001115 }
1116 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001117
1118 private void decrementCount(final int uid, final int numToDecrement) {
1119 final int newRequestCount =
1120 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1121 if (newRequestCount < 0) {
1122 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1123 } else if (newRequestCount == 0) {
1124 mUidToNetworkRequestCount.delete(uid);
1125 } else {
1126 mUidToNetworkRequestCount.put(uid, newRequestCount);
1127 }
1128 }
1129
1130 /**
1131 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1132 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1133 * are used to create the new nris upon set. Therefore the request count limit can be
1134 * artificially hit. This method is used as a workaround for this particular case so that
1135 * the request counts are accounted for correctly.
1136 * @param uid the uid to adjust counts for
1137 * @param numOfNewRequests the new request count to account for
1138 * @param r the runnable to execute
1139 */
1140 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1141 // This should only be used on the handler thread as per all current and foreseen
1142 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1143 // no ref to the outer ConnectivityService.
1144 synchronized (mUidToNetworkRequestCount) {
1145 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1146 decrementCount(uid, reqCountOverage);
1147 r.run();
1148 incrementCountOrThrow(uid, reqCountOverage);
1149 }
1150 }
1151
1152 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1153 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1154 + numOfNewRequests;
1155 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1156 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1157 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001158 }
1159
1160 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001161 * Dependencies of ConnectivityService, for injection in tests.
1162 */
1163 @VisibleForTesting
1164 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001165 public int getCallingUid() {
1166 return Binder.getCallingUid();
1167 }
1168
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001169 /**
1170 * Get system properties to use in ConnectivityService.
1171 */
1172 public MockableSystemProperties getSystemProperties() {
1173 return new MockableSystemProperties();
1174 }
1175
1176 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001177 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1178 */
1179 public ConnectivityResources getResources(@NonNull Context ctx) {
1180 return new ConnectivityResources(ctx);
1181 }
1182
1183 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001184 * Create a HandlerThread to use in ConnectivityService.
1185 */
1186 public HandlerThread makeHandlerThread() {
1187 return new HandlerThread("ConnectivityServiceThread");
1188 }
1189
1190 /**
1191 * Get a reference to the NetworkStackClient.
1192 */
1193 public NetworkStackClient getNetworkStack() {
1194 return NetworkStackClient.getInstance();
1195 }
1196
1197 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001198 * @see ProxyTracker
1199 */
1200 public ProxyTracker makeProxyTracker(@NonNull Context context,
1201 @NonNull Handler connServiceHandler) {
1202 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1203 }
1204
1205 /**
1206 * @see NetIdManager
1207 */
1208 public NetIdManager makeNetIdManager() {
1209 return new NetIdManager();
1210 }
1211
1212 /**
1213 * @see NetworkUtils#queryUserAccess(int, int)
1214 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001215 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1216 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001217 }
1218
1219 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001220 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1221 * requires CAP_NET_ADMIN, which the unit tests do not have.
1222 */
1223 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1224 InetSocketAddress remote) {
1225 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1226 }
1227
1228 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001229 * @see MultinetworkPolicyTracker
1230 */
1231 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1232 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1233 return new MultinetworkPolicyTracker(c, h, r);
1234 }
1235
Aaron Huang330a4c02020-10-27 03:36:19 +08001236 /**
1237 * @see BatteryStatsManager
1238 */
1239 public void reportNetworkInterfaceForTransports(Context context, String iface,
1240 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001241 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001242 context.getSystemService(BatteryStatsManager.class);
1243 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1244 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001245
1246 public boolean getCellular464XlatEnabled() {
1247 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1248 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001249 }
1250
junyulaie7c7d2a2021-01-26 15:29:15 +08001251 public ConnectivityService(Context context) {
1252 this(context, getDnsResolver(context), new IpConnectivityLog(),
paulhu9a9f71b2020-12-29 18:15:13 +08001253 NetdService.getInstance(), new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001254 }
1255
1256 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001257 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1258 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001259 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001260
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001261 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001262 mSystemProperties = mDeps.getSystemProperties();
1263 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001264 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001265 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001266 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001267 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001268
Hugo Benichi208c0102016-07-28 17:53:06 +09001269 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001270 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001271 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1272 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001273 Process.myUid(), defaultInternetRequest, null,
Roshan Pius951c0032020-12-22 15:10:42 -08001274 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001275 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001276 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1277 mDefaultNetworkRequests.add(mDefaultRequest);
1278 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001279
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001280 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001281 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001282
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001283 // The default WiFi request is a background request so that apps using WiFi are
1284 // migrated to a better network (typically ethernet) when one comes up, instead
1285 // of staying on WiFi forever.
1286 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1287 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1288
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001289 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1290 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1291 NetworkRequest.Type.BACKGROUND_REQUEST);
1292
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001293 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001294 mHandlerThread.start();
1295 mHandler = new InternalHandler(mHandlerThread.getLooper());
1296 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001297 mConnectivityDiagnosticsHandler =
1298 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001299
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001300 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001301 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001302
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001303 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
junyulai0ac374f2020-12-14 18:41:52 +08001304 // TODO: Consider making the timer customizable.
1305 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09001306
junyulaie7c7d2a2021-01-26 15:29:15 +08001307 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001308 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001309 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001310 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001311
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001312 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001313 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001314 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1315 mLocationPermissionChecker = new LocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001316
Sudheer Shanka9967d462021-03-18 19:09:25 +00001317 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001318 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1319 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001320 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001321
1322 final PowerManager powerManager = (PowerManager) context.getSystemService(
1323 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001324 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001325 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001326
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001327 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1328 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001329 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001330 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001331 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001332 mProtectedNetworks.add(p);
1333 } else {
1334 if (DBG) loge("Ignoring protectedNetwork " + p);
1335 }
1336 }
1337
soma, kawata29444ae2019-05-23 09:30:40 +09001338 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1339
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001340 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001341
James Mattis02220e22021-03-13 19:27:21 -08001342 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001343 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001344 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001345 final IntentFilter userIntentFilter = new IntentFilter();
1346 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1347 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1348 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1349 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001350
James Mattis02220e22021-03-13 19:27:21 -08001351 // Listen to package add/removes for netd
1352 final IntentFilter packageIntentFilter = new IntentFilter();
1353 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1354 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1355 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1356 packageIntentFilter.addDataScheme("package");
1357 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001358 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001359
lucaslind5c2d072021-02-20 18:59:47 +08001360 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001361
lucaslin66f44212021-02-23 01:12:55 +08001362 mNetdCallback = new NetdCallback();
1363 try {
1364 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1365 } catch (RemoteException | ServiceSpecificException e) {
1366 loge("Error registering event listener :" + e);
1367 }
1368
Erik Kline05f2b402015-04-30 12:58:40 +09001369 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1370 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001371
junyulai7e06ad42019-03-04 22:45:36 +08001372 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001373 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001374 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001375
1376 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001377 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001378 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1379 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001380 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001381 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1382 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001383
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001384 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Erik Kline95ecfee2016-10-02 18:02:14 +09001385 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001386 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001387
Chiachang Wangc1215d32020-10-20 15:38:58 +08001388 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001389 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001390
Chalard Jean28018572020-12-21 18:36:52 +09001391 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1392 // request that doesn't allow fallback to the default network. It should never be visible
1393 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1394 // arguments like the handler or the DnsResolver.
1395 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001396 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001397 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001398 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001399 new LinkProperties(), new NetworkCapabilities(),
1400 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
1401 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID, mQosCallbackTracker,
1402 mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001403 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001404
Chalard Jean46adcf32018-04-18 20:18:38 +09001405 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001406 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1407 }
1408
1409 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1410 @NonNull final UidRange uids) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001411 final NetworkCapabilities netCap = new NetworkCapabilities();
1412 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001413 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001414 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Chiachang Wang8156c4e2021-03-19 00:45:39 +00001415 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
Chalard Jean46adcf32018-04-18 20:18:38 +09001416 return netCap;
1417 }
1418
James Mattis45d81842021-01-10 14:24:24 -08001419 private NetworkRequest createDefaultRequest() {
1420 return createDefaultInternetRequestForTransport(
1421 TYPE_NONE, NetworkRequest.Type.REQUEST);
1422 }
1423
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001424 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001425 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001426 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001427 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001428 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001429 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001430 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001431 netCap.addTransportType(transportType);
1432 }
James Mattis45d81842021-01-10 14:24:24 -08001433 return createNetworkRequest(type, netCap);
1434 }
1435
1436 private NetworkRequest createNetworkRequest(
1437 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001438 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001439 }
1440
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001441 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1442 NetworkRequest.Type type) {
1443 final NetworkCapabilities netCap = new NetworkCapabilities();
1444 netCap.clearAll();
1445 netCap.addCapability(capability);
1446 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1447 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1448 }
1449
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001450 // Used only for testing.
1451 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001452 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001453 // changing ContentResolver to make registerContentObserver non-final).
1454 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1455 // by subclassing SettingsObserver.
1456 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001457 void updateAlwaysOnNetworks() {
1458 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001459 }
1460
Erik Kline9a62f012018-03-21 07:18:33 -07001461 // See FakeSettingsProvider comment above.
1462 @VisibleForTesting
1463 void updatePrivateDnsSettings() {
1464 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1465 }
1466
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001467 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, @BoolRes int id) {
1468 final boolean enable = mContext.getResources().getBoolean(id);
1469 handleAlwaysOnNetworkRequest(networkRequest, enable);
1470 }
1471
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001472 private void handleAlwaysOnNetworkRequest(
1473 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001474 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001475 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001476 handleAlwaysOnNetworkRequest(networkRequest, enable);
1477 }
1478
1479 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001480 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001481 if (enable == isEnabled) {
1482 return; // Nothing to do.
1483 }
1484
1485 if (enable) {
1486 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001487 Process.myUid(), networkRequest, null, new Binder(),
Roshan Pius951c0032020-12-22 15:10:42 -08001488 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001489 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001490 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001491 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1492 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001493 }
1494 }
1495
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001496 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001497 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1498 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1499 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1500 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001501 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1502 R.bool.config_vehicleInternalNetworkAlwaysRequested);
1503 // TODO (b/183076074): remove legacy fallback after migrating overlays
1504 final boolean legacyAlwaysRequested = mContext.getResources().getBoolean(
1505 mContext.getResources().getIdentifier(
1506 "config_vehicleInternalNetworkAlwaysRequested", "bool", "android"));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001507 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001508 vehicleAlwaysRequested || legacyAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001509 }
1510
Erik Kline05f2b402015-04-30 12:58:40 +09001511 private void registerSettingsCallbacks() {
1512 // Watch for global HTTP proxy changes.
1513 mSettingsObserver.observe(
1514 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1515 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1516
1517 // Watch for whether or not to keep mobile data always on.
1518 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001519 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001520 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1521
1522 // Watch for whether or not to keep wifi always on.
1523 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001524 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001525 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Kline05f2b402015-04-30 12:58:40 +09001526 }
1527
Erik Kline31b4a9e2018-01-11 21:07:29 +09001528 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001529 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1530 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001531 }
1532 }
1533
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001534 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001535 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1536 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001537 return mNextNetworkRequestId++;
1538 }
1539
junyulai74f9a8b2018-06-13 15:00:37 +08001540 @VisibleForTesting
1541 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001542 if (network == null) {
1543 return null;
1544 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001545 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001546 }
1547
1548 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001549 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001550 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001551 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001552 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001553
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001554 // TODO: determine what to do when more than one VPN applies to |uid|.
1555 private NetworkAgentInfo getVpnForUid(int uid) {
1556 synchronized (mNetworkForNetId) {
1557 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1558 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1559 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1560 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001561 }
1562 }
1563 }
1564 return null;
1565 }
1566
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001567 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001568 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001569 final NetworkAgentInfo nai = getVpnForUid(uid);
1570 if (nai != null) return nai.declaredUnderlyingNetworks;
1571 return null;
1572 }
1573
Lorenzo Colittia7574052021-01-19 01:33:05 +09001574 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001575 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001576
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001577 final Network[] networks = getVpnUnderlyingNetworks(uid);
1578 if (networks != null) {
1579 // getUnderlyingNetworks() returns:
1580 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1581 // empty array => the VPN explicitly said "no default network".
1582 // non-empty array => the VPN specified one or more default networks; we use the
1583 // first one.
1584 if (networks.length > 0) {
1585 nai = getNetworkAgentInfoForNetwork(networks[0]);
1586 } else {
1587 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001588 }
1589 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001590 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001591 }
1592
1593 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001594 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001595 */
paulhu7aeba372020-12-30 00:42:19 +08001596 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1597 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001598 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001599 if (ignoreBlocked) {
1600 return false;
1601 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001602 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001603 final long ident = Binder.clearCallingIdentity();
1604 try {
1605 final boolean metered = nc == null ? true : nc.isMetered();
1606 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1607 } finally {
1608 Binder.restoreCallingIdentity(ident);
1609 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001610 }
1611
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001612 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001613 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1614 return;
1615 }
Hugo Benichi47011212017-03-30 10:46:05 +09001616 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001617 synchronized (mBlockedAppUids) {
1618 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001619 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001620 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001621 blocked = false;
1622 } else {
1623 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001624 }
1625 }
Hugo Benichi47011212017-03-30 10:46:05 +09001626 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1627 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1628 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001629 }
1630
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001631 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001632 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1633 return;
1634 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001635 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001636 final int requestId = nri.getActiveRequest() != null
1637 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001638 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001639 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001640 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001641 }
1642
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001643 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001644 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001645 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001646 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001647 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001648 @NonNull
1649 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1650 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001651 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1652 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1653 // but only exists if an app asks about them or requests them. Ensure the requesting app
1654 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001655 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001656 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1657 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1658 null /* extraInfo */);
1659 }
1660 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001661 return filtered;
1662 }
1663
1664 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1665 boolean ignoreBlocked) {
1666 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1667 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001668 }
1669
1670 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001671 * Return NetworkInfo for the active (i.e., connected) network interface.
1672 * It is assumed that at most one network is active at a time. If more
1673 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001674 * @return the info for the active network, or {@code null} if none is
1675 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001676 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001677 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001678 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001679 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001680 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001681 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1682 if (nai == null) return null;
1683 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1684 maybeLogBlockedNetworkInfo(networkInfo, uid);
1685 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001686 }
1687
Paul Jensen1f567382015-02-13 14:18:39 -05001688 @Override
1689 public Network getActiveNetwork() {
1690 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001691 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001692 }
1693
1694 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001695 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001696 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001697 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001698 }
1699
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001700 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001701 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1702 if (vpnNai != null) {
1703 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1704 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1705 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001706 }
Paul Jensen1f567382015-02-13 14:18:39 -05001707 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001708
James Mattis2516da32021-01-31 17:06:19 -08001709 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001710 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1711 ignoreBlocked)) {
1712 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001713 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001714 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001715 }
1716
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001717 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001718 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001719 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001720 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1721 if (nai == null) return null;
1722 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001723 }
1724
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001725 /** Returns a NetworkInfo object for a network that doesn't exist. */
1726 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1727 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1728 getNetworkTypeName(networkType), "" /* subtypeName */);
1729 info.setIsAvailable(true);
1730 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1731 // background data is restricted.
1732 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1733 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1734 ? DetailedState.BLOCKED
1735 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001736 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1737 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001738 return info;
1739 }
1740
Lorenzo Colittia7574052021-01-19 01:33:05 +09001741 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001742 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1743 return null;
1744 }
1745 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001746 if (nai == null) {
1747 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001748 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001749 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1750 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001751 }
1752
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001753 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001754 public NetworkInfo getNetworkInfo(int networkType) {
1755 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001756 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001757 if (getVpnUnderlyingNetworks(uid) != null) {
1758 // A VPN is active, so we may need to return one of its underlying networks. This
1759 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001760 // getNetworkAgentInfoForUid.
1761 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1762 if (nai == null) return null;
1763 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1764 if (networkInfo.getType() == networkType) {
1765 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001766 }
1767 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001768 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001769 }
1770
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001771 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001772 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001773 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001774 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001775 if (nai == null) return null;
1776 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001777 }
1778
1779 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001780 public NetworkInfo[] getAllNetworkInfo() {
1781 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001782 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001783 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1784 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001785 NetworkInfo info = getNetworkInfo(networkType);
1786 if (info != null) {
1787 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001788 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001789 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001790 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001791 }
1792
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001793 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001794 public Network getNetworkForType(int networkType) {
1795 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001796 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1797 return null;
1798 }
1799 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1800 if (nai == null) {
1801 return null;
1802 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001803 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001804 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1805 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001806 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001807 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001808 }
1809
1810 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001811 public Network[] getAllNetworks() {
1812 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001813 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001814 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001815 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001816 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001817 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001818 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001819 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001820 }
1821
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001822 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001823 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001824 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001825 // The basic principle is: if an app's traffic could possibly go over a
1826 // network, without the app doing anything multinetwork-specific,
1827 // (hence, by "default"), then include that network's capabilities in
1828 // the array.
1829 //
1830 // In the normal case, app traffic only goes over the system's default
1831 // network connection, so that's the only network returned.
1832 //
1833 // With a VPN in force, some app traffic may go into the VPN, and thus
1834 // over whatever underlying networks the VPN specifies, while other app
1835 // traffic may go over the system default network (e.g.: a split-tunnel
1836 // VPN, or an app disallowed by the VPN), so the set of networks
1837 // returned includes the VPN's underlying networks and the system
1838 // default.
1839 enforceAccessPermission();
1840
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001841 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001842
James Mattis2516da32021-01-31 17:06:19 -08001843 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1844 if (!nri.isBeingSatisfied()) {
1845 continue;
1846 }
1847 final NetworkAgentInfo nai = nri.getSatisfier();
1848 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1849 if (null != nc
1850 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1851 && !result.containsKey(nai.network)) {
1852 result.put(
1853 nai.network,
1854 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001855 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001856 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1857 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001858 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001859 }
1860
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001861 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001862 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001863 if (null != networks) {
1864 for (final Network network : networks) {
1865 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1866 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001867 result.put(
1868 network,
1869 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001870 nc,
1871 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001872 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001873 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001874 }
1875 }
1876 }
1877
1878 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1879 out = result.values().toArray(out);
1880 return out;
1881 }
1882
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001883 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001884 public boolean isNetworkSupported(int networkType) {
1885 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001886 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001887 }
1888
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001889 /**
1890 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08001891 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001892 * @return the ip properties for the active network, or {@code null} if
1893 * none is active
1894 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001895 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001896 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001897 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001898 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001899 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1900 if (nai == null) return null;
1901 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001902 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001903 }
1904
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001905 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001906 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001907 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001908 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001909 final LinkProperties lp = getLinkProperties(nai);
1910 if (lp == null) return null;
1911 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001912 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001913 }
1914
Robert Greenwaltbe46b752014-05-13 21:41:06 -07001915 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07001916 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001917 public LinkProperties getLinkProperties(Network network) {
1918 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001919 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1920 if (lp == null) return null;
1921 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001922 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09001923 }
1924
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001925 @Nullable
1926 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09001927 if (nai == null) {
1928 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001929 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09001930 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001931 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09001932 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001933 }
1934
Qingxi Lib2748102020-01-08 12:51:49 -08001935 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1936 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1937 }
1938
Lorenzo Colittie97685a2015-05-14 17:28:27 +09001939 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001940 if (nai == null) return null;
1941 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001942 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001943 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001944 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001945 }
1946
1947 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08001948 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1949 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001950 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09001951 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08001952 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08001953 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08001954 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001955 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09001956 }
1957
Qingxi Libb8da982020-01-17 17:54:27 -08001958 @VisibleForTesting
1959 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09001960 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09001961 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09001962 if (!checkSettingsPermission(callerPid, callerUid)) {
1963 newNc.setUids(null);
1964 newNc.setSSID(null);
1965 }
Etan Cohen107ae952018-12-30 17:59:59 -08001966 if (newNc.getNetworkSpecifier() != null) {
1967 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1968 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07001969 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07001970 if (!checkAnyPermissionOf(
1971 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08001972 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07001973 }
Qingxi Libb8da982020-01-17 17:54:27 -08001974
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09001975 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09001976 }
1977
Roshan Pius98f59ec2021-02-23 08:47:39 -08001978 /**
1979 * Wrapper used to cache the permission check results performed for the corresponding
1980 * app. This avoid performing multiple permission checks for different fields in
1981 * NetworkCapabilities.
1982 * Note: This wrapper does not support any sort of invalidation and thus must not be
1983 * persistent or long-lived. It may only be used for the time necessary to
1984 * compute the redactions required by one particular NetworkCallback or
1985 * synchronous call.
1986 */
1987 private class RedactionPermissionChecker {
1988 private final int mCallingPid;
1989 private final int mCallingUid;
1990 @NonNull private final String mCallingPackageName;
1991 @Nullable private final String mCallingAttributionTag;
1992
1993 private Boolean mHasLocationPermission = null;
1994 private Boolean mHasLocalMacAddressPermission = null;
1995 private Boolean mHasSettingsPermission = null;
1996
1997 RedactionPermissionChecker(int callingPid, int callingUid,
1998 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
1999 mCallingPid = callingPid;
2000 mCallingUid = callingUid;
2001 mCallingPackageName = callingPackageName;
2002 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002003 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002004
2005 private boolean hasLocationPermissionInternal() {
2006 final long token = Binder.clearCallingIdentity();
2007 try {
2008 return mLocationPermissionChecker.checkLocationPermission(
2009 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2010 null /* message */);
2011 } finally {
2012 Binder.restoreCallingIdentity(token);
2013 }
2014 }
2015
2016 /**
2017 * Returns whether the app holds location permission or not (might return cached result
2018 * if the permission was already checked before).
2019 */
2020 public boolean hasLocationPermission() {
2021 if (mHasLocationPermission == null) {
2022 // If there is no cached result, perform the check now.
2023 mHasLocationPermission = hasLocationPermissionInternal();
2024 }
2025 return mHasLocationPermission;
2026 }
2027
2028 /**
2029 * Returns whether the app holds local mac address permission or not (might return cached
2030 * result if the permission was already checked before).
2031 */
2032 public boolean hasLocalMacAddressPermission() {
2033 if (mHasLocalMacAddressPermission == null) {
2034 // If there is no cached result, perform the check now.
2035 mHasLocalMacAddressPermission =
2036 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2037 }
2038 return mHasLocalMacAddressPermission;
2039 }
2040
2041 /**
2042 * Returns whether the app holds settings permission or not (might return cached
2043 * result if the permission was already checked before).
2044 */
2045 public boolean hasSettingsPermission() {
2046 if (mHasSettingsPermission == null) {
2047 // If there is no cached result, perform the check now.
2048 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2049 }
2050 return mHasSettingsPermission;
2051 }
2052 }
2053
2054 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2055 @NetworkCapabilities.NetCapability long redaction) {
2056 return (redactions & redaction) != 0;
2057 }
2058
2059 /**
2060 * Use the provided |applicableRedactions| to check the receiving app's
2061 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2062 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2063 * before being sent to the corresponding app.
2064 */
2065 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2066 @NetworkCapabilities.RedactionType long applicableRedactions,
2067 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2068 boolean includeLocationSensitiveInfo) {
2069 long redactions = applicableRedactions;
2070 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2071 if (includeLocationSensitiveInfo
2072 && redactionPermissionChecker.hasLocationPermission()) {
2073 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2074 }
2075 }
2076 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2077 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2078 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2079 }
2080 }
2081 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2082 if (redactionPermissionChecker.hasSettingsPermission()) {
2083 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2084 }
2085 }
2086 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002087 }
2088
Qingxi Lib2748102020-01-08 12:51:49 -08002089 @VisibleForTesting
2090 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002091 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002092 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002093 int callingPid, int callingUid, @NonNull String callingPkgName,
2094 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002095 if (nc == null) {
2096 return null;
2097 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002098 // Avoid doing location permission check if the transport info has no location sensitive
2099 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002100 final RedactionPermissionChecker redactionPermissionChecker =
2101 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2102 callingAttributionTag);
2103 final long redactions = retrieveRequiredRedactions(
2104 nc.getApplicableRedactions(), redactionPermissionChecker,
2105 includeLocationSensitiveInfo);
2106 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002107 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002108 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002109 newNc.setOwnerUid(INVALID_UID);
2110 return newNc;
2111 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002112 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2113 if (nc.hasTransport(TRANSPORT_VPN)) {
2114 // Owner UIDs already checked above. No need to re-check.
2115 return newNc;
2116 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002117 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2118 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002119 // compatibility for older apps.
2120 if (!includeLocationSensitiveInfo
2121 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002122 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002123 newNc.setOwnerUid(INVALID_UID);
2124 return newNc;
2125 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002126 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002127 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002128 newNc.setOwnerUid(INVALID_UID);
2129 }
Qingxi Lib2748102020-01-08 12:51:49 -08002130 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002131 }
2132
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002133 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2134 LinkProperties lp, int callerPid, int callerUid) {
2135 if (lp == null) return new LinkProperties();
2136
2137 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2138 final boolean needsSanitization =
2139 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2140 if (!needsSanitization) {
2141 return new LinkProperties(lp);
2142 }
2143
2144 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002145 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002146 }
2147
2148 final LinkProperties newLp = new LinkProperties(lp);
2149 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2150 // object gets parceled.
2151 newLp.setCaptivePortalApiUrl(null);
2152 newLp.setCaptivePortalData(null);
2153 return newLp;
2154 }
2155
Roshan Pius08c94fb2020-01-16 12:17:17 -08002156 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2157 int callerUid, String callerPackageName) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09002158 if (!checkSettingsPermission()) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09002159 // There is no need to track the effective UID of the request here. If the caller lacks
2160 // the settings permission, the effective UID is the same as the calling ID.
Roshan Pius08c94fb2020-01-16 12:17:17 -08002161 nc.setSingleUid(callerUid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002162 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002163 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002164 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002165
2166 // Clear owner UID; this can never come from an app.
2167 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002168 }
2169
Chalard Jean38354d12018-03-20 19:13:57 +09002170 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002171 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002172 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2173 }
2174 }
2175
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002176 @Override
2177 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2178 enforceAccessPermission();
2179 final int callerUid = Binder.getCallingUid();
2180 final long token = Binder.clearCallingIdentity();
2181 try {
2182 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2183 } finally {
2184 Binder.restoreCallingIdentity(token);
2185 }
2186 }
2187
junyulaiebd15162021-03-03 12:09:05 +08002188 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002189 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002190 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002191 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002192 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002193
Serik Beketayev05130302021-01-15 16:47:25 -08002194 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002195 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002196 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2197 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002198 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002199 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002200 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002201 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2202 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002203 }
2204 }
2205 return result.toArray(new NetworkState[result.size()]);
2206 }
2207
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002208 @Override
junyulaiebd15162021-03-03 12:09:05 +08002209 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002210 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002211 // This contains IMSI details, so make sure the caller is privileged.
2212 PermissionUtils.enforceNetworkStackPermission(mContext);
2213
2214 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2215 for (Network network : getAllNetworks()) {
2216 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2217 // TODO: Consider include SUSPENDED networks, which should be considered as
2218 // temporary shortage of connectivity of a connected network.
2219 if (nai != null && nai.networkInfo.isConnected()) {
2220 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2221 // NetworkCapabilities, which may contain UIDs of apps to which the
2222 // network applies. Should the UIDs be cleared so as not to leak or
2223 // interfere ?
2224 result.add(nai.getNetworkStateSnapshot());
2225 }
2226 }
2227 return result;
2228 }
2229
2230 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002231 public boolean isActiveNetworkMetered() {
2232 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002233
Qingxi Lib2748102020-01-08 12:51:49 -08002234 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002235 if (caps != null) {
2236 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2237 } else {
2238 // Always return the most conservative value
2239 return true;
2240 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002241 }
2242
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002243 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002244 * Ensures that the system cannot call a particular method.
2245 */
2246 private boolean disallowedBecauseSystemCaller() {
2247 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002248 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2249 // for devices launched with Q and above. However, existing devices upgrading to Q and
2250 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002251 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002252 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002253 log("This method exists only for app backwards compatibility"
2254 + " and must not be called by system services.");
2255 return true;
2256 }
2257 return false;
2258 }
2259
2260 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002261 * Ensure that a network route exists to deliver traffic to the specified
2262 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002263 * @param networkType the type of the network over which traffic to the
2264 * specified host is to be routed
2265 * @param hostAddress the IP address of the host to which the route is
2266 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002267 * @return {@code true} on success, {@code false} on failure
2268 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002269 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002270 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2271 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002272 if (disallowedBecauseSystemCaller()) {
2273 return false;
2274 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002275 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002276 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002277 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002278 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002279
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002280 InetAddress addr;
2281 try {
2282 addr = InetAddress.getByAddress(hostAddress);
2283 } catch (UnknownHostException e) {
2284 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2285 return false;
2286 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002287
The Android Open Source Project28527d22009-03-03 19:31:44 -08002288 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002289 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002290 return false;
2291 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002292
2293 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2294 if (nai == null) {
2295 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2296 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2297 } else {
2298 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2299 }
2300 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002301 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002302
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002303 DetailedState netState;
2304 synchronized (nai) {
2305 netState = nai.networkInfo.getDetailedState();
2306 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002307
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002308 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002309 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002310 log("requestRouteToHostAddress on down network "
2311 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002312 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002313 }
2314 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002315 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002316
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002317 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002318 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002319 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002320 LinkProperties lp;
2321 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002322 synchronized (nai) {
2323 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002324 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002325 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002326 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002327 if (DBG) {
2328 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2329 }
Wink Saville32506bc2013-06-29 21:10:57 -07002330 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002331 } finally {
2332 Binder.restoreCallingIdentity(token);
2333 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002334 }
2335
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002336 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002337 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002338 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002339 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002340 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002341 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002342 if (bestRoute.getGateway().equals(addr)) {
2343 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002344 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002345 } else {
2346 // if we will connect to this through another route, add a direct route
2347 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002348 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002349 }
2350 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002351 if (DBG) log("Adding legacy route " + bestRoute +
2352 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002353
2354 final String dst = bestRoute.getDestinationLinkAddress().toString();
2355 final String nextHop = bestRoute.hasGateway()
2356 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002357 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002358 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2359 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002360 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002361 return false;
2362 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002363 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002364 }
2365
paulhu7c0a2e62021-01-08 00:51:49 +08002366 class DnsResolverUnsolicitedEventCallback extends
2367 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002368 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002369 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002370 try {
2371 mHandler.sendMessage(mHandler.obtainMessage(
2372 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002373 new PrivateDnsValidationUpdate(event.netId,
2374 InetAddresses.parseNumericAddress(event.ipAddress),
2375 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002376 } catch (IllegalArgumentException e) {
2377 loge("Error parsing ip address in validation event");
2378 }
2379 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002380
2381 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002382 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2383 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002384 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2385 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2386 // event callback for certain nai. e.g. cellular. Register here to pass to
2387 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002388 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2389 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2390 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002391 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002392 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002393 }
2394 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002395
2396 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002397 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2398 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2399 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002400 }
dalyk1720e542018-03-05 12:42:22 -05002401
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002402 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002403 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002404 return this.VERSION;
2405 }
2406
2407 @Override
2408 public String getInterfaceHash() {
2409 return this.HASH;
2410 }
paulhu7c0a2e62021-01-08 00:51:49 +08002411 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002412
2413 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002414 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2415 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002416
paulhu7c0a2e62021-01-08 00:51:49 +08002417 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002418 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002419 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002420 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002421 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002422 }
2423 }
2424
Sudheer Shanka9967d462021-03-18 19:09:25 +00002425 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002426 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002427 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002428 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2429 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002430 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002431 };
2432
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002433 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002434 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002435 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002436 }
2437
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002438 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002439 for (String permission : permissions) {
2440 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002441 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002442 }
2443 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002444 return false;
2445 }
2446
paulhu1a407652019-03-22 16:35:06 +08002447 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2448 for (String permission : permissions) {
2449 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2450 return true;
2451 }
2452 }
2453 return false;
2454 }
2455
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002456 private void enforceAnyPermissionOf(String... permissions) {
2457 if (!checkAnyPermissionOf(permissions)) {
2458 throw new SecurityException("Requires one of the following permissions: "
2459 + String.join(", ", permissions) + ".");
2460 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002461 }
2462
Paul Jensen83f5d572014-08-29 09:54:01 -04002463 private void enforceInternetPermission() {
2464 mContext.enforceCallingOrSelfPermission(
2465 android.Manifest.permission.INTERNET,
2466 "ConnectivityService");
2467 }
2468
The Android Open Source Project28527d22009-03-03 19:31:44 -08002469 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002470 mContext.enforceCallingOrSelfPermission(
2471 android.Manifest.permission.ACCESS_NETWORK_STATE,
2472 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002473 }
2474
paulhua6ee2122021-02-22 15:40:43 +08002475 /**
2476 * Performs a strict and comprehensive check of whether a calling package is allowed to
2477 * change the state of network, as the condition differs for pre-M, M+, and
2478 * privileged/preinstalled apps. The caller is expected to have either the
2479 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2480 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2481 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2482 * permission and cannot be revoked. See http://b/23597341
2483 *
2484 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2485 * of this app will be updated to the current time.
2486 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002487 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002488 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2489 == PackageManager.PERMISSION_GRANTED) {
2490 return;
2491 }
2492
2493 if (callingPkg == null) {
2494 throw new SecurityException("Calling package name is null.");
2495 }
2496
2497 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2498 final int uid = mDeps.getCallingUid();
2499 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2500 callingPkg, callingAttributionTag, null /* message */);
2501
2502 if (mode == AppOpsManager.MODE_ALLOWED) {
2503 return;
2504 }
2505
2506 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2507 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2508 return;
2509 }
2510
2511 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2512 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2513 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002514 }
2515
Charles He9369e612017-05-15 17:07:18 +01002516 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002517 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002518 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002519 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002520 }
2521
paulhu8e96a752019-08-12 16:25:11 +08002522 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002523 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002524 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002525 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002526 }
2527
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002528 private void enforceNetworkFactoryOrSettingsPermission() {
2529 enforceAnyPermissionOf(
2530 android.Manifest.permission.NETWORK_SETTINGS,
2531 android.Manifest.permission.NETWORK_FACTORY,
2532 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2533 }
2534
2535 private void enforceNetworkFactoryOrTestNetworksPermission() {
2536 enforceAnyPermissionOf(
2537 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2538 android.Manifest.permission.NETWORK_FACTORY,
2539 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2540 }
2541
Chalard Jean9a396cc2018-02-21 18:43:54 +09002542 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002543 return checkAnyPermissionOf(
2544 android.Manifest.permission.NETWORK_SETTINGS,
2545 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002546 }
2547
2548 private boolean checkSettingsPermission(int pid, int uid) {
2549 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002550 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2551 || PERMISSION_GRANTED == mContext.checkPermission(
2552 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002553 }
2554
paulhu8e96a752019-08-12 16:25:11 +08002555 private void enforceNetworkStackOrSettingsPermission() {
2556 enforceAnyPermissionOf(
2557 android.Manifest.permission.NETWORK_SETTINGS,
2558 android.Manifest.permission.NETWORK_STACK,
2559 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2560 }
2561
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002562 private void enforceNetworkStackSettingsOrSetup() {
2563 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002564 android.Manifest.permission.NETWORK_SETTINGS,
2565 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002566 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002567 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002568 }
2569
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002570 private void enforceAirplaneModePermission() {
2571 enforceAnyPermissionOf(
2572 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2573 android.Manifest.permission.NETWORK_SETTINGS,
2574 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2575 android.Manifest.permission.NETWORK_STACK,
2576 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2577 }
2578
James Mattis8378aec2021-01-26 14:05:36 -08002579 private void enforceOemNetworkPreferencesPermission() {
2580 mContext.enforceCallingOrSelfPermission(
2581 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2582 "ConnectivityService");
2583 }
2584
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002585 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002586 return checkAnyPermissionOf(
2587 android.Manifest.permission.NETWORK_STACK,
2588 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002589 }
2590
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002591 private boolean checkNetworkStackPermission(int pid, int uid) {
2592 return checkAnyPermissionOf(pid, uid,
2593 android.Manifest.permission.NETWORK_STACK,
2594 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2595 }
2596
paulhu1a407652019-03-22 16:35:06 +08002597 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2598 return checkAnyPermissionOf(pid, uid,
2599 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002600 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2601 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002602 }
2603
Hugo Benichibd0cc762016-07-19 15:59:27 +09002604 private void enforceConnectivityRestrictedNetworksPermission() {
2605 try {
2606 mContext.enforceCallingOrSelfPermission(
2607 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2608 "ConnectivityService");
2609 return;
2610 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002611 // TODO: Remove this fallback check after all apps have declared
2612 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2613 mContext.enforceCallingOrSelfPermission(
2614 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2615 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002616 }
2617
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002618 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002619 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002620 }
2621
Roshan Pius98f59ec2021-02-23 08:47:39 -08002622 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2623 return PERMISSION_GRANTED == mContext.checkPermission(
2624 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2625 }
2626
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002627 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002628 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002629 }
2630
2631 private void sendInetConditionBroadcast(NetworkInfo info) {
2632 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2633 }
2634
Wink Saville4f0de1e2011-08-04 15:01:58 -07002635 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002636 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002637 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002638 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002639 if (info.isFailover()) {
2640 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2641 info.setFailover(false);
2642 }
2643 if (info.getReason() != null) {
2644 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2645 }
2646 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002647 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2648 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002649 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002650 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002651 return intent;
2652 }
2653
2654 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2655 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2656 }
2657
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002658 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002659 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002660 if (!mSystemReady
2661 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002662 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002663 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002664 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002665 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002666 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002667 }
2668
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002669 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002670 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002671 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002672 final NetworkInfo ni = intent.getParcelableExtra(
2673 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002674 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2675 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2676 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002677 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002678 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002679 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002680 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002684 }
2685 }
2686
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002687 /**
Aaron Huang96011892020-06-27 07:18:23 +08002688 * Called by SystemServer through ConnectivityManager when the system is ready.
2689 */
2690 @Override
2691 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002692 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002693 throw new SecurityException("Calling Uid is not system uid.");
2694 }
2695 systemReadyInternal();
2696 }
2697
2698 /**
2699 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002700 */
2701 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002702 public void systemReadyInternal() {
Aaron Huang9a57acf2020-12-08 10:03:29 +08002703 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2704 // listening network request which is sent by MultipathPolicyTracker won't be added
2705 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2706 // be called after PermissionMonitor#startMonitoring().
2707 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2708 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2709 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002710 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002711 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002712 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002713
Hugo Benichie5220992017-04-26 14:53:28 +09002714 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002715 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002716 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002717 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002718 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002719 }
2720 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002721
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002722 // Create network requests for always-on networks.
2723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
The Android Open Source Project28527d22009-03-03 19:31:44 -08002724 }
2725
The Android Open Source Project28527d22009-03-03 19:31:44 -08002726 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002727 * Start listening for default data network activity state changes.
2728 */
2729 @Override
2730 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002731 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002732 }
2733
2734 /**
2735 * Stop listening for default data network activity state changes.
2736 */
2737 @Override
2738 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002739 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002740 }
2741
2742 /**
2743 * Check whether the default network radio is currently active.
2744 */
2745 @Override
2746 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002747 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002748 }
2749
2750 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002751 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002752 * and set it on it's iface.
2753 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002754 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2755 final String iface = newLp.getInterfaceName();
2756 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002757 if (oldLp == null && mtu == 0) {
2758 // Silently ignore unset MTU value.
2759 return;
2760 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002761 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2762 if (VDBG) log("identical MTU - not setting");
2763 return;
2764 }
paulhucbbc3db2019-03-08 16:35:20 +08002765 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002766 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002767 return;
2768 }
sy.yun4aa73922013-09-02 05:24:09 +09002769
w19976e714f1d2014-08-05 15:18:11 -07002770 // Cannot set MTU without interface name
2771 if (TextUtils.isEmpty(iface)) {
2772 loge("Setting MTU size with null iface.");
2773 return;
2774 }
2775
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002776 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002777 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002778 mNetd.interfaceSetMtu(iface, mtu);
2779 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002780 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002781 }
2782 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002783
Chenbo Feng15416292018-11-08 17:36:21 -08002784 @VisibleForTesting
2785 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002786
lucaslin821c9782018-11-28 19:27:52 +08002787 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002788 String[] values = null;
2789 if (tcpBufferSizes != null) {
2790 values = tcpBufferSizes.split(",");
2791 }
2792
2793 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002794 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002795 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2796 values = tcpBufferSizes.split(",");
2797 }
2798
2799 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2800
2801 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002802 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002803
Chenbo Feng15416292018-11-08 17:36:21 -08002804 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2805 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2806 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002807 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002808 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002809 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002810 }
2811 }
2812
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002813 @Override
2814 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002815 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002816 NETWORK_RESTORE_DELAY_PROP_NAME);
2817 if(restoreDefaultNetworkDelayStr != null &&
2818 restoreDefaultNetworkDelayStr.length() != 0) {
2819 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002820 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002821 } catch (NumberFormatException e) {
2822 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002823 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002824 // if the system property isn't set, use the value for the apn type
2825 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2826
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002827 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2828 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002829 }
2830 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002831 }
2832
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002833 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2834 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2835 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09002836 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08002837 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002838 // Start gathering diagnostic information.
2839 netDiags.add(new NetworkDiagnostics(
2840 nai.network,
2841 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08002842 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002843 DIAG_TIME_MS));
2844 }
2845
2846 for (NetworkDiagnostics netDiag : netDiags) {
2847 pw.println();
2848 netDiag.waitForMeasurements();
2849 netDiag.dump(pw);
2850 }
2851 }
2852
The Android Open Source Project28527d22009-03-03 19:31:44 -08002853 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09002854 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2855 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08002856 if (!checkDumpPermission(mContext, TAG, writer)) return;
2857
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08002858 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07002859 }
2860
lucaslin99473f62020-12-10 15:10:54 +08002861 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2862 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2863 != PackageManager.PERMISSION_GRANTED) {
2864 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002865 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08002866 + " due to missing android.permission.DUMP permission");
2867 return false;
2868 } else {
2869 return true;
2870 }
2871 }
2872
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08002873 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002874 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002875
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002876 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002877 dumpNetworkDiagnostics(pw);
2878 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002879 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002880 dumpNetworks(pw);
2881 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002882 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002883 dumpNetworkRequests(pw);
2884 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002885 }
Erik Kline9647f382015-06-05 17:47:34 +09002886
Lorenzo Colittia86fae72020-01-10 00:40:28 +09002887 pw.print("NetworkProviders for:");
2888 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2889 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07002890 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09002891 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07002892 pw.println();
2893
Chalard Jean5b409c72021-02-04 13:12:59 +09002894 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002895 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09002896 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002897 pw.println("none");
2898 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09002899 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002900 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002901 pw.println();
2902
James Mattis45d81842021-01-10 14:24:24 -08002903 pw.print("Current per-app default networks: ");
2904 pw.increaseIndent();
2905 dumpPerAppNetworkPreferences(pw);
2906 pw.decreaseIndent();
2907 pw.println();
2908
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002909 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002910 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002911 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002912 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002913 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002914
junyulaif2c67e42018-08-07 19:50:45 +08002915 pw.println("Status for known UIDs:");
2916 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00002917 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08002918 for (int i = 0; i < size; i++) {
2919 // Don't crash if the array is modified while dumping in bugreports.
2920 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002921 final int uid = mUidBlockedReasons.keyAt(i);
2922 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2923 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002924 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08002925 } catch (ArrayIndexOutOfBoundsException e) {
2926 pw.println(" ArrayIndexOutOfBoundsException");
2927 } catch (ConcurrentModificationException e) {
2928 pw.println(" ConcurrentModificationException");
2929 }
2930 }
2931 pw.println();
2932 pw.decreaseIndent();
2933
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002934 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002935 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002936 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002937 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002938 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002939
Robert Greenwalt94e22142014-07-30 16:31:24 -07002940 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07002941
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002942 pw.println();
markchien5e866652019-09-30 14:40:57 +08002943 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002944
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002945 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09002946 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002947
Lorenzo Colitti389a8142018-01-24 17:35:07 +09002948 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09002949
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002950 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07002951 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09002952 pw.println("mNetworkRequestInfoLogs (most recent first):");
2953 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07002954 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09002955 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09002956
2957 pw.println();
2958 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2959 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07002960 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09002961 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09002962
2963 pw.println();
2964 pw.println("NetTransition WakeLock activity (most recent first):");
2965 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09002966 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2967 pw.println("total releases: " + mTotalWakelockReleases);
2968 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2969 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2970 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2971 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2972 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2973 }
James Mattiscb1e0362021-04-06 17:07:42 -07002974 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07002975
2976 pw.println();
2977 pw.println("bandwidth update requests (by uid):");
2978 pw.increaseIndent();
2979 synchronized (mBandwidthRequests) {
2980 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2981 pw.println("[" + mBandwidthRequests.keyAt(i)
2982 + "]: " + mBandwidthRequests.valueAt(i));
2983 }
2984 }
2985 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07002986 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07002987
James Mattiscb1e0362021-04-06 17:07:42 -07002988 pw.println();
2989 pw.println("mOemNetworkPreferencesLogs (most recent first):");
2990 pw.increaseIndent();
2991 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09002992 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07002993 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09002994
2995 pw.println();
2996 pw.println("NetworkStackClient logs:");
2997 pw.increaseIndent();
2998 NetworkStackClient.getInstance().dump(pw);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00002999 pw.decreaseIndent();
3000
3001 pw.println();
3002 pw.println("Permission Monitor:");
3003 pw.increaseIndent();
3004 mPermissionMonitor.dump(pw);
3005 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003006
3007 pw.println();
3008 pw.println("Legacy network activity:");
3009 pw.increaseIndent();
3010 mNetworkActivityTracker.dump(pw);
3011 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003012 }
3013
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003014 private void dumpNetworks(IndentingPrintWriter pw) {
3015 for (NetworkAgentInfo nai : networksSortedById()) {
3016 pw.println(nai.toString());
3017 pw.increaseIndent();
3018 pw.println(String.format(
3019 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3020 nai.numForegroundNetworkRequests(),
3021 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3022 nai.numBackgroundNetworkRequests(),
3023 nai.numNetworkRequests()));
3024 pw.increaseIndent();
3025 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3026 pw.println(nai.requestAt(i).toString());
3027 }
3028 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003029 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003030 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003031 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003032 pw.decreaseIndent();
3033 pw.decreaseIndent();
3034 }
3035 }
3036
James Mattis45d81842021-01-10 14:24:24 -08003037 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3038 pw.println("Per-App Network Preference:");
3039 pw.increaseIndent();
3040 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3041 pw.println("none");
3042 } else {
3043 pw.println(mOemNetworkPreferences.toString());
3044 }
3045 pw.decreaseIndent();
3046
3047 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3048 if (mDefaultRequest == defaultRequest) {
3049 continue;
3050 }
3051
3052 final boolean isActive = null != defaultRequest.getSatisfier();
3053 pw.println("Is per-app network active:");
3054 pw.increaseIndent();
3055 pw.println(isActive);
3056 if (isActive) {
3057 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3058 }
3059 pw.println("Tracked UIDs:");
3060 pw.increaseIndent();
3061 if (0 == defaultRequest.mRequests.size()) {
3062 pw.println("none, this should never occur.");
3063 } else {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00003064 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
James Mattis45d81842021-01-10 14:24:24 -08003065 }
3066 pw.decreaseIndent();
3067 pw.decreaseIndent();
3068 }
3069 }
3070
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003071 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3072 for (NetworkRequestInfo nri : requestsSortedById()) {
3073 pw.println(nri.toString());
3074 }
3075 }
3076
Hugo Benichia480ba52018-09-03 08:19:02 +09003077 /**
3078 * Return an array of all current NetworkAgentInfos sorted by network id.
3079 */
3080 private NetworkAgentInfo[] networksSortedById() {
3081 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003082 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003083 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003084 return networks;
3085 }
3086
3087 /**
3088 * Return an array of all current NetworkRequest sorted by request id.
3089 */
James Mattis258ea3c2020-11-15 15:04:40 -08003090 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003091 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003092 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003093 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003094 // Sort the array based off the NRI containing the min requestId in its requests.
3095 Arrays.sort(requests,
3096 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3097 Comparator.comparingInt(req -> req.requestId)).requestId
3098 )
3099 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003100 return requests;
3101 }
3102
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003103 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003104 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003105 if (officialNai != null && officialNai.equals(nai)) return true;
3106 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003107 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003108 " - " + nai);
3109 }
3110 return false;
3111 }
3112
Robert Greenwalt2034b912009-08-12 16:08:25 -07003113 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003114 private class NetworkStateTrackerHandler extends Handler {
3115 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003116 super(looper);
3117 }
3118
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003119 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003120 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3121 final NetworkAgentInfo nai = arg.first;
3122 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003123 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003124 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003125 }
3126 return;
3127 }
3128
3129 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003130 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003131 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003132 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003133 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003134 }
Chalard Jean5b639762020-03-09 21:25:37 +09003135 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3136 // Make sure the original object is not mutated. NetworkAgent normally
3137 // makes a copy of the capabilities when sending the message through
3138 // the Messenger, but if this ever changes, not making a defensive copy
3139 // here will give attack vectors to clients using this code path.
3140 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Cody Kestingfc7cad32020-04-07 16:07:33 -07003141 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003142 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003143 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003144 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003145 break;
3146 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003147 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003148 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003149 processLinkPropertiesFromAgent(nai, newLp);
3150 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003151 break;
3152 }
3153 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003154 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003155 updateNetworkInfo(nai, info);
3156 break;
3157 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003158 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003159 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003160 break;
3161 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003162 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003163 if (nai.everConnected) {
3164 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003165 // Note that if the NAI had been connected, this would affect the
3166 // score, and therefore would require re-mixing the score and performing
3167 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003168 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003169 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3170 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003171 // Mark the network as temporarily accepting partial connectivity so that it
3172 // will be validated (and possibly become default) even if it only provides
3173 // partial internet access. Note that if user connects to partial connectivity
3174 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3175 // out of wifi coverage) and if the same wifi is available again, the device
3176 // will auto connect to this wifi even though the wifi has "no internet".
3177 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003178 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003179 break;
3180 }
junyulai011b1f12019-01-03 18:50:15 +08003181 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003182 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003183 break;
3184 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003185 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003186 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003187 if (!nai.supportsUnderlyingNetworks()) {
3188 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3189 break;
3190 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003191
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003192 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003193
3194 if (isLegacyLockdownNai(nai)
3195 && (underlying == null || underlying.size() != 1)) {
3196 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3197 + " must have exactly one underlying network: " + underlying);
3198 }
3199
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003200 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3201 nai.declaredUnderlyingNetworks = (underlying != null)
3202 ? underlying.toArray(new Network[0]) : null;
3203
3204 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3205 if (DBG) {
3206 log(nai.toShortString() + " changed underlying networks to "
3207 + Arrays.toString(nai.declaredUnderlyingNetworks));
3208 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003209 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003210 notifyIfacesChangedForNetworkStats();
3211 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003212 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003213 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003214 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3215 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3216 nai.teardownDelayMs = msg.arg1;
3217 } else {
3218 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3219 }
3220 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003221 }
3222 }
3223
3224 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3225 switch (msg.what) {
3226 default:
3227 return false;
lucasline117e2e2019-10-22 18:27:33 +08003228 case EVENT_PROBE_STATUS_CHANGED: {
3229 final Integer netId = (Integer) msg.obj;
3230 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3231 if (nai == null) {
3232 break;
3233 }
3234 final boolean probePrivateDnsCompleted =
3235 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3236 final boolean privateDnsBroken =
3237 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3238 if (probePrivateDnsCompleted) {
3239 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3240 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003241 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003242 }
3243 // Only show the notification when the private DNS is broken and the
3244 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003245 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003246 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3247 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003248 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003249 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3250 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3251 // private DNS is broken, it means this network is being reevaluated.
3252 // Either probing private DNS is not necessary any more or it hasn't been
3253 // done yet. In either case, the networkCapabilities should be updated to
3254 // reflect the new status.
3255 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003256 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003257 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003258 }
3259 break;
3260 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003261 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003262 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3263
3264 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003265 if (nai == null) break;
3266
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003267 handleNetworkTested(nai, results.mTestResult,
3268 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003269 break;
3270 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003271 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003272 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003273 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003274 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003275 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003276 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3277 nai.lastCaptivePortalDetected = visible;
3278 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003279 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003280 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3281 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003282 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003283 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003284 teardownUnneededNetwork(nai);
3285 break;
3286 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003287 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003288 }
3289 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003290 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003291 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003292 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3293 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003294 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003295 if (nai == null) {
3296 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3297 break;
3298 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003299 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003300 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003301 (PendingIntent) msg.obj,
3302 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003303 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003304 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003305 break;
3306 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003307 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003308 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003309 if (nai == null) break;
3310
Erik Kline9a62f012018-03-21 07:18:33 -07003311 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003312 break;
3313 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003314 case EVENT_CAPPORT_DATA_CHANGED: {
3315 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3316 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003317 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003318 break;
3319 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003320 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003321 return true;
3322 }
3323
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003324 private void handleNetworkTested(
3325 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3326 final boolean wasPartial = nai.partialConnectivity;
3327 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3328 final boolean partialConnectivityChanged =
3329 (wasPartial != nai.partialConnectivity);
3330
3331 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3332 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003333 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003334
3335 if (DBG) {
3336 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3337 ? " with redirect to " + redirectUrl
3338 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003339 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003340 }
3341 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003342 final int oldScore = nai.getCurrentScore();
3343 nai.lastValidated = valid;
3344 nai.everValidated |= valid;
3345 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3346 // If score has changed, rebroadcast to NetworkProviders. b/17726566
3347 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
3348 if (valid) {
3349 handleFreshlyValidatedNetwork(nai);
3350 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3351 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003352 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003353 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003354 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003355 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003356 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003357 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003358 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003359 NotificationType.PRIVATE_DNS_BROKEN);
3360 // If network becomes valid, the hasShownBroken should be reset for
3361 // that network so that the notification will be fired when the private
3362 // DNS is broken again.
3363 nai.networkAgentConfig.hasShownBroken = false;
3364 }
3365 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003366 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003367 }
3368 updateInetCondition(nai);
3369 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003370 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003371 nai.onValidationStatusChanged(
3372 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3373 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003374
3375 // If NetworkMonitor detects partial connectivity before
3376 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3377 // immediately. Re-notify partial connectivity silently if no internet
3378 // notification already there.
3379 if (!wasPartial && nai.partialConnectivity) {
3380 // Remove delayed message if there is a pending message.
3381 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3382 handlePromptUnvalidated(nai.network);
3383 }
3384
3385 if (wasValidated && !nai.lastValidated) {
3386 handleNetworkUnvalidated(nai);
3387 }
3388 }
3389
Calvin Ondada1452016-10-11 15:10:46 -07003390 private int getCaptivePortalMode() {
3391 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003392 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3393 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003394 }
3395
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003396 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3397 switch (msg.what) {
3398 default:
3399 return false;
3400 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3401 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3402 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3403 handleLingerComplete(nai);
3404 }
3405 break;
3406 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003407 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3408 handleNetworkAgentRegistered(msg);
3409 break;
3410 }
3411 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3412 handleNetworkAgentDisconnected(msg);
3413 break;
3414 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003415 }
3416 return true;
3417 }
3418
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003419 @Override
3420 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003421 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003422 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003423 maybeHandleNetworkAgentMessage(msg);
3424 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003425 }
3426 }
3427
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003428 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003429 private final int mNetId;
3430 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003431
3432 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003433 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003434 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003435 }
3436
3437 @Override
3438 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3439 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003440 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003441 }
3442
3443 @Override
3444 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003445 // Legacy version of notifyNetworkTestedWithExtras.
3446 // Would only be called if the system has a NetworkStack module older than the
3447 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003448 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003449 }
3450
3451 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003452 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003453 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3454 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003455 final Message msg = mTrackerHandler.obtainMessage(
3456 EVENT_NETWORK_TESTED,
3457 new NetworkTestedResults(
3458 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003459 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003460
3461 // Invoke ConnectivityReport generation for this Network test event.
3462 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3463 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003464
3465 final PersistableBundle extras = new PersistableBundle();
3466 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3467 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3468 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3469
Aaron Huang959d3642021-01-21 15:47:41 +08003470 ConnectivityReportEvent reportEvent =
3471 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3472 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3473 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003474 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003475 }
3476
3477 @Override
3478 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3479 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3480 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003481 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003482 }
3483
3484 @Override
lucasline117e2e2019-10-22 18:27:33 +08003485 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3486 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3487 EVENT_PROBE_STATUS_CHANGED,
3488 probesCompleted, probesSucceeded, new Integer(mNetId)));
3489 }
3490
3491 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003492 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3493 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3494 EVENT_CAPPORT_DATA_CHANGED,
3495 0, mNetId, data));
3496 }
3497
3498 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003499 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003500 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003501 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003502
3503 final PendingIntent pendingIntent;
3504 // Only the system server can register notifications with package "android"
3505 final long token = Binder.clearCallingIdentity();
3506 try {
paulhu7746e4e2020-06-09 19:07:03 +08003507 pendingIntent = PendingIntent.getBroadcast(
3508 mContext,
3509 0 /* requestCode */,
3510 intent,
3511 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003512 } finally {
3513 Binder.restoreCallingIdentity(token);
3514 }
3515 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3516 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003517 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003518 }
3519
3520 @Override
3521 public void hideProvisioningNotification() {
3522 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003523 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003524 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003525
3526 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003527 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003528 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003529 }
3530
3531 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003532 public int getInterfaceVersion() {
3533 return this.VERSION;
3534 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003535
3536 @Override
3537 public String getInterfaceHash() {
3538 return this.HASH;
3539 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003540 }
3541
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003542 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003543 log("Data stall detected with methods: " + p.detectionMethod);
3544
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003545 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003546 int detectionMethod = 0;
3547 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3548 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3549 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3550 }
3551 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3552 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3553 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3554 p.tcpMetricsCollectionPeriodMillis);
3555 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003556 }
3557
Cody Kestingf53a0752020-04-15 12:33:28 -07003558 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003559 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003560 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003561
3562 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3563 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3564 // the cost of going through two handlers.
3565 mConnectivityDiagnosticsHandler.sendMessage(msg);
3566 }
3567
Cody Kestingb37958e2020-05-15 10:36:01 -07003568 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3569 return (p.detectionMethod & detectionMethod) != 0;
3570 }
3571
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003572 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3573 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003574 }
3575
Erik Klinea73af002018-06-26 18:53:43 +09003576 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3577 if (nai == null) return;
3578 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3579 // in order to restart a validation pass from within netd.
3580 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3581 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003582 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003583 }
3584 }
3585
Erik Kline31b4a9e2018-01-11 21:07:29 +09003586 private void handlePrivateDnsSettingsChanged() {
3587 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3588
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003589 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003590 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003591 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003592 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3593 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003594 }
3595 }
3596
Erik Kline9a62f012018-03-21 07:18:33 -07003597 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3598 // Private DNS only ever applies to networks that might provide
3599 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003600 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003601
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003602 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003603 // schedule DNS resolutions. If a DNS resolution is required the
3604 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003605 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003606
3607 // With Private DNS bypass support, we can proceed to update the
3608 // Private DNS config immediately, even if we're in strict mode
3609 // and have not yet resolved the provider name into a set of IPs.
3610 updatePrivateDns(nai, cfg);
3611 }
3612
3613 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3614 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003615 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003616 }
3617
dalyk1720e542018-03-05 12:42:22 -05003618 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3619 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3620 if (nai == null) {
3621 return;
3622 }
3623 mDnsManager.updatePrivateDnsValidation(update);
3624 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3625 }
3626
paulhu7c0a2e62021-01-08 00:51:49 +08003627 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003628 int prefixLength) {
3629 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3630 if (nai == null) return;
3631
paulhu7c0a2e62021-01-08 00:51:49 +08003632 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3633 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003634
3635 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003636 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003637 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003638 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003639 prefixLength);
3640 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003641 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003642 return;
3643 }
3644 }
3645
Lorenzo Colittid523d142020-04-01 20:16:30 +09003646 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003647 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3648 }
3649
Hai Shalome58bdc62021-01-11 18:45:34 -08003650 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003651 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003652 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003653 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3654 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3655 }
3656
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003657 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003658 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003659 * @param nai the agent info to update
3660 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003661 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003662 */
junyulai2b6f0c22021-02-03 20:15:30 +08003663 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3664 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3665 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003666 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003667 // one lingered request, set inactive.
3668 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003669 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003670 if (DBG) log("Unsetting inactive " + nai.toShortString());
3671 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003672 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003673 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003674 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003675 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3676 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003677 }
junyulai2b6f0c22021-02-03 20:15:30 +08003678 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003679 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003680 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003681 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003682 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003683 }
3684
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003685 private void handleNetworkAgentRegistered(Message msg) {
3686 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3687 if (!mNetworkAgentInfos.contains(nai)) {
3688 return;
3689 }
3690
3691 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3692 if (VDBG) log("NetworkAgent registered");
3693 } else {
3694 loge("Error connecting NetworkAgent");
3695 mNetworkAgentInfos.remove(nai);
3696 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003697 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003698 synchronized (mNetworkForNetId) {
3699 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003700 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003701 mNetIdManager.releaseNetId(nai.network.getNetId());
3702 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003703 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003704 }
3705 }
3706 }
Paul Jensend5f53392014-11-25 15:26:53 -05003707
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003708 private void handleNetworkAgentDisconnected(Message msg) {
3709 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3710 if (mNetworkAgentInfos.contains(nai)) {
3711 disconnectAndDestroyNetwork(nai);
3712 }
3713 }
3714
Chalard Jeand9fffc32018-05-11 20:19:20 +09003715 // Destroys a network, remove references to it from the internal state managed by
3716 // ConnectivityService, free its interfaces and clean up.
3717 // Must be called on the Handler thread.
3718 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003719 ensureRunningOnConnectivityServiceThread();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003720 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003721 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003722 }
lucaslinb25c9a62019-02-12 15:30:13 +08003723 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003724 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003725 // A network agent has disconnected.
3726 // TODO - if we move the logic to the network agent (have them disconnect
3727 // because they lost all their requests or because their score isn't good)
3728 // then they would disconnect organically, report their new state and then
3729 // disconnect the channel.
3730 if (nai.networkInfo.isConnected()) {
3731 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3732 null, null);
3733 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003734 final boolean wasDefault = isDefaultNetwork(nai);
3735 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003736 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003737 }
3738 notifyIfacesChangedForNetworkStats();
3739 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3740 // by other networks that are already connected. Perhaps that can be done by
3741 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3742 // of rematchAllNetworksAndRequests
3743 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003744 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003745
3746 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003747 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3748 // Disable wakeup packet monitoring for each interface.
3749 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3750 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003751 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003752 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003753 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003754 synchronized (mNetworkForNetId) {
3755 // Remove the NetworkAgent, but don't mark the netId as
3756 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003757 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003758 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09003759 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003760 // Remove all previously satisfied requests.
3761 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003762 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09003763 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08003764 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08003765 if (currentNetwork != null
3766 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003767 // uid rules for this network will be removed in destroyNativeNetwork(nai).
James Mattisa076c532020-12-02 14:12:41 -08003768 nri.setSatisfier(null, null);
James Mattisd31bdfa2020-12-23 16:37:26 -08003769 if (request.isRequest()) {
3770 sendUpdatedScoreToFactories(request, null);
3771 }
James Mattise3ef1912020-12-20 11:09:58 -08003772
Chalard Jean5b409c72021-02-04 13:12:59 +09003773 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08003774 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09003775 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08003776 // network, because while incorrect this is the closest to the old (also
3777 // incorrect) behavior.
3778 mNetworkActivityTracker.updateDataActivityTracking(
3779 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08003780 ensureNetworkTransitionWakelock(nai.toShortString());
3781 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09003782 }
3783 }
junyulai2b6f0c22021-02-03 20:15:30 +08003784 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08003785 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09003786 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08003787 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09003788 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09003789 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003790 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003791
3792 // Immediate teardown.
3793 if (nai.teardownDelayMs == 0) {
3794 destroyNetwork(nai);
3795 return;
3796 }
3797
3798 // Delayed teardown.
3799 try {
3800 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3801 } catch (RemoteException e) {
3802 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3803 }
3804 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3805 }
3806
3807 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003808 if (nai.created) {
3809 // Tell netd to clean up the configuration for this network
3810 // (routing rules, DNS, etc).
3811 // This may be slow as it requires a lot of netd shelling out to ip and
3812 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09003813 // after we've rematched networks with requests (which might change the default
3814 // network or service a new request from an app), so network traffic isn't interrupted
3815 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08003816 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003817 mDnsManager.removeNetwork(nai.network);
3818 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08003819 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003820 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003821 }
3822
Ken Chen6df7a902021-04-09 15:08:42 +08003823 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08003824 try {
3825 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08003826 final NativeNetworkConfig config;
3827 if (nai.isVPN()) {
3828 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08003829 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08003830 return false;
3831 }
3832 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3833 INetd.PERMISSION_NONE,
3834 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3835 getVpnType(nai));
Luke Huangfdd11f82019-04-09 18:41:49 +08003836 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08003837 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3838 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3839 VpnManager.TYPE_VPN_NONE);
Luke Huangfdd11f82019-04-09 18:41:49 +08003840 }
Ken Chen6df7a902021-04-09 15:08:42 +08003841 mNetd.networkCreate(config);
3842 mDnsResolver.createNetworkCache(nai.network.getNetId());
3843 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3844 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08003845 return true;
3846 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08003847 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08003848 return false;
3849 }
3850 }
3851
Ken Chen6df7a902021-04-09 15:08:42 +08003852 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08003853 try {
Ken Chen6df7a902021-04-09 15:08:42 +08003854 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09003855 } catch (RemoteException | ServiceSpecificException e) {
3856 loge("Exception destroying network(networkDestroy): " + e);
3857 }
3858 try {
Ken Chen6df7a902021-04-09 15:08:42 +08003859 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08003860 } catch (RemoteException | ServiceSpecificException e) {
3861 loge("Exception destroying network: " + e);
3862 }
3863 }
3864
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003865 // If this method proves to be too slow then we can maintain a separate
3866 // pendingIntent => NetworkRequestInfo map.
3867 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3868 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003869 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3870 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3871 if (existingPendingIntent != null &&
paulhu90b43ff2021-03-04 11:36:55 +08003872 existingPendingIntent.intentFilterEquals(pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003873 return entry.getValue();
3874 }
3875 }
3876 return null;
3877 }
3878
James Mattisf7027322020-12-13 16:28:14 -08003879 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003880 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08003881 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3882 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3883 final NetworkRequestInfo existingRequest =
3884 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003885 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08003886 if (DBG) {
3887 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3888 + nri.mRequests.get(0) + " because their intents matched.");
3889 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09003890 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08003891 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003892 }
Erik Kline05f2b402015-04-30 12:58:40 +09003893 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003894 }
3895
James Mattisf7027322020-12-13 16:28:14 -08003896 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08003897 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08003898 }
3899
James Mattis3ce3d3c2021-02-09 18:18:28 -08003900 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003901 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08003902 for (final NetworkRequestInfo nri : nris) {
3903 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3904 for (final NetworkRequest req : nri.mRequests) {
3905 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08003906 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08003907 if (req.isListen()) {
3908 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3909 if (req.networkCapabilities.hasSignalStrength()
3910 && network.satisfiesImmutableCapabilitiesOf(req)) {
3911 updateSignalStrengthThresholds(network, "REGISTER", req);
3912 }
James Mattisf7027322020-12-13 16:28:14 -08003913 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09003914 }
3915 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09003916 // If this NRI has a satisfier already, it is replacing an older request that
3917 // has been removed. Track it.
3918 final NetworkRequest activeRequest = nri.getActiveRequest();
3919 if (null != activeRequest) {
3920 // If there is an active request, then for sure there is a satisfier.
3921 nri.getSatisfier().addRequest(activeRequest);
3922 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09003923 }
James Mattisf7027322020-12-13 16:28:14 -08003924
James Mattis45d81842021-01-10 14:24:24 -08003925 rematchAllNetworksAndRequests();
3926 for (final NetworkRequestInfo nri : nris) {
3927 // If the nri is satisfied, return as its score has already been sent if needed.
3928 if (nri.isBeingSatisfied()) {
3929 return;
3930 }
3931
3932 // As this request was not satisfied on rematch and thus never had any scores sent to
3933 // the factories, send null now for each request of type REQUEST.
3934 for (final NetworkRequest req : nri.mRequests) {
3935 if (req.isRequest()) sendUpdatedScoreToFactories(req, null);
3936 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003937 }
3938 }
3939
James Mattisf7027322020-12-13 16:28:14 -08003940 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3941 final int callingUid) {
3942 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003943 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08003944 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3945 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3946 handleReleaseNetworkRequest(
3947 nri.mRequests.get(0),
3948 callingUid,
3949 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003950 }
3951 }
3952
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003953 // Determines whether the network is the best (or could become the best, if it validated), for
3954 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3955 // on the value of reason:
3956 //
3957 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3958 // then it should be torn down.
3959 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3960 // then it should be lingered.
3961 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003962 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003963 final int numRequests;
3964 switch (reason) {
3965 case TEARDOWN:
3966 numRequests = nai.numRequestNetworkRequests();
3967 break;
3968 case LINGER:
3969 numRequests = nai.numForegroundNetworkRequests();
3970 break;
3971 default:
Aaron Huang6616df32020-10-30 22:04:25 +08003972 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003973 return true;
3974 }
3975
junyulai0ac374f2020-12-14 18:41:52 +08003976 if (!nai.everConnected || nai.isVPN() || nai.isInactive() || numRequests > 0) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003977 return false;
3978 }
Paul Jensende49eb12015-06-25 15:30:08 -04003979 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08003980 if (reason == UnneededFor.LINGER
3981 && !nri.isMultilayerRequest()
3982 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09003983 // Background requests don't affect lingering.
3984 continue;
3985 }
3986
James Mattis3d229892020-11-16 16:46:28 -08003987 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04003988 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05003989 }
3990 }
Paul Jensende49eb12015-06-25 15:30:08 -04003991 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05003992 }
3993
James Mattis3d229892020-11-16 16:46:28 -08003994 private boolean isNetworkPotentialSatisfier(
3995 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
3996 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08003997 // request, return immediately. For multilayer requests, check to see if any of the
3998 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08003999 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4000 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004001 return false;
4002 }
4003 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004004 // This multilayer listen request is satisfied therefore no further requests need to be
4005 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004006 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004007 return false;
4008 }
James Mattis3d229892020-11-16 16:46:28 -08004009 // As non-multilayer listen requests have already returned, the below would only happen
4010 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004011 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004012 continue;
4013 }
4014 // If this Network is already the highest scoring Network for a request, or if
4015 // there is hope for it to become one if it validated, then it is needed.
4016 if (candidate.satisfies(req)) {
4017 // As soon as a network is found that satisfies a request, return. Specifically for
4018 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4019 // is important so as to not evaluate lower priority requests further in
4020 // nri.mRequests.
4021 final boolean isNetworkNeeded = candidate.isSatisfyingRequest(req.requestId)
4022 // Note that this catches two important cases:
4023 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4024 // is currently satisfying the request. This is desirable when
4025 // cellular ends up validating but WiFi does not.
4026 // 2. Unvalidated WiFi will not be reaped when validated cellular
4027 // is currently satisfying the request. This is desirable when
4028 // WiFi ends up validating and out scoring cellular.
James Mattisa076c532020-12-02 14:12:41 -08004029 || nri.getSatisfier().getCurrentScore()
James Mattis3d229892020-11-16 16:46:28 -08004030 < candidate.getCurrentScoreAsValidated();
4031 return isNetworkNeeded;
4032 }
4033 }
4034
4035 return false;
4036 }
4037
Erik Kline0c04b742016-07-07 16:50:58 +09004038 private NetworkRequestInfo getNriForAppRequest(
4039 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004040 // Looking up the app passed param request in mRequests isn't possible since it may return
4041 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4042 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004043 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4044 // to avoid potential race conditions when validating a package->uid mapping when sending
4045 // the callback on the very low-chance that an application shuts down prior to the callback
4046 // being sent.
4047 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4048 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004049
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004050 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004051 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004052 log(String.format("UID %d attempted to %s for unowned request %s",
4053 callingUid, requestedOperation, nri));
4054 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004055 }
Erik Kline0c04b742016-07-07 16:50:58 +09004056 }
4057
4058 return nri;
4059 }
4060
James Mattisf7027322020-12-13 16:28:14 -08004061 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4062 final String callingMethod) {
4063 if (nri.isMultilayerRequest()) {
4064 throw new IllegalStateException(
4065 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004066 }
4067 }
4068
James Mattisf7027322020-12-13 16:28:14 -08004069 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004070 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004071 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4072 // single NetworkRequest and thus does not apply to multilayer requests.
4073 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4074 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004075 return;
4076 }
James Mattis2516da32021-01-31 17:06:19 -08004077 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004078 return;
4079 }
James Mattisf7027322020-12-13 16:28:14 -08004080 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4081 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004082 }
4083 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004084 callCallbackForRequest(
4085 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004086 }
4087
James Mattisf7027322020-12-13 16:28:14 -08004088 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4089 final int callingUid,
4090 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004091 final NetworkRequestInfo nri =
4092 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4093 if (nri == null) {
4094 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004095 }
James Mattisf7027322020-12-13 16:28:14 -08004096 if (VDBG || (DBG && request.isRequest())) {
4097 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004098 }
4099 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004100 if (callOnUnavailable) {
4101 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4102 }
Erik Kline155a59a2015-11-25 12:49:38 +09004103 }
Erik Kline0c04b742016-07-07 16:50:58 +09004104
James Mattisa076c532020-12-02 14:12:41 -08004105 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004106 ensureRunningOnConnectivityServiceThread();
Erik Kline0c04b742016-07-07 16:50:58 +09004107 nri.unlinkDeathRecipient();
James Mattisa076c532020-12-02 14:12:41 -08004108 for (final NetworkRequest req : nri.mRequests) {
4109 mNetworkRequests.remove(req);
4110 if (req.isListen()) {
4111 removeListenRequestFromNetworks(req);
4112 }
4113 }
Chalard Jean738c5bf2021-03-01 22:08:57 +09004114 if (mDefaultNetworkRequests.remove(nri)) {
4115 // If this request was one of the defaults, then the UID rules need to be updated
4116 // WARNING : if the app(s) for which this network request is the default are doing
4117 // traffic, this will kill their connected sockets, even if an equivalent request
4118 // is going to be reinstated right away ; unconnected traffic will go on the default
4119 // until the new default is set, which will happen very soon.
4120 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4121 // remove ranges for those requests that won't have a replacement
4122 final NetworkAgentInfo satisfier = nri.getSatisfier();
4123 if (null != satisfier) {
4124 try {
4125 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4126 toUidRangeStableParcels(nri.getUids()));
4127 } catch (RemoteException e) {
4128 loge("Exception setting network preference default network", e);
4129 }
4130 }
4131 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004132 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004133 mNetworkRequestInfoLogs.log("RELEASE " + nri);
James Mattisa076c532020-12-02 14:12:41 -08004134
4135 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004136 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004137 removeSatisfiedNetworkRequestFromNetwork(nri);
4138 } else {
4139 nri.setSatisfier(null, null);
4140 }
4141 }
4142
4143 cancelNpiRequests(nri);
4144 }
4145
James Mattis3ce3d3c2021-02-09 18:18:28 -08004146 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4147 for (final NetworkRequestInfo nri : nris) {
4148 if (mDefaultRequest == nri) {
4149 // Make sure we never remove the default request.
4150 continue;
4151 }
4152 handleRemoveNetworkRequest(nri);
4153 }
4154 }
4155
James Mattisa076c532020-12-02 14:12:41 -08004156 private void cancelNpiRequests(@NonNull final NetworkRequestInfo nri) {
4157 for (final NetworkRequest req : nri.mRequests) {
4158 cancelNpiRequest(req);
4159 }
4160 }
4161
4162 private void cancelNpiRequest(@NonNull final NetworkRequest req) {
4163 if (req.isRequest()) {
4164 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
4165 npi.cancelRequest(req);
4166 }
4167 }
4168 }
4169
4170 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4171 // listens don't have a singular affected Network. Check all networks to see
4172 // if this listen request applies and remove it.
4173 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4174 nai.removeRequest(req.requestId);
4175 if (req.networkCapabilities.hasSignalStrength()
4176 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4177 updateSignalStrengthThresholds(nai, "RELEASE", req);
4178 }
4179 }
4180 }
4181
4182 /**
4183 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4184 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4185 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4186 */
4187 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4188 boolean wasKept = false;
4189 final NetworkAgentInfo nai = nri.getSatisfier();
4190 if (nai != null) {
4191 final int requestLegacyType = nri.getActiveRequest().legacyType;
4192 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4193 nai.removeRequest(nri.getActiveRequest().requestId);
4194 if (VDBG || DDBG) {
4195 log(" Removing from current network " + nai.toShortString()
4196 + ", leaving " + nai.numNetworkRequests() + " requests.");
4197 }
4198 // If there are still lingered requests on this network, don't tear it down,
4199 // but resume lingering instead.
4200 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004201 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004202 notifyNetworkLosing(nai, now);
4203 }
4204 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4205 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4206 teardownUnneededNetwork(nai);
4207 } else {
4208 wasKept = true;
4209 }
4210 nri.setSatisfier(null, null);
4211 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4212 // Went from foreground to background.
4213 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004214 }
4215
Erik Kline0c04b742016-07-07 16:50:58 +09004216 // Maintain the illusion. When this request arrived, we might have pretended
4217 // that a network connected to serve it, even though the network was already
4218 // connected. Now that this request has gone away, we might have to pretend
4219 // that the network disconnected. LegacyTypeTracker will generate that
4220 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004221 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004222 boolean doRemove = true;
4223 if (wasKept) {
4224 // check if any of the remaining requests for this network are for the
4225 // same legacy type - if so, don't remove the nai
4226 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4227 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004228 if (otherRequest.legacyType == requestLegacyType
4229 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004230 if (DBG) log(" still have other legacy request - leaving");
4231 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004232 }
4233 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004234 }
4235
Erik Kline0c04b742016-07-07 16:50:58 +09004236 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004237 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004238 }
4239 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004240 }
4241 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004242
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004243 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4244 return checkAnyPermissionOf(
4245 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4246 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4247 }
4248
Lorenzo Colittid6459092016-07-04 12:55:44 +09004249 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004250 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004251 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004252 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004253 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004254 }
4255
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004256 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004257 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4258 enforceNetworkStackSettingsOrSetup();
4259 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4260 encodeBool(accept), encodeBool(always), network));
4261 }
4262
4263 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004264 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004265 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004266 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4267 }
4268
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004269 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4270 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4271 " accept=" + accept + " always=" + always);
4272
4273 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4274 if (nai == null) {
4275 // Nothing to do.
4276 return;
4277 }
4278
4279 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004280 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004281 return;
4282 }
4283
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004284 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004285 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004286 }
4287
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004288 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4289 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004290 // If network becomes partial connectivity and user already accepted to use this
4291 // network, we should respect the user's option and don't need to popup the
4292 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004293 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jeanfbc54672021-01-20 20:47:32 +09004294 nai.updateScoreForNetworkAgentConfigUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004295 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004296 sendUpdatedScoreToFactories(nai);
4297 }
4298
4299 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004300 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004301 }
4302
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004303 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004304 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004305 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004306 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004307 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004308 }
4309
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004310 }
4311
lucaslin2240ef62019-03-12 13:08:03 +08004312 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4313 boolean always) {
4314 if (DBG) {
4315 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4316 + " always=" + always);
4317 }
4318
4319 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4320 if (nai == null) {
4321 // Nothing to do.
4322 return;
4323 }
4324
4325 if (nai.lastValidated) {
4326 // The network validated while the dialog box was up. Take no action.
4327 return;
4328 }
4329
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004330 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4331 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004332 }
4333
4334 // TODO: Use the current design or save the user choice into IpMemoryStore.
4335 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004336 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004337 }
4338
4339 if (!accept) {
4340 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004341 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004342 // Tear down the network.
4343 teardownUnneededNetwork(nai);
4344 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004345 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4346 // result in a partial connectivity result which will be processed by
4347 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004348 //
4349 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4350 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004351 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004352 }
4353 }
4354
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004355 private void handleSetAvoidUnvalidated(Network network) {
4356 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4357 if (nai == null || nai.lastValidated) {
4358 // Nothing to do. The network either disconnected or revalidated.
4359 return;
4360 }
4361 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004362 nai.avoidUnvalidated = true;
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004363 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004364 sendUpdatedScoreToFactories(nai);
4365 }
4366 }
4367
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004368 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004369 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004370 mHandler.sendMessageDelayed(
4371 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4372 PROMPT_UNVALIDATED_DELAY_MS);
4373 }
4374
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004375 @Override
4376 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004377 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004378 mHandler.post(() -> {
4379 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4380 if (nai == null) return;
4381 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004382 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004383 });
4384 }
4385
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004386 /**
4387 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4388 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004389 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004390 * @param appExtras Bundle to use as intent extras for the captive portal application.
4391 * Must be treated as opaque to avoid preventing the captive portal app to
4392 * update its arguments.
4393 */
4394 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004395 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004396 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4397 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004398
4399 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4400 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004401 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4402 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004403 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4404
lucaslin75ff7022020-12-17 04:14:35 +08004405 final long token = Binder.clearCallingIdentity();
4406 try {
4407 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4408 } finally {
4409 Binder.restoreCallingIdentity(token);
4410 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004411 }
4412
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004413 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4414 private final Network mNetwork;
4415
4416 private CaptivePortalImpl(Network network) {
4417 mNetwork = network;
4418 }
4419
4420 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004421 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004422 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4423 enforceSettingsPermission();
4424 }
4425
Chiachang Wang938bfba2020-01-09 13:50:55 +08004426 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004427 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004428 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004429 }
4430
4431 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004432 public void appRequest(final int request) {
4433 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4434 if (nm == null) return;
4435
4436 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004437 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004438 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004439 }
4440 }
4441
4442 @Nullable
4443 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4444 // getNetworkAgentInfoForNetwork is thread-safe
4445 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4446 if (nai == null) return null;
4447
4448 // nai.networkMonitor() is thread-safe
4449 return nai.networkMonitor();
4450 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004451 }
4452
Hugo Benichic9048bc2016-09-14 23:23:08 +00004453 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004454 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004455 }
4456
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004457 /**
4458 * Return whether the device should maintain continuous, working connectivity by switching away
4459 * from WiFi networks having no connectivity.
4460 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4461 */
4462 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004463 if (!checkNetworkStackPermission()) {
4464 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4465 }
4466 return avoidBadWifi();
4467 }
4468
4469
Erik Kline95ecfee2016-10-02 18:02:14 +09004470 private void rematchForAvoidBadWifiUpdate() {
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004471 rematchAllNetworksAndRequests();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004472 for (NetworkAgentInfo nai: mNetworkAgentInfos) {
Erik Kline95ecfee2016-10-02 18:02:14 +09004473 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4474 sendUpdatedScoreToFactories(nai);
4475 }
4476 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004477 }
4478
Erik Kline95ecfee2016-10-02 18:02:14 +09004479 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004480 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004481 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004482 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004483 if (!configRestrict) {
4484 pw.println("Bad Wi-Fi avoidance: unrestricted");
4485 return;
4486 }
4487
4488 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4489 pw.increaseIndent();
4490 pw.println("Config restrict: " + configRestrict);
4491
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004492 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004493 String description;
4494 // Can't use a switch statement because strings are legal case labels, but null is not.
4495 if ("0".equals(value)) {
4496 description = "get stuck";
4497 } else if (value == null) {
4498 description = "prompt";
4499 } else if ("1".equals(value)) {
4500 description = "avoid";
4501 } else {
4502 description = value + " (?)";
4503 }
4504 pw.println("User setting: " + description);
4505 pw.println("Network overrides:");
4506 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004507 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004508 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004509 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004510 }
4511 }
4512 pw.decreaseIndent();
4513 pw.decreaseIndent();
4514 }
4515
paulhu7746e4e2020-06-09 19:07:03 +08004516 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4517 // unify the method.
4518 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4519 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4520 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4521 return settingsComponent != null
4522 ? settingsComponent.getPackageName() : "com.android.settings";
4523 }
4524
lucaslinb1e8e382019-01-24 15:55:30 +08004525 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004526 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004527 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004528 switch (type) {
4529 case NO_INTERNET:
4530 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004531 // High priority because it is only displayed for explicitly selected networks.
4532 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004533 break;
lucasline117e2e2019-10-22 18:27:33 +08004534 case PRIVATE_DNS_BROKEN:
4535 action = Settings.ACTION_WIRELESS_SETTINGS;
4536 // High priority because we should let user know why there is no internet.
4537 highPriority = true;
4538 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004539 case LOST_INTERNET:
4540 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004541 // High priority because it could help the user avoid unexpected data usage.
4542 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004543 break;
lucaslin2240ef62019-03-12 13:08:03 +08004544 case PARTIAL_CONNECTIVITY:
4545 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004546 // Don't bother the user with a high-priority notification if the network was not
4547 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004548 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004549 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004550 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004551 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004552 return;
4553 }
4554
4555 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004556 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004557 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004558 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004559 // Some OEMs have their own Settings package. Thus, need to get the current using
4560 // Settings package name instead of just use default name "com.android.settings".
4561 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4562 intent.setClassName(settingsPkgName,
4563 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004564 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004565
paulhu2af50222020-10-11 22:52:27 +08004566 PendingIntent pendingIntent = PendingIntent.getActivity(
4567 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004568 0 /* requestCode */,
4569 intent,
paulhu2af50222020-10-11 22:52:27 +08004570 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004571
Serik Beketayevec8ad212020-12-07 22:43:07 -08004572 mNotifier.showNotification(
4573 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004574 }
4575
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004576 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4577 // Don't prompt if the network is validated, and don't prompt on captive portals
4578 // because we're already prompting the user to sign in.
4579 if (nai.everValidated || nai.everCaptivePortalDetected) {
4580 return false;
4581 }
4582
4583 // If a network has partial connectivity, always prompt unless the user has already accepted
4584 // partial connectivity and selected don't ask again. This ensures that if the device
4585 // automatically connects to a network that has partial Internet access, the user will
4586 // always be able to use it, either because they've already chosen "don't ask again" or
4587 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004588 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004589 return true;
4590 }
4591
4592 // If a network has no Internet access, only prompt if the network was explicitly selected
4593 // and if the user has not already told us to use the network regardless of whether it
4594 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004595 if (nai.networkAgentConfig.explicitlySelected
4596 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004597 return true;
4598 }
4599
4600 return false;
4601 }
4602
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004603 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004604 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004605 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4606
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004607 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004608 return;
4609 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004610
4611 // Stop automatically reconnecting to this network in the future. Automatically connecting
4612 // to a network that provides no or limited connectivity is not useful, because the user
4613 // cannot use that network except through the notification shown by this method, and the
4614 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004615 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004616
lucaslin2240ef62019-03-12 13:08:03 +08004617 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4618 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4619 // popup the notification immediately when the network is partial connectivity.
4620 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004621 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004622 } else {
4623 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4624 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004625 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004626
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004627 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4628 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004629 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004630
lucaslin2240ef62019-03-12 13:08:03 +08004631 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4632 return;
4633 }
4634
4635 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004636 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004637 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004638 }
4639
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004640 @Override
4641 public int getMultipathPreference(Network network) {
4642 enforceAccessPermission();
4643
4644 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004645 if (nai != null && nai.networkCapabilities
4646 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004647 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4648 }
4649
Aaron Huang9a57acf2020-12-08 10:03:29 +08004650 final NetworkPolicyManager netPolicyManager =
4651 mContext.getSystemService(NetworkPolicyManager.class);
4652
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004653 final long token = Binder.clearCallingIdentity();
4654 final int networkPreference;
4655 try {
4656 networkPreference = netPolicyManager.getMultipathPreference(network);
4657 } finally {
4658 Binder.restoreCallingIdentity(token);
4659 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004660 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004661 return networkPreference;
4662 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004663 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4664 }
4665
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004666 @Override
4667 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004668 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004669 }
4670
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004671 private class InternalHandler extends Handler {
4672 public InternalHandler(Looper looper) {
4673 super(looper);
4674 }
4675
4676 @Override
4677 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004678 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004679 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004680 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004681 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004682 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004683 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004684 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004685 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004686 break;
4687 }
Jason Monka69f1b02013-10-10 14:02:51 -04004688 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004689 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4690 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004691 break;
4692 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004693 case EVENT_REGISTER_NETWORK_PROVIDER: {
4694 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004695 break;
4696 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004697 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4698 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004699 break;
4700 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004701 case EVENT_REGISTER_NETWORK_OFFER: {
4702 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4703 break;
4704 }
4705 case EVENT_UNREGISTER_NETWORK_OFFER: {
4706 final NetworkOfferInfo offer =
4707 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4708 if (null != offer) {
4709 handleUnregisterNetworkOffer(offer);
4710 }
4711 break;
4712 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004713 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004714 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4715 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4716 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004717 break;
4718 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004719 case EVENT_REGISTER_NETWORK_REQUEST:
4720 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09004721 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004722 break;
4723 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004724 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4725 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004726 handleRegisterNetworkRequestWithIntent(msg);
4727 break;
4728 }
Erik Kline155a59a2015-11-25 12:49:38 +09004729 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4730 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4731 handleTimedOutNetworkRequest(nri);
4732 break;
4733 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004734 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4735 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4736 break;
4737 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004738 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08004739 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4740 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004741 break;
4742 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004743 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09004744 Network network = (Network) msg.obj;
4745 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004746 break;
4747 }
lucaslin2240ef62019-03-12 13:08:03 +08004748 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4749 Network network = (Network) msg.obj;
4750 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4751 toBool(msg.arg2));
4752 break;
4753 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004754 case EVENT_SET_AVOID_UNVALIDATED: {
4755 handleSetAvoidUnvalidated((Network) msg.obj);
4756 break;
4757 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004758 case EVENT_PROMPT_UNVALIDATED: {
4759 handlePromptUnvalidated((Network) msg.obj);
4760 break;
4761 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07004762 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4763 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09004764 break;
4765 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004766 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08004767 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004768 mKeepaliveTracker.handleStartKeepalive(msg);
4769 break;
4770 }
4771 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08004772 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004773 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4774 int slot = msg.arg1;
4775 int reason = msg.arg2;
4776 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4777 break;
4778 }
Hugo Benichid6b510a2017-04-06 17:22:18 +09004779 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichif4210292017-04-21 15:07:12 +09004780 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09004781 break;
4782 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004783 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4784 handlePrivateDnsSettingsChanged();
4785 break;
dalyk1720e542018-03-05 12:42:22 -05004786 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4787 handlePrivateDnsValidationUpdate(
4788 (PrivateDnsValidationUpdate) msg.obj);
4789 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00004790 case EVENT_UID_BLOCKED_REASON_CHANGED:
4791 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08004792 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09004793 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4794 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4795 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004796 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09004797 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4798 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004799 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08004800 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004801 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09004802 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4803 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4804 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4805 msg.obj;
4806 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08004807 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09004808 }
lucaslin1193a5d2021-01-21 02:04:15 +08004809 case EVENT_REPORT_NETWORK_ACTIVITY:
4810 mNetworkActivityTracker.handleReportNetworkActivity();
4811 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004812 }
4813 }
4814 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004815
Lorenzo Colittid6459092016-07-04 12:55:44 +09004816 @Override
markchien5776f962019-12-16 20:15:20 +08004817 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004818 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08004819 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4820 Context.TETHERING_SERVICE);
4821 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -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[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08004827 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4828 Context.TETHERING_SERVICE);
4829 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004830 }
4831
Lorenzo Colittid6459092016-07-04 12:55:44 +09004832 @Override
markchien5776f962019-12-16 20:15:20 +08004833 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004834 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08004835 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4836 Context.TETHERING_SERVICE);
4837 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004838 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004839
markchien5776f962019-12-16 20:15:20 +08004840
Lorenzo Colittid6459092016-07-04 12:55:44 +09004841 @Override
markchien5776f962019-12-16 20:15:20 +08004842 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004843 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08004844 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4845 Context.TETHERING_SERVICE);
4846
4847 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004848 }
4849
Lorenzo Colittid6459092016-07-04 12:55:44 +09004850 @Override
markchien5776f962019-12-16 20:15:20 +08004851 @Deprecated
4852 public String[] getTetherableUsbRegexs() {
4853 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4854 Context.TETHERING_SERVICE);
4855
4856 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07004857 }
4858
Udam Saini8f7d6a72017-06-07 12:06:28 -07004859 @Override
markchien5776f962019-12-16 20:15:20 +08004860 @Deprecated
4861 public String[] getTetherableWifiRegexs() {
4862 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4863 Context.TETHERING_SERVICE);
4864 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08004865 }
4866
Robert Greenwalte0b00512014-07-02 09:59:16 -07004867 // Called when we lose the default network and have no replacement yet.
4868 // This will automatically be cleared after X seconds or a new default network
4869 // becomes CONNECTED, whichever happens first. The timer is started by the
4870 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09004871 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004872 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004873 if (mNetTransitionWakeLock.isHeld()) {
4874 return;
4875 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004876 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004877 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4878 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004879 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004880 mWakelockLogs.log("ACQUIRE for " + forWhom);
4881 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09004882 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09004883 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09004884 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004885 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07004886
Hugo Benichi471b62a2017-03-30 23:18:10 +09004887 // Called when we gain a new default network to release the network transition wakelock in a
4888 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4889 // message is cancelled.
4890 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09004891 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004892 if (!mNetTransitionWakeLock.isHeld()) {
4893 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09004894 }
4895 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004896 // Cancel self timeout on wakelock hold.
4897 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4898 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4899 mHandler.sendMessageDelayed(msg, 1000);
4900 }
4901
4902 // Called when either message of ensureNetworkTransitionWakelock or
4903 // scheduleReleaseNetworkTransitionWakelock is processed.
4904 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4905 String event = eventName(eventId);
4906 synchronized (this) {
4907 if (!mNetTransitionWakeLock.isHeld()) {
4908 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08004909 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09004910 return;
4911 }
4912 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004913 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4914 mTotalWakelockDurationMs += lockDuration;
4915 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4916 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09004917 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004918 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09004919 }
4920
Robert Greenwalt986c7412010-09-08 15:24:47 -07004921 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09004922 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07004923 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07004924 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09004925 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04004926 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07004927 }
4928
Lorenzo Colittid6459092016-07-04 12:55:44 +09004929 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04004930 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04004931 enforceAccessPermission();
4932 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004933 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09004934 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08004935
Cody Kesting3d1df812020-06-25 11:13:39 -07004936 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4937 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4938 // does not match the known connectivity of the network - this causes NetworkMonitor to
4939 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08004940 final NetworkAgentInfo nai;
4941 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004942 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08004943 } else {
4944 nai = getNetworkAgentInfoForNetwork(network);
4945 }
4946 if (nai != null) {
4947 mConnectivityDiagnosticsHandler.sendMessage(
4948 mConnectivityDiagnosticsHandler.obtainMessage(
4949 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4950 connectivityInfo, 0, nai));
4951 }
Cody Kesting3d1df812020-06-25 11:13:39 -07004952
4953 mHandler.sendMessage(
4954 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
Hugo Benichid6b510a2017-04-06 17:22:18 +09004955 }
Paul Jensen83f5d572014-08-29 09:54:01 -04004956
Hugo Benichid6b510a2017-04-06 17:22:18 +09004957 private void handleReportNetworkConnectivity(
4958 Network network, int uid, boolean hasConnectivity) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09004959 final NetworkAgentInfo nai;
Paul Jensenb95d7952015-04-07 12:43:13 -04004960 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004961 nai = getDefaultNetwork();
Paul Jensenb95d7952015-04-07 12:43:13 -04004962 } else {
4963 nai = getNetworkAgentInfoForNetwork(network);
4964 }
Paul Jensen3c3c6e82015-06-25 10:28:34 -04004965 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4966 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4967 return;
4968 }
Paul Jensenb95d7952015-04-07 12:43:13 -04004969 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09004970 if (hasConnectivity == nai.lastValidated) {
4971 return;
4972 }
Paul Jensenb95d7952015-04-07 12:43:13 -04004973 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004974 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09004975 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04004976 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09004977 // Validating a network that has not yet connected could result in a call to
4978 // rematchNetworkAndRequests() which is not meant to work on such networks.
4979 if (!nai.everConnected) {
4980 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04004981 }
paulhu7aeba372020-12-30 00:42:19 +08004982 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
4983 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09004984 return;
4985 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004986 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004987 }
4988
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09004989 // TODO: call into netd.
4990 private boolean queryUserAccess(int uid, Network network) {
4991 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4992 if (nai == null) return false;
4993
4994 // Any UID can use its default network.
4995 if (nai == getDefaultNetworkForUid(uid)) return true;
4996
4997 // Privileged apps can use any network.
4998 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
4999 return true;
5000 }
5001
5002 // An unprivileged UID can use a VPN iff the VPN applies to it.
5003 if (nai.isVPN()) {
5004 return nai.networkCapabilities.appliesToUid(uid);
5005 }
5006
5007 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5008 // sockets, i.e., if it is the owner.
5009 final NetworkAgentInfo vpn = getVpnForUid(uid);
5010 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5011 && uid != vpn.networkCapabilities.getOwnerUid()) {
5012 return false;
5013 }
5014
5015 // The UID's permission must be at least sufficient for the network. Since the restricted
5016 // permission was already checked above, that just leaves background networks.
5017 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5018 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5019 }
5020
5021 // Unrestricted network. Anyone gets to use it.
5022 return true;
5023 }
5024
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005025 /**
5026 * Returns information about the proxy a certain network is using. If given a null network, it
5027 * it will return the proxy for the bound network for the caller app or the default proxy if
5028 * none.
5029 *
5030 * @param network the network we want to get the proxy information for.
5031 * @return Proxy information if a network has a proxy configured, or otherwise null.
5032 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005033 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005034 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005035 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005036 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005037 if (network == null) {
5038 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005039 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005040 true);
5041 if (activeNetwork == null) {
5042 return null;
5043 }
5044 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005045 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005046 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5047 // caller may not have.
5048 return getLinkPropertiesProxyInfo(network);
5049 }
5050 // No proxy info available if the calling UID does not have network access.
5051 return null;
5052 }
5053
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005054
5055 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005056 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5057 if (nai == null) return null;
5058 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005059 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5060 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005061 }
5062 }
5063
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005064 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005065 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005066 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005067 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005068 }
5069
Chalard Jean777e2e52018-06-07 18:02:37 +09005070 @Override
5071 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005072 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005073 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005074 }
5075
Jason Monk4d5e20f2014-04-25 15:00:09 -04005076 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005077 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005078 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005079 proxy = null;
5080 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005081 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005082 }
5083
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005084 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5085 // when any network changes proxy.
5086 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5087 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005088 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005089 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5090 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5091
Chalard Jean7d97afc2018-06-07 17:41:29 +09005092 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005093 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005094 }
5095 }
5096
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005097 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005098 final private HashMap<Uri, Integer> mUriEventMap;
5099 final private Context mContext;
5100 final private Handler mHandler;
5101
5102 SettingsObserver(Context context, Handler handler) {
5103 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005104 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005105 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005106 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005107 }
5108
Erik Kline05f2b402015-04-30 12:58:40 +09005109 void observe(Uri uri, int what) {
5110 mUriEventMap.put(uri, what);
5111 final ContentResolver resolver = mContext.getContentResolver();
5112 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005113 }
5114
5115 @Override
5116 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005117 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005118 }
5119
5120 @Override
5121 public void onChange(boolean selfChange, Uri uri) {
5122 final Integer what = mUriEventMap.get(uri);
5123 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005124 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005125 } else {
5126 loge("No matching event to send for URI=" + uri);
5127 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005128 }
5129 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005130
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005131 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005132 Log.d(TAG, s);
5133 }
5134
5135 private static void logw(String s) {
5136 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005137 }
5138
Daniel Brightf9e945b2020-06-15 16:10:01 -07005139 private static void logwtf(String s) {
5140 Log.wtf(TAG, s);
5141 }
5142
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005143 private static void logwtf(String s, Throwable t) {
5144 Log.wtf(TAG, s, t);
5145 }
5146
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005147 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005148 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005149 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005150
Hugo Benichi39621362017-02-11 17:04:43 +09005151 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005152 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005153 }
5154
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005155 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005156 * Return the information of all ongoing VPNs.
5157 *
5158 * <p>This method is used to update NetworkStatsService.
5159 *
5160 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005161 */
junyulai2050bed2021-01-23 09:46:34 +08005162 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005163 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005164 if (mLockdownEnabled) {
5165 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005166 }
junyulai2050bed2021-01-23 09:46:34 +08005167 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005168 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005169 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005170 if (info != null) {
5171 infoList.add(info);
5172 }
5173 }
junyulai2050bed2021-01-23 09:46:34 +08005174 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005175 }
5176
5177 /**
5178 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005179 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005180 */
junyulai2050bed2021-01-23 09:46:34 +08005181 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005182 if (!nai.isVPN()) return null;
5183
5184 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005185 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5186 // the underlyingNetworks list.
5187 if (underlyingNetworks == null) {
James Mattis2516da32021-01-31 17:06:19 -08005188 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5189 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005190 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005191 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005192 }
5193 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005194
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005195 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005196
5197 List<String> interfaces = new ArrayList<>();
5198 for (Network network : underlyingNetworks) {
5199 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5200 if (underlyingNai == null) continue;
5201 LinkProperties lp = underlyingNai.linkProperties;
5202 for (String iface : lp.getAllInterfaceNames()) {
5203 if (!TextUtils.isEmpty(iface)) {
5204 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005205 }
5206 }
Benedict Wong34857f82019-06-12 17:46:15 +00005207 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005208
5209 if (interfaces.isEmpty()) return null;
5210
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005211 // Must be non-null or NetworkStatsService will crash.
5212 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5213 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005214 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005215 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005216
junyulai2050bed2021-01-23 09:46:34 +08005217 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5218 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005219 }
5220
James Mattisd31bdfa2020-12-23 16:37:26 -08005221 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005222 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5223 Network[] underlyingNetworks) {
5224 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005225 if (underlyingNetworks == null && defaultNetwork != null) {
5226 // null underlying networks means to track the default.
5227 underlyingNetworks = new Network[] { defaultNetwork };
5228 }
5229 return underlyingNetworks;
5230 }
5231
5232 // Returns true iff |network| is an underlying network of |nai|.
5233 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5234 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5235 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5236 if (!nai.supportsUnderlyingNetworks()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005237 final Network[] underlying = underlyingNetworksOrDefault(
5238 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005239 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005240 }
5241
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005242 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005243 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005244 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005245 * When underlying networks change, such networks may have to update capabilities to reflect
5246 * things like the metered bit, their transports, and so on. The capabilities are calculated
5247 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005248 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005249 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005250 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005251 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005252 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005253 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005254 }
5255 }
5256 }
5257
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005258 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5259 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5260 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5261 // a VPN is not up.
5262 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5263 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5264 for (UidRange range : blockedUidRanges) {
5265 if (range.contains(uid)) return true;
5266 }
5267 return false;
5268 }
5269
5270 @Override
5271 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005272 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005273 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5274 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5275 }
5276
5277 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5278 if (DBG) {
5279 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5280 + Arrays.toString(ranges));
5281 }
5282 // Cannot use a Set since the list of UID ranges might contain duplicates.
5283 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5284 for (int i = 0; i < ranges.length; i++) {
5285 if (requireVpn) {
5286 newVpnBlockedUidRanges.add(ranges[i]);
5287 } else {
5288 newVpnBlockedUidRanges.remove(ranges[i]);
5289 }
5290 }
5291
5292 try {
5293 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5294 } catch (RemoteException | ServiceSpecificException e) {
5295 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5296 + Arrays.toString(ranges) + "): netd command failed: " + e);
5297 }
5298
5299 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5300 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005301 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5302 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005303 }
5304
5305 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5306 }
5307
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005308 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005309 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005310 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005311 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005312 }
5313
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005314 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5315 return mLockdownEnabled
5316 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5317 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005318 }
5319
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005320 private NetworkAgentInfo getLegacyLockdownNai() {
5321 if (!mLockdownEnabled) {
5322 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005323 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005324 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005325 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5326 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005327
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005328 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005329 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5330 // a local variable. There is no need to make a copy because its contents cannot change.
5331 final Network[] underlying = nai.declaredUnderlyingNetworks;
5332 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005333 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005334 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005335
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005336 // The legacy lockdown VPN always uses the default network.
5337 // If the VPN's underlying network is no longer the current default network, it means that
5338 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005339 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5340 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005341 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005342 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005343 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005344 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005345
5346 return nai;
5347 };
5348
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005349 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5350 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5351 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005352 private DetailedState getLegacyLockdownState(DetailedState origState) {
5353 if (origState != DetailedState.CONNECTED) {
5354 return origState;
5355 }
5356 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5357 ? DetailedState.CONNECTING
5358 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005359 }
5360
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005361 private void filterForLegacyLockdown(NetworkInfo ni) {
5362 if (!mLockdownEnabled || !ni.isConnected()) return;
5363 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5364 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5365 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5366 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5367 // network, this time with a state of CONNECTED.
5368 //
5369 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5370 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5371 // is not too far off the truth, since an always-on VPN, when not connected, is always
5372 // trying to reconnect.
5373 if (getLegacyLockdownNai() == null) {
5374 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5375 }
5376 }
5377
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005378 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005379 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005380 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005381 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005382 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5383 return;
5384 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005385 final long ident = Binder.clearCallingIdentity();
5386 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005387 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005388 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005389 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005390 } finally {
5391 Binder.restoreCallingIdentity(ident);
5392 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005393 }
Wink Savillecb117d32013-08-29 14:57:08 -07005394
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005395 @Override
5396 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005397 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005398 final long ident = Binder.clearCallingIdentity();
5399 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005400 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005401 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005402 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5403 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005404 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005405 } finally {
5406 Binder.restoreCallingIdentity(ident);
5407 }
5408 }
5409
James Mattis02220e22021-03-13 19:27:21 -08005410 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005411 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005412 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5413 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5414 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005415 }
5416
James Mattis02220e22021-03-13 19:27:21 -08005417 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005418 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005419 // If there was a network preference for this user, remove it.
5420 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5421 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005422 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5423 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5424 }
junyulaid91e7052020-08-28 13:44:33 +08005425 }
5426
James Mattis02220e22021-03-13 19:27:21 -08005427 private void onPackageChanged(@NonNull final String packageName) {
5428 // This is necessary in case a package is added or removed, but also when it's replaced to
5429 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5430 // as one in the preferences, then it should follow the same routing as that other package,
5431 // which means updating the rules is never to be needed in this case (whether it joins or
5432 // leaves a UID with a preference).
5433 if (isMappedInOemNetworkPreference(packageName)) {
5434 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5435 }
5436 }
5437
5438 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005439 @Override
5440 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005441 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005442 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005443 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005444
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005445 // User should be filled for below intents, check the existence.
5446 if (user == null) {
5447 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5448 return;
5449 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005450
Lorenzo Colitticd675292021-02-04 17:32:07 +09005451 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005452 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005453 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005454 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005455 } else {
junyulaid91e7052020-08-28 13:44:33 +08005456 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005457 }
5458 }
5459 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005460
James Mattis02220e22021-03-13 19:27:21 -08005461 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5462 @Override
5463 public void onReceive(Context context, Intent intent) {
5464 ensureRunningOnConnectivityServiceThread();
5465 switch (intent.getAction()) {
5466 case Intent.ACTION_PACKAGE_ADDED:
5467 case Intent.ACTION_PACKAGE_REMOVED:
5468 case Intent.ACTION_PACKAGE_REPLACED:
5469 onPackageChanged(intent.getData().getSchemeSpecificPart());
5470 break;
5471 default:
5472 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5473 }
5474 }
5475 };
5476
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005477 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005478 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005479
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005480 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005481 public final String name;
5482 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005483 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005484 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005485
lifraf3a3492021-03-10 13:58:14 +08005486 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5487 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005488 this.name = name;
5489 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005490 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005491 mDeathRecipient = deathRecipient;
5492
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005493 if (mDeathRecipient == null) {
5494 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005495 }
5496 }
5497
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005498 void sendMessageToNetworkProvider(int what, int arg1, int arg2, Object obj) {
5499 try {
5500 messenger.send(Message.obtain(null /* handler */, what, arg1, arg2, obj));
5501 } catch (RemoteException e) {
5502 // Remote process died. Ignore; the death recipient will remove this
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005503 // NetworkProviderInfo from mNetworkProviderInfos.
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005504 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005505 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005506
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005507 void requestNetwork(NetworkRequest request, int score, int servingProviderId) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005508 sendMessageToNetworkProvider(NetworkProvider.CMD_REQUEST_NETWORK, score,
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005509 servingProviderId, request);
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005510 }
5511
5512 void cancelRequest(NetworkRequest request) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005513 sendMessageToNetworkProvider(NetworkProvider.CMD_CANCEL_REQUEST, 0, 0, request);
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005514 }
5515
5516 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005517 try {
5518 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5519 } catch (RemoteException e) {
5520 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005521 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005522 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005523 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005524
James Mattis4fce5d12020-11-12 15:53:42 -08005525 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5526 for (int i = 0; i < requests.size(); i++) {
5527 ensureNetworkRequestHasType(requests.get(i));
5528 }
5529 }
5530
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005531 private void ensureNetworkRequestHasType(NetworkRequest request) {
5532 if (request.type == NetworkRequest.Type.NONE) {
5533 throw new IllegalArgumentException(
5534 "All NetworkRequests in ConnectivityService must have a type");
5535 }
5536 }
5537
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005538 /**
5539 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005540 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005541 */
James Mattis258ea3c2020-11-15 15:04:40 -08005542 @VisibleForTesting
5543 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005544 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5545 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005546 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005547
James Mattisa076c532020-12-02 14:12:41 -08005548 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5549 void setSatisfier(
5550 @Nullable final NetworkAgentInfo satisfier,
5551 @Nullable final NetworkRequest activeRequest) {
5552 mSatisfier = satisfier;
5553 mActiveRequest = activeRequest;
5554 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005555
James Mattisd31bdfa2020-12-23 16:37:26 -08005556 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005557 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005558 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005559 private NetworkAgentInfo mSatisfier;
5560 NetworkAgentInfo getSatisfier() {
5561 return mSatisfier;
5562 }
5563
5564 // The request in mRequests assigned to a network agent. This is null if none of the
5565 // requests in mRequests can be satisfied. This member has the constraint of only being
5566 // accessible on the handler thread.
5567 @Nullable
5568 private NetworkRequest mActiveRequest;
5569 NetworkRequest getActiveRequest() {
5570 return mActiveRequest;
5571 }
5572
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005573 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005574 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005575 @Nullable
5576 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005577
5578 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005579 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005580 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005581 final int mPid;
5582 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005583 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005584 @Nullable
5585 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005586
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005587 // Counter keeping track of this NRI.
5588 final PerUidCounter mPerUidCounter;
5589
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005590 // Effective UID of this request. This is different from mUid when a privileged process
5591 // files a request on behalf of another UID. This UID is used to determine blocked status,
5592 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5593 // maximum limit of registered callbacks per UID.
5594 final int mAsUid;
5595
James Mattis3ce3d3c2021-02-09 18:18:28 -08005596 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5597 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5598 // maintained for keying off of. This is only a concern when the original nri
5599 // mNetworkRequests changes which happens currently for apps that register callbacks to
5600 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5601 // that match the per-app default nri that currently tracks the calling app's uid so that
5602 // callbacks are fired at the appropriate time. When the callbacks fire,
5603 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5604 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5605 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5606 @NonNull
5607 private final NetworkRequest mNetworkRequestForCallback;
5608 NetworkRequest getNetworkRequestForCallback() {
5609 return mNetworkRequestForCallback;
5610 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005611
James Mattisd31bdfa2020-12-23 16:37:26 -08005612 /**
5613 * Get the list of UIDs this nri applies to.
5614 */
5615 @NonNull
5616 private Set<UidRange> getUids() {
5617 // networkCapabilities.getUids() returns a defensive copy.
5618 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005619 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5620 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005621 }
5622
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005623 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5624 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5625 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005626 }
5627
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005628 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005629 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5630 @Nullable String callingAttributionTag) {
5631 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005632 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005633 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005634 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005635 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005636 mBinder = null;
5637 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005638 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005639 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005640 mPerUidCounter = getRequestCounter(this);
5641 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005642 /**
5643 * Location sensitive data not included in pending intent. Only included in
5644 * {@link NetworkCallback}.
5645 */
5646 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005647 mCallingAttributionTag = callingAttributionTag;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005648 }
5649
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005650 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005651 @Nullable final IBinder binder,
5652 @NetworkCallback.Flag int callbackFlags,
5653 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005654 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5655 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005656 }
5657
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005658 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005659 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005660 @Nullable final IBinder binder,
5661 @NetworkCallback.Flag int callbackFlags,
5662 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005663 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005664 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005665 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005666 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005667 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005668 mBinder = binder;
5669 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005670 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005671 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005672 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005673 mPerUidCounter = getRequestCounter(this);
5674 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005675 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005676 mCallingAttributionTag = callingAttributionTag;
James Mattisb1392002021-03-31 13:57:52 -07005677 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005678 }
5679
James Mattis3ce3d3c2021-02-09 18:18:28 -08005680 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5681 @NonNull final List<NetworkRequest> r) {
5682 super();
5683 ensureAllNetworkRequestsHaveType(r);
5684 mRequests = initializeRequests(r);
5685 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005686 final NetworkAgentInfo satisfier = nri.getSatisfier();
5687 if (null != satisfier) {
5688 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5689 // The active request is necessary to figure out what callbacks to send, in
5690 // particular then a network updates its capabilities.
5691 // As this code creates a new NRI with a new set of requests, figure out which of
5692 // the list of requests should be the active request. It is always the first
5693 // request of the list that can be satisfied by the satisfier since the order of
5694 // requests is a priority order.
5695 // Note even in the presence of a satisfier there may not be an active request,
5696 // when the satisfier is the no-service network.
5697 NetworkRequest activeRequest = null;
5698 for (final NetworkRequest candidate : r) {
5699 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5700 activeRequest = candidate;
5701 break;
5702 }
5703 }
5704 setSatisfier(satisfier, activeRequest);
5705 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005706 mMessenger = nri.mMessenger;
5707 mBinder = nri.mBinder;
5708 mPid = nri.mPid;
5709 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005710 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005711 mPendingIntent = nri.mPendingIntent;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005712 mPerUidCounter = getRequestCounter(this);
5713 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005714 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005715 mCallingAttributionTag = nri.mCallingAttributionTag;
James Mattisb1392002021-03-31 13:57:52 -07005716 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005717 }
5718
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005719 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5720 this(asUid, Collections.singletonList(r));
James Mattis45d81842021-01-10 14:24:24 -08005721 }
5722
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005723 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5724 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
Cody Kesting73708bf2019-12-18 10:57:50 -08005725 }
5726
James Mattis2516da32021-01-31 17:06:19 -08005727 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5728 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5729 // false.
5730 boolean isBeingSatisfied() {
5731 return (null != mSatisfier && null != mActiveRequest);
5732 }
5733
James Mattis3d229892020-11-16 16:46:28 -08005734 boolean isMultilayerRequest() {
5735 return mRequests.size() > 1;
5736 }
5737
James Mattis45d81842021-01-10 14:24:24 -08005738 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5739 // Creating a defensive copy to prevent the sender from modifying the list being
5740 // reflected in the return value of this method.
5741 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08005742 return Collections.unmodifiableList(tempRequests);
5743 }
5744
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005745 void decrementRequestCount() {
5746 mPerUidCounter.decrementCount(mUid);
5747 }
5748
James Mattisb1392002021-03-31 13:57:52 -07005749 void linkDeathRecipient() {
5750 if (null != mBinder) {
5751 try {
5752 mBinder.linkToDeath(this, 0);
5753 } catch (RemoteException e) {
5754 binderDied();
5755 }
5756 }
5757 }
5758
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005759 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07005760 if (null != mBinder) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005761 mBinder.unlinkToDeath(this, 0);
5762 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005763 }
5764
James Mattis4fce5d12020-11-12 15:53:42 -08005765 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005766 public void binderDied() {
5767 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis4fce5d12020-11-12 15:53:42 -08005768 mRequests + ", " + mBinder + ")");
James Mattisa152f882020-11-20 16:08:10 -08005769 releaseNetworkRequests(mRequests);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005770 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005771
James Mattis4fce5d12020-11-12 15:53:42 -08005772 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005773 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005774 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5775 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08005776 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005777 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005778 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08005779 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08005780 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
Roshan Piuse1220262021-03-11 21:16:44 -08005781 + " callback flags: " + mCallbackFlags;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005782 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005783 }
5784
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09005785 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5786 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5787 if (badCapability != null) {
5788 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04005789 }
5790 }
5791
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005792 // This checks that the passed capabilities either do not request a
5793 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005794 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08005795 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09005796 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005797 throw new SecurityException("Insufficient permissions to request a specific SSID");
5798 }
paulhu1a407652019-03-22 16:35:06 +08005799
5800 if (nc.hasSignalStrength()
5801 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5802 throw new SecurityException(
5803 "Insufficient permissions to request a specific signal strength");
5804 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08005805 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07005806
junyulai2217bec2021-04-14 23:33:31 +08005807 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07005808 enforceNetworkFactoryPermission();
5809 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005810 }
5811
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005812 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005813 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005814 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08005815 // mNetworkRequests may contain the same value multiple times in case of
5816 // multilayer requests. It won't matter in this case because the thresholds
5817 // will then be the same and be deduplicated as they enter the `thresholds` set.
5818 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08005819 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5820 for (final NetworkRequest req : nri.mRequests) {
5821 if (req.networkCapabilities.hasSignalStrength()
5822 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5823 thresholds.add(req.networkCapabilities.getSignalStrength());
5824 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005825 }
5826 }
5827 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005828 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005829 }
5830
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005831 private void updateSignalStrengthThresholds(
5832 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005833 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005834
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09005835 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005836 String detail;
5837 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5838 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5839 } else {
5840 detail = reason;
5841 }
5842 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005843 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005844 }
5845
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005846 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005847 }
5848
Etan Cohen1b6d4182017-04-03 17:42:34 -07005849 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5850 if (nc == null) {
5851 return;
5852 }
5853 NetworkSpecifier ns = nc.getNetworkSpecifier();
5854 if (ns == null) {
5855 return;
5856 }
lucaslin22f9b9f2021-01-22 15:15:23 +08005857 if (ns instanceof MatchAllNetworkSpecifier) {
5858 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5859 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07005860 }
5861
lucasline117e2e2019-10-22 18:27:33 +08005862 private void ensureValid(NetworkCapabilities nc) {
5863 ensureValidNetworkSpecifier(nc);
5864 if (nc.isPrivateDnsBroken()) {
5865 throw new IllegalArgumentException("Can't request broken private DNS");
5866 }
5867 }
5868
Roshan Pius951c0032020-12-22 15:10:42 -08005869 private boolean isTargetSdkAtleast(int version, int callingUid,
5870 @NonNull String callingPackageName) {
5871 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08005872 final PackageManager pm =
5873 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08005874 try {
Roshan Pius951c0032020-12-22 15:10:42 -08005875 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08005876 if (callingVersion < version) return false;
5877 } catch (PackageManager.NameNotFoundException e) { }
5878 return true;
5879 }
5880
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005881 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005882 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
junyulaiad010792021-01-11 16:53:38 +08005883 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08005884 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08005885 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08005886 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08005887 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5888 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08005889 throw new SecurityException("Insufficient permissions to specify legacy type");
5890 }
markchienfac84a22020-03-18 21:16:15 +08005891 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005892 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005893 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005894 // Privileged callers can track the default network of another UID by passing in a UID.
5895 if (asUid != Process.INVALID_UID) {
5896 enforceSettingsPermission();
5897 } else {
5898 asUid = callingUid;
5899 }
junyulaiad010792021-01-11 16:53:38 +08005900 final NetworkRequest.Type reqType;
5901 try {
5902 reqType = NetworkRequest.Type.values()[reqTypeInt];
5903 } catch (ArrayIndexOutOfBoundsException e) {
5904 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5905 }
5906 switch (reqType) {
5907 case TRACK_DEFAULT:
5908 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005909 // is unused and will be replaced by ones appropriate for the UID (usually, the
5910 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08005911 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005912 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08005913 enforceAccessPermission();
5914 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005915 case TRACK_SYSTEM_DEFAULT:
5916 enforceSettingsPermission();
5917 networkCapabilities = new NetworkCapabilities(defaultNc);
5918 break;
Junyu Laia62493f2021-01-19 11:10:56 +00005919 case BACKGROUND_REQUEST:
5920 enforceNetworkStackOrSettingsPermission();
5921 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08005922 case REQUEST:
5923 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5924 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5925 callingAttributionTag);
5926 // TODO: this is incorrect. We mark the request as metered or not depending on
5927 // the state of the app when the request is filed, but we never change the
5928 // request if the app changes network state. http://b/29964605
5929 enforceMeteredApnPolicy(networkCapabilities);
5930 break;
junyulai1b1c8742021-03-12 20:05:08 +08005931 case LISTEN_FOR_BEST:
5932 enforceAccessPermission();
5933 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5934 break;
junyulaiad010792021-01-11 16:53:38 +08005935 default:
5936 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09005937 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09005938 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005939 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08005940 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005941
junyulai1b1c8742021-03-12 20:05:08 +08005942 // Enforce FOREGROUND if the caller does not have permission to use background network.
5943 if (reqType == LISTEN_FOR_BEST) {
5944 restrictBackgroundRequestForCaller(networkCapabilities);
5945 }
5946
5947 // Set the UID range for this request to the single UID of the requester, unless the
5948 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09005949 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5950 // are no visible methods to set the UIDs, an app could use reflection to try and get
5951 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08005952 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08005953 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5954 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005955
Etan Cohen85000162017-02-05 10:42:27 -08005956 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005957 throw new IllegalArgumentException("Bad timeout specified");
5958 }
lucasline117e2e2019-10-22 18:27:33 +08005959 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08005960
James Mattis3ce3d3c2021-02-09 18:18:28 -08005961 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08005962 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005963 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005964 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005965 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09005966 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005967
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005968 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5969 // copied from the default request above. (This is necessary to ensure, for example, that
5970 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5971 // changes don't alter request matching.
5972 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5973 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09005974 throw new IllegalStateException(
5975 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005976 + networkCapabilities + " vs. " + defaultNc);
5977 }
5978
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005979 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07005980 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005981 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07005982 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005983 }
5984 return networkRequest;
5985 }
5986
James Mattis3ce3d3c2021-02-09 18:18:28 -08005987 /**
5988 * Return the nri to be used when registering a network request. Specifically, this is used with
5989 * requests registered to track the default request. If there is currently a per-app default
5990 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5991 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005992 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5993 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08005994 * @param nr the network request for the nri.
5995 * @param msgr the messenger for the nri.
5996 * @param binder the binder for the nri.
5997 * @param callingAttributionTag the calling attribution tag for the nri.
5998 * @return the nri to register.
5999 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006000 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006001 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006002 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006003 @Nullable String callingAttributionTag) {
6004 final List<NetworkRequest> requests;
6005 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6006 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006007 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006008 } else {
6009 requests = Collections.singletonList(nr);
6010 }
Roshan Pius951c0032020-12-22 15:10:42 -08006011 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006012 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006013 }
6014
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006015 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6016 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006017 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006018 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006019 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006020 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006021 }
6022 }
6023
fenglu3f357402015-03-20 11:29:56 -07006024 @Override
fenglub00f4882015-04-21 17:12:05 -07006025 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006026 enforceAccessPermission();
6027 NetworkAgentInfo nai = null;
6028 if (network == null) {
6029 return false;
6030 }
6031 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006032 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006033 }
6034 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006035 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006036 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006037 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006038 Integer uidReqs = mBandwidthRequests.get(uid);
6039 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006040 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006041 }
6042 mBandwidthRequests.put(uid, ++uidReqs);
6043 }
fenglu3f357402015-03-20 11:29:56 -07006044 return true;
6045 }
6046 return false;
6047 }
6048
Felipe Leme0a5ae422016-06-20 16:36:29 -07006049 private boolean isSystem(int uid) {
6050 return uid < Process.FIRST_APPLICATION_UID;
6051 }
fenglu3f357402015-03-20 11:29:56 -07006052
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006053 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006054 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006055 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006056 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006057 return;
6058 }
Hugo Benichi39621362017-02-11 17:04:43 +09006059 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6060 // Policy already enforced.
6061 return;
6062 }
paulhuaf50d7d2020-12-24 19:47:34 +08006063 final long ident = Binder.clearCallingIdentity();
6064 try {
6065 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6066 // If UID is restricted, don't allow them to bring up metered APNs.
6067 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6068 }
6069 } finally {
6070 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006071 }
6072 }
6073
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006074 @Override
6075 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006076 PendingIntent operation, @NonNull String callingPackageName,
6077 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006078 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006079 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006080 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006081 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6082 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006083 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006084 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006085 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006086 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006087 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006088 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6089 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006090
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006091 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006092 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006093 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6094 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006095 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006096 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6097 nri));
6098 return networkRequest;
6099 }
6100
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006101 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6102 mHandler.sendMessageDelayed(
6103 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006104 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006105 }
6106
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006107 @Override
6108 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006109 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006110 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006111 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006112 }
6113
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006114 // In order to implement the compatibility measure for pre-M apps that call
6115 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6116 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6117 // This ensures it has permission to do so.
6118 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6119 if (nc == null) {
6120 return false;
6121 }
6122 int[] transportTypes = nc.getTransportTypes();
6123 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6124 return false;
6125 }
6126 try {
6127 mContext.enforceCallingOrSelfPermission(
6128 android.Manifest.permission.ACCESS_WIFI_STATE,
6129 "ConnectivityService");
6130 } catch (SecurityException e) {
6131 return false;
6132 }
6133 return true;
6134 }
6135
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006136 @Override
6137 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006138 Messenger messenger, IBinder binder,
6139 @NetworkCallback.Flag int callbackFlags,
6140 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006141 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006142 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6143 enforceAccessPermission();
6144 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006145
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006146 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006147 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006148 Binder.getCallingPid(), callingUid, callingPackageName);
6149 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006150 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6151 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6152 // onLost and onAvailable callbacks when networks move in and out of the background.
6153 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6154 // can't request networks.
6155 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006156 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006157
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006158 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006159 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006160 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006161 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006162 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006163 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006164
6165 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6166 return networkRequest;
6167 }
6168
6169 @Override
6170 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006171 PendingIntent operation, @NonNull String callingPackageName,
6172 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006173 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006174 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006175 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6176 enforceAccessPermission();
6177 }
lucasline117e2e2019-10-22 18:27:33 +08006178 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006179 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006180 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006181 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006182 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006183
6184 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006185 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006186 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6187 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006188 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006189
6190 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006191 }
6192
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006193 /** Returns the next Network provider ID. */
6194 public final int nextNetworkProviderId() {
6195 return mNextNetworkProviderId.getAndIncrement();
6196 }
6197
James Mattisa152f882020-11-20 16:08:10 -08006198 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
James Mattis4fce5d12020-11-12 15:53:42 -08006199 for (int i = 0; i < networkRequests.size(); i++) {
6200 releaseNetworkRequest(networkRequests.get(i));
6201 }
6202 }
6203
Erik Kline0c04b742016-07-07 16:50:58 +09006204 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006205 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006206 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006207 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006208 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006209 }
6210
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006211 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6212 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006213 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6214 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6215 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006216 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006217 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006218 return;
6219 }
6220
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006221 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6222 mNetworkProviderInfos.put(npi.messenger, npi);
6223 npi.connect(mContext, mTrackerHandler);
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006224 sendAllRequestsToProvider(npi);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006225 }
6226
6227 @Override
6228 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006229 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006230 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006231 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006232 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006233 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6234 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006235 }
6236
6237 @Override
6238 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006239 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006240 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006241 }
6242
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006243 @Override
6244 public void offerNetwork(@NonNull final Messenger providerMessenger,
6245 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6246 @NonNull final INetworkOfferCallback callback) {
6247 final NetworkOffer offer = new NetworkOffer(
6248 FullScore.makeProspectiveScore(score, caps), caps, callback, providerMessenger);
6249 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6250 }
6251
6252 @Override
6253 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6254 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6255 }
6256
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006257 private void handleUnregisterNetworkProvider(Messenger messenger) {
6258 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6259 if (npi == null) {
6260 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006261 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006262 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006263 // Unregister all the offers from this provider
6264 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6265 for (final NetworkOfferInfo noi : mNetworkOffers) {
6266 if (noi.offer.provider == messenger) {
6267 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6268 toRemove.add(noi);
6269 }
6270 }
6271 for (NetworkOfferInfo noi : toRemove) {
6272 handleUnregisterNetworkOffer(noi);
6273 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006274 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006275 }
6276
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006277 @Override
James Mattisf7027322020-12-13 16:28:14 -08006278 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006279 if (request.hasTransport(TRANSPORT_TEST)) {
6280 enforceNetworkFactoryOrTestNetworksPermission();
6281 } else {
6282 enforceNetworkFactoryPermission();
6283 }
James Mattisf7027322020-12-13 16:28:14 -08006284 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6285 if (nri != null) {
6286 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6287 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6288 mHandler.post(() -> handleReleaseNetworkRequest(
6289 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6290 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006291 }
6292
Paul Jensen1f567382015-02-13 14:18:39 -05006293 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6294 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006295 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006296 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006297 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006298 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006299 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006300
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006301 // NetworkAgentInfo keyed off its connecting messenger
6302 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen1f567382015-02-13 14:18:39 -05006303 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006304 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006305
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006306 // UID ranges for users that are currently blocked by VPNs.
6307 // This array is accessed and iterated on multiple threads without holding locks, so its
6308 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6309 // (on the handler thread).
6310 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6311
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006312 // Must only be accessed on the handler thread
6313 @NonNull
6314 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6315
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006316 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006317 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006318
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006319 // Current OEM network preferences. This object must only be written to on the handler thread.
6320 // Since it is immutable and always non-null, other threads may read it if they only care
6321 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006322 @NonNull
6323 private OemNetworkPreferences mOemNetworkPreferences =
6324 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006325 // Current per-profile network preferences. This object follows the same threading rules as
6326 // the OEM network preferences above.
6327 @NonNull
6328 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
James Mattis45d81842021-01-10 14:24:24 -08006329
James Mattiscb1e0362021-04-06 17:07:42 -07006330 // OemNetworkPreferences activity String log entries.
6331 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6332 @NonNull
6333 private final LocalLog mOemNetworkPreferencesLogs =
6334 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6335
James Mattis02220e22021-03-13 19:27:21 -08006336 /**
6337 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6338 * @param packageName the package name to check existence of a mapping for.
6339 * @return true if a mapping exists, false otherwise
6340 */
6341 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6342 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6343 }
6344
James Mattise3ef1912020-12-20 11:09:58 -08006345 // The always-on request for an Internet-capable network that apps without a specific default
6346 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006347 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006348 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006349 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006350 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006351 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006352 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006353 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006354
James Mattisd31bdfa2020-12-23 16:37:26 -08006355 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6356 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6357 }
6358
6359 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006360 * Return the default network request currently tracking the given uid.
6361 * @param uid the uid to check.
6362 * @return the NetworkRequestInfo tracking the given uid.
6363 */
6364 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006365 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006366 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6367 if (nri == mDefaultRequest) {
6368 continue;
6369 }
6370 // Checking the first request is sufficient as only multilayer requests will have more
6371 // than one request and for multilayer, all requests will track the same uids.
6372 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6373 return nri;
6374 }
6375 }
6376 return mDefaultRequest;
6377 }
6378
6379 /**
6380 * Get a copy of the network requests of the default request that is currently tracking the
6381 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006382 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6383 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006384 * @param requestorUid the uid to check the default for.
6385 * @param requestorPackageName the requestor's package name.
6386 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6387 */
6388 @NonNull
6389 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006390 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006391 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006392 getDefaultRequestTrackingUid(asUid).mRequests,
6393 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006394 }
6395
6396 /**
6397 * Copy the given nri's NetworkRequest collection.
6398 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006399 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6400 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006401 * @param requestorUid the uid to set on the copied collection.
6402 * @param requestorPackageName the package name to set on the copied collection.
6403 * @return the copied NetworkRequest collection.
6404 */
6405 @NonNull
6406 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006407 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6408 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006409 final List<NetworkRequest> requests = new ArrayList<>();
6410 for (final NetworkRequest nr : requestsToCopy) {
6411 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006412 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006413 nr.legacyType, nextNetworkRequestId(), nr.type));
6414 }
6415 return requests;
6416 }
6417
6418 @NonNull
6419 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006420 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6421 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006422 // These capabilities are for a TRACK_DEFAULT callback, so:
6423 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6424 // mDefaultRequest and a per-UID default request.
6425 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006426 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006427 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006428 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6429 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006430 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006431 restrictRequestUidsForCallerAndSetRequestorInfo(
6432 netCap, requestorUid, requestorPackageName);
6433 return netCap;
6434 }
6435
6436 /**
6437 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6438 * @param nr the network request to check for equality against.
6439 * @return the nri if one exists, null otherwise.
6440 */
6441 @Nullable
6442 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6443 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6444 if (nri.getNetworkRequestForCallback().equals(nr)) {
6445 return nri;
6446 }
6447 }
6448 return null;
6449 }
6450
6451 /**
6452 * Check if an nri is currently being managed by per-app default networking.
6453 * @param nri the nri to check.
6454 * @return true if this nri is currently being managed by per-app default networking.
6455 */
6456 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6457 // nri.mRequests.get(0) is only different from the original request filed in
6458 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6459 // functionality therefore if these two don't match, it means this particular nri is
6460 // currently being managed by a per-app default.
6461 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6462 }
6463
6464 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006465 * Determine if an nri is a managed default request that disallows default networking.
6466 * @param nri the request to evaluate
6467 * @return true if device-default networking is disallowed
6468 */
6469 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6470 // Check if this nri is a managed default that supports the default network at its
6471 // lowest priority request.
6472 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6473 final NetworkCapabilities lowestPriorityNetCap =
6474 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6475 return isPerAppDefaultRequest(nri)
6476 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6477 lowestPriorityNetCap));
6478 }
6479
Erik Kline05f2b402015-04-30 12:58:40 +09006480 // Request used to optionally keep mobile data active even when higher
6481 // priority networks like Wi-Fi are active.
6482 private final NetworkRequest mDefaultMobileDataRequest;
6483
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006484 // Request used to optionally keep wifi data active even when higher
6485 // priority networks like ethernet are active.
6486 private final NetworkRequest mDefaultWifiRequest;
6487
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006488 // Request used to optionally keep vehicle internal network always active
6489 private final NetworkRequest mDefaultVehicleRequest;
6490
James Mattisd31bdfa2020-12-23 16:37:26 -08006491 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6492 // network with no service. This NAI should never be matched against, nor should any public API
6493 // ever return the associated network. For this reason, this NAI is not in the list of available
6494 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6495 // default requests that don't support using the device default network which will ultimately
6496 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6497 @VisibleForTesting
6498 final NetworkAgentInfo mNoServiceNetwork;
6499
Chalard Jean5b409c72021-02-04 13:12:59 +09006500 // The NetworkAgentInfo currently satisfying the default request, if any.
6501 private NetworkAgentInfo getDefaultNetwork() {
6502 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006503 }
6504
James Mattis2516da32021-01-31 17:06:19 -08006505 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6506 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6507 // Currently, all network requests will have the same uids therefore checking the first
6508 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006509 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006510 if (null == uids) {
6511 continue;
6512 }
6513 for (final UidRange range : uids) {
6514 if (range.contains(uid)) {
6515 return nri.getSatisfier();
6516 }
6517 }
6518 }
6519 return getDefaultNetwork();
6520 }
6521
Varun Ananddf569952019-02-06 10:13:38 -08006522 @Nullable
6523 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6524 return nai != null ? nai.network : null;
6525 }
6526
6527 private void ensureRunningOnConnectivityServiceThread() {
6528 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6529 throw new IllegalStateException(
6530 "Not running on ConnectivityService thread: "
6531 + Thread.currentThread().getName());
6532 }
6533 }
6534
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006535 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006536 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6537 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006538 }
6539
Chalard Jean29d06db2018-05-02 21:14:54 +09006540 /**
6541 * Register a new agent with ConnectivityService to handle a network.
6542 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006543 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006544 * @param networkInfo the initial info associated with this network. It can be updated later :
6545 * see {@link #updateNetworkInfo}.
6546 * @param linkProperties the initial link properties of this network. They can be updated
6547 * later : see {@link #updateLinkProperties}.
6548 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006549 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006550 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006551 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006552 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006553 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006554 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006555 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006556 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006557 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006558 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6559 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006560 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6561 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6562 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006563 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006564 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006565 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6566 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006567 } else {
6568 enforceNetworkFactoryPermission();
6569 }
6570
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006571 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006572 final long token = Binder.clearCallingIdentity();
6573 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006574 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006575 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006576 } finally {
6577 Binder.restoreCallingIdentity(token);
6578 }
6579 }
6580
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006581 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006582 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006583 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6584 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006585 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006586 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6587 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6588 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6589 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006590 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006591 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006592
Rubin Xuffd77d82017-09-05 18:40:49 +01006593 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006594
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006595 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006596 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006597 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006598 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09006599 this, mNetd, mDnsResolver, providerId, uid, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006600
6601 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006602 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006603 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006604 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6605
Chalard Jeanf2da1772018-04-26 16:16:10 +09006606 final String extraInfo = networkInfo.getExtraInfo();
6607 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006608 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006609 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006610 mDeps.getNetworkStack().makeNetworkMonitor(
6611 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006612 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6613 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006614 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006615 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006616 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006617 }
6618
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006619 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6620 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006621 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006622 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006623 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006624 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006625 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006626
6627 try {
6628 networkMonitor.start();
6629 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006630 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006631 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006632 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006633 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006634 updateNetworkInfo(nai, networkInfo);
6635 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006636 }
6637
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006638 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6639 @NonNull public final NetworkOffer offer;
6640
6641 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6642 this.offer = offer;
6643 }
6644
6645 @Override
6646 public void binderDied() {
6647 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6648 }
6649 }
6650
6651 /**
6652 * Register or update a network offer.
6653 * @param newOffer The new offer. If the callback member is the same as an existing
6654 * offer, it is an update of that offer.
6655 */
6656 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6657 ensureRunningOnConnectivityServiceThread();
6658 if (null == mNetworkProviderInfos.get(newOffer.provider)) {
6659 // This may actually happen if a provider updates its score or registers and then
6660 // immediately unregisters. The offer would still be in the handler queue, but the
6661 // provider would have been removed.
6662 if (DBG) log("Received offer from an unregistered provider");
6663 return;
6664 }
6665
6666 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6667 if (null != existingOffer) {
6668 handleUnregisterNetworkOffer(existingOffer);
6669 newOffer.migrateFrom(existingOffer.offer);
6670 }
6671 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6672 try {
6673 noi.offer.provider.getBinder().linkToDeath(noi, 0 /* flags */);
6674 } catch (RemoteException e) {
6675 noi.binderDied();
6676 return;
6677 }
6678 mNetworkOffers.add(noi);
6679 // TODO : send requests to the provider.
6680 }
6681
6682 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6683 ensureRunningOnConnectivityServiceThread();
6684 mNetworkOffers.remove(noi);
6685 noi.offer.provider.getBinder().unlinkToDeath(noi, 0 /* flags */);
6686 }
6687
6688 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6689 @NonNull final INetworkOfferCallback callback) {
6690 ensureRunningOnConnectivityServiceThread();
6691 for (final NetworkOfferInfo noi : mNetworkOffers) {
6692 if (noi.offer.callback.equals(callback)) return noi;
6693 }
6694 return null;
6695 }
6696
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006697 /**
6698 * Called when receiving LinkProperties directly from a NetworkAgent.
6699 * Stores into |nai| any data coming from the agent that might also be written to the network's
6700 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6701 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09006702 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006703 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006704 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6705 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09006706 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08006707 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006708 }
6709
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006710 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006711 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006712 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006713
Lorenzo Colittid523d142020-04-01 20:16:30 +09006714 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6715 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6716 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09006717 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09006718
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006719 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00006720
6721 // update filtering rules, need to happen after the interface update so netd knows about the
6722 // new interface (the interface name -> index map becomes initialized)
6723 updateVpnFiltering(newLp, oldLp, networkAgent);
6724
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006725 updateMtu(newLp, oldLp);
6726 // TODO - figure out what to do for clat
6727// for (LinkProperties lp : newLp.getStackedLinks()) {
6728// updateMtu(lp, null);
6729// }
Chalard Jean5b409c72021-02-04 13:12:59 +09006730 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08006731 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6732 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09006733
Erik Klineb9888902016-04-05 13:30:49 +09006734 updateRoutes(newLp, oldLp, netId);
6735 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05006736 // Make sure LinkProperties represents the latest private DNS status.
6737 // This does not need to be done before updateDnses because the
6738 // LinkProperties are not the source of the private DNS configuration.
6739 // updateDnses will fetch the private DNS configuration from DnsManager.
6740 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09006741
Chalard Jean5b409c72021-02-04 13:12:59 +09006742 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05006743 handleApplyDefaultProxy(newLp.getHttpProxy());
6744 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006745 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05006746 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02006747
6748 updateWakeOnLan(newLp);
6749
Hai Shalome58bdc62021-01-11 18:45:34 -08006750 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6751 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6752 // does, it needs to be merged here.
6753 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6754 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09006755
Robert Greenwalte525a0a2014-09-30 16:50:07 -07006756 // TODO - move this check to cover the whole function
6757 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09006758 synchronized (networkAgent) {
6759 networkAgent.linkProperties = newLp;
6760 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09006761 // Start or stop DNS64 detection and 464xlat according to network state.
6762 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08006763 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09006764 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6765 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08006766 if (networkAgent.everConnected) {
6767 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6768 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07006769 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006770
6771 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04006772 }
6773
Hai Shalome58bdc62021-01-11 18:45:34 -08006774 /**
6775 * @param naData captive portal data from NetworkAgent
6776 * @param apiData captive portal data from capport API
6777 */
6778 @Nullable
6779 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6780 CaptivePortalData apiData) {
6781 if (naData == null || apiData == null) {
6782 return naData == null ? apiData : naData;
6783 }
6784 final CaptivePortalData.Builder captivePortalBuilder =
6785 new CaptivePortalData.Builder(naData);
6786
6787 if (apiData.isCaptive()) {
6788 captivePortalBuilder.setCaptive(true);
6789 }
6790 if (apiData.isSessionExtendable()) {
6791 captivePortalBuilder.setSessionExtendable(true);
6792 }
6793 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6794 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6795 // otherwise data would be inconsistent. Prefer the capport API info if present,
6796 // as it can generally be refreshed more often.
6797 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6798 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6799 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6800 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6801 // No source has time / bytes remaining information: surface the newest refresh time
6802 // for other fields
6803 captivePortalBuilder.setRefreshTime(
6804 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6805 }
6806
Hai Shalom7c6ab402021-02-04 19:34:06 -08006807 // Prioritize the user portal URL from the network agent if the source is authenticated.
6808 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6809 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6810 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6811 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08006812 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08006813 // Prioritize the venue information URL from the network agent if the source is
6814 // authenticated.
6815 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6816 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6817 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6818 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08006819 }
6820 return captivePortalBuilder.build();
6821 }
6822
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006823 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09006824 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09006825 // marks on unsupported interfaces is harmless.
6826 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6827 return;
6828 }
Joel Scherpelza235a812017-05-22 13:47:41 +09006829
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006830 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6831 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6832
6833 // TODO (b/183076074): remove legacy fallback after migrating overlays
6834 final int legacyMark = mContext.getResources().getInteger(mContext.getResources()
6835 .getIdentifier("config_networkWakeupPacketMark", "integer", "android"));
6836 final int legacyMask = mContext.getResources().getInteger(mContext.getResources()
6837 .getIdentifier("config_networkWakeupPacketMask", "integer", "android"));
6838 mark = mark == 0 ? legacyMark : mark;
6839 mask = mask == 0 ? legacyMask : mask;
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006840
6841 // Mask/mark of zero will not detect anything interesting.
6842 // Don't install rules unless both values are nonzero.
6843 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09006844 return;
6845 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006846
6847 final String prefix = "iface:" + iface;
6848 try {
6849 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08006850 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006851 } else {
Luke Huang46289a22018-09-27 19:33:11 +08006852 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006853 }
6854 } catch (Exception e) {
6855 loge("Exception modifying wakeup packet monitoring: " + e);
6856 }
6857
Joel Scherpelza235a812017-05-22 13:47:41 +09006858 }
6859
Chalard Jean9589e722019-11-19 19:03:53 +09006860 private void updateInterfaces(final @Nullable LinkProperties newLp,
6861 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006862 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09006863 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01006864 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6865 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09006866 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09006867 for (final String iface : interfaceDiff.added) {
6868 try {
6869 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08006870 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09006871 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08006872 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6873 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09006874 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08006875 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09006876 }
Paul Jensenbff73492014-04-28 10:33:11 -04006877 }
6878 }
Chalard Jean9589e722019-11-19 19:03:53 +09006879 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04006880 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006881 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006882 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08006883 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04006884 } catch (Exception e) {
6885 loge("Exception removing interface: " + e);
6886 }
6887 }
6888 }
6889
Tyler Weare4314862019-12-05 14:55:30 -08006890 // TODO: move to frameworks/libs/net.
6891 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6892 final String nextHop;
6893
6894 switch (route.getType()) {
6895 case RouteInfo.RTN_UNICAST:
6896 if (route.hasGateway()) {
6897 nextHop = route.getGateway().getHostAddress();
6898 } else {
6899 nextHop = INetd.NEXTHOP_NONE;
6900 }
6901 break;
6902 case RouteInfo.RTN_UNREACHABLE:
6903 nextHop = INetd.NEXTHOP_UNREACHABLE;
6904 break;
6905 case RouteInfo.RTN_THROW:
6906 nextHop = INetd.NEXTHOP_THROW;
6907 break;
6908 default:
6909 nextHop = INetd.NEXTHOP_NONE;
6910 break;
6911 }
6912
6913 final RouteInfoParcel rip = new RouteInfoParcel();
6914 rip.ifName = route.getInterface();
6915 rip.destination = route.getDestination().toString();
6916 rip.nextHop = nextHop;
6917 rip.mtu = route.getMtu();
6918
6919 return rip;
6920 }
6921
Paul Jensene0fd4a82014-08-06 15:51:33 -04006922 /**
6923 * Have netd update routes from oldLp to newLp.
6924 * @return true if routes changed between oldLp and newLp
6925 */
6926 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08006927 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08006928 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
6929 new CompareOrUpdateResult<>(
6930 oldLp != null ? oldLp.getAllRoutes() : null,
6931 newLp != null ? newLp.getAllRoutes() : null,
6932 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006933
6934 // add routes before removing old in case it helps with continuous connectivity
6935
Chalard Jean9dd11612018-06-04 16:52:49 +09006936 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006937 for (RouteInfo route : routeDiff.added) {
6938 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09006939 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006940 try {
Tyler Weare4314862019-12-05 14:55:30 -08006941 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006942 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006943 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08006944 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006945 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006946 }
6947 }
6948 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006949 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09006950 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006951 try {
Tyler Weare4314862019-12-05 14:55:30 -08006952 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006953 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006954 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08006955 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006956 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006957 }
6958 }
6959
6960 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09006961 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006962 try {
Tyler Weare4314862019-12-05 14:55:30 -08006963 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006964 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08006965 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006966 }
6967 }
Tyler Weare4314862019-12-05 14:55:30 -08006968
6969 for (RouteInfo route : routeDiff.updated) {
6970 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
6971 try {
6972 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
6973 } catch (Exception e) {
6974 loge("Exception in networkUpdateRouteParcel: " + e);
6975 }
6976 }
6977 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
6978 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006979 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09006980
Erik Klineb9888902016-04-05 13:30:49 +09006981 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
6982 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
6983 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006984 }
Erik Klineb9888902016-04-05 13:30:49 +09006985
Erik Kline31b4a9e2018-01-11 21:07:29 +09006986 if (DBG) {
6987 final Collection<InetAddress> dnses = newLp.getDnsServers();
6988 log("Setting DNS servers for network " + netId + " to " + dnses);
6989 }
Erik Klineb9888902016-04-05 13:30:49 +09006990 try {
chenbruce7b2f8982020-02-20 14:28:31 +08006991 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08006992 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09006993 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09006994 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09006995 }
Erik Kline54e35c02017-04-07 15:29:29 +09006996 }
6997
Lorenzo Colittibad9d912019-04-12 10:48:06 +00006998 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
6999 NetworkAgentInfo nai) {
7000 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7001 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7002 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7003 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7004
7005 if (!wasFiltering && !needsFiltering) {
7006 // Nothing to do.
7007 return;
7008 }
7009
7010 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7011 // Nothing changed.
7012 return;
7013 }
7014
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007015 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007016 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007017 // TODO: this create a window of opportunity for apps to receive traffic between the time
7018 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007019 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007020 // old rules are being removed.
7021 if (wasFiltering) {
7022 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7023 }
7024 if (needsFiltering) {
7025 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7026 }
7027 }
7028
Valentin Iftime9fa35092019-09-24 13:32:13 +02007029 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007030 if (mWolSupportedInterfaces == null) {
7031 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007032 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007033 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007034 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7035 }
7036
Luke Huangb913c812018-08-24 20:33:16 +08007037 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007038 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007039 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007040 }
7041 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007042 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007043 }
Luke Huangb913c812018-08-24 20:33:16 +08007044 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007045 }
7046
Chalard Jean62edfd82019-12-02 18:39:29 +09007047 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7048 @NonNull final NetworkCapabilities newNc) {
7049 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7050 final int newPermission = getNetworkPermission(newNc);
7051 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7052 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007053 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007054 } catch (RemoteException | ServiceSpecificException e) {
7055 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007056 }
7057 }
7058 }
7059
Paul Jensen53f08952015-06-16 14:27:36 -04007060 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007061 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7062 * Stores into |nai| any data coming from the agent that might also be written to the network's
7063 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7064 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007065 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007066 */
7067 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007068 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7069 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7070 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7071 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007072 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7073 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7074 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7075 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7076 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007077 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007078 }
7079
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007080 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007081 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007082 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007083 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007084 underlyingNetworks = underlyingNetworksOrDefault(
7085 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007086 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007087 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7088 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007089 // metered if any underlying is metered, or originally declared metered by the agent.
7090 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007091 boolean roaming = false; // roaming if any underlying is roaming
7092 boolean congested = false; // congested if any underlying is congested
7093 boolean suspended = true; // suspended if all underlying are suspended
7094
7095 boolean hadUnderlyingNetworks = false;
7096 if (null != underlyingNetworks) {
7097 for (Network underlyingNetwork : underlyingNetworks) {
7098 final NetworkAgentInfo underlying =
7099 getNetworkAgentInfoForNetwork(underlyingNetwork);
7100 if (underlying == null) continue;
7101
7102 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7103 hadUnderlyingNetworks = true;
7104 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007105 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007106 }
7107
7108 // Merge capabilities of this underlying network. For bandwidth, assume the
7109 // worst case.
7110 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7111 underlyingCaps.getLinkDownstreamBandwidthKbps());
7112 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7113 underlyingCaps.getLinkUpstreamBandwidthKbps());
7114 // If this underlying network is metered, the VPN is metered (it may cost money
7115 // to send packets on this network).
7116 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7117 // If this underlying network is roaming, the VPN is roaming (the billing structure
7118 // is different than the usual, local one).
7119 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7120 // If this underlying network is congested, the VPN is congested (the current
7121 // condition of the network affects the performance of this network).
7122 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7123 // If this network is not suspended, the VPN is not suspended (the VPN
7124 // is able to transfer some data).
7125 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7126 }
7127 }
7128 if (!hadUnderlyingNetworks) {
7129 // No idea what the underlying networks are; assume reasonable defaults
7130 metered = true;
7131 roaming = false;
7132 congested = false;
7133 suspended = false;
7134 }
7135
lifrade6c2a2021-03-04 14:08:08 +08007136 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007137 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7138 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7139 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7140 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7141 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7142 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007143 }
7144
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007145 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007146 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7147 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7148 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007149 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007150 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007151 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007152 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007153 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7154 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007155 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007156 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007157 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007158 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007159 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7160 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007161 // does not cause any request (that is not a listen) currently matching that agent to
7162 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007163 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007164 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007165 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007166 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007167 }
7168
Paul Jensen53f08952015-06-16 14:27:36 -04007169 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007170 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007171 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007172 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007173 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007174 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007175 }
Paul Jensende49eb12015-06-25 15:30:08 -04007176 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007177 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007178 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007179 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007180 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007181 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007182 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007183 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007184 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007185 }
lucaslin2240ef62019-03-12 13:08:03 +08007186 if (nai.partialConnectivity) {
7187 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7188 } else {
7189 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7190 }
lucasline117e2e2019-10-22 18:27:33 +08007191 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007192
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007193 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007194 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7195 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007196 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007197 }
7198
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007199 if (nai.supportsUnderlyingNetworks()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007200 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7201 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007202 }
7203
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007204 return newNc;
7205 }
7206
Lorenzo Colitti44840702021-01-11 22:27:57 +09007207 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7208 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7209 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7210 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7211 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7212 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7213 if (prevSuspended != suspended) {
7214 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7215 // onResumed have been removed.
7216 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7217 : ConnectivityManager.CALLBACK_RESUMED);
7218 }
7219 if (prevSuspended != suspended || prevRoaming != roaming) {
7220 // updateNetworkInfo will mix in the suspended info from the capabilities and
7221 // take appropriate action for the network having possibly changed state.
7222 updateNetworkInfo(nai, nai.networkInfo);
7223 }
7224 }
7225
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007226 /**
7227 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7228 *
7229 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7230 * capabilities we manage and store in {@code nai}, such as validated status and captive
7231 * portal status)
7232 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7233 * potentially triggers rematches.
7234 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7235 * change.)
7236 *
7237 * @param oldScore score of the network before any of the changes that prompted us
7238 * to call this function.
7239 * @param nai the network having its capabilities updated.
7240 * @param nc the new network capabilities.
7241 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007242 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7243 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007244 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007245 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007246 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007247 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007248
Chalard Jeanb2a49912018-01-16 18:43:05 +09007249 updateUids(nai, prevNc, newNc);
7250
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007251 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007252 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7253 // the change we're processing can't affect any requests, it can only affect the listens
7254 // on this network. We might have been called by rematchNetworkAndRequests when a
7255 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007256 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007257 } else {
7258 // If the requestable capabilities have changed or the score changed, we can't have been
7259 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007260 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007261 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007262 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007263 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007264
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007265 final boolean oldMetered = prevNc.isMetered();
7266 final boolean newMetered = newNc.isMetered();
7267 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007268
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007269 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007270 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7271 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007272 }
junyulaif2c67e42018-08-07 19:50:45 +08007273
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007274 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7275 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007276
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007277 // Report changes that are interesting for network statistics tracking.
7278 if (meteredChanged || roamingChanged) {
7279 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007280 }
7281
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007282 // This network might have been underlying another network. Propagate its capabilities.
7283 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007284
7285 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007286 mDnsManager.updateTransportsForNetwork(
7287 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007288 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007289 }
7290
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007291 /** Convenience method to update the capabilities for a given network. */
7292 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7293 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7294 }
7295
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007296 /**
7297 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7298 * network.
7299 *
7300 * Ingress interface filtering enforces that all apps under the given network can only receive
7301 * packets from the network's interface (and loopback). This is important for VPNs because
7302 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7303 * non-VPN interfaces.
7304 *
7305 * As a result, this method should return true iff
7306 * 1. the network is an app VPN (not legacy VPN)
7307 * 2. the VPN does not allow bypass
7308 * 3. the VPN is fully-routed
7309 * 4. the VPN interface is non-null
7310 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007311 * @see INetd#firewallAddUidInterfaceRules
7312 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007313 */
7314 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7315 LinkProperties lp) {
7316 if (nc == null || lp == null) return false;
7317 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007318 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007319 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007320 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007321 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7322 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007323 }
7324
Chiachang Wang28afaff2020-12-10 22:24:47 +08007325 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7326 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7327 int index = 0;
7328 for (UidRange range : ranges) {
7329 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7330 index++;
7331 }
7332 return stableRanges;
7333 }
7334
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007335 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7336 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7337 for (int i = 0; i < ranges.length; i++) {
7338 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7339 }
7340 return stableRanges;
7341 }
7342
Ken Chen5e65a852020-12-24 12:59:10 +08007343 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7344 int[] exemptUids) {
7345 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7346 try {
7347 mNetd.socketDestroy(ranges, exemptUids);
7348 } catch (Exception e) {
7349 loge("Exception in socket destroy: ", e);
7350 }
7351 }
7352 }
7353
7354 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7355 int[] exemptUids = new int[2];
7356 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7357 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7358 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7359 exemptUids[0] = VPN_UID;
7360 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7361 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7362
7363 maybeCloseSockets(nai, ranges, exemptUids);
7364 try {
7365 if (add) {
7366 mNetd.networkAddUidRanges(nai.network.netId, ranges);
7367 } else {
7368 mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
7369 }
7370 } catch (Exception e) {
7371 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7372 " on netId " + nai.network.netId + ". " + e);
7373 }
7374 maybeCloseSockets(nai, ranges, exemptUids);
7375 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007376
Chalard Jeanb2a49912018-01-16 18:43:05 +09007377 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7378 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007379 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7380 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007381 if (null == prevRanges) prevRanges = new ArraySet<>();
7382 if (null == newRanges) newRanges = new ArraySet<>();
7383 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7384
7385 prevRanges.removeAll(newRanges);
7386 newRanges.removeAll(prevRangesCopy);
7387
7388 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007389 // When updating the VPN uid routing rules, add the new range first then remove the old
7390 // range. If old range were removed first, there would be a window between the old
7391 // range being removed and the new range being added, during which UIDs contained
7392 // in both ranges are not subject to any VPN routing rules. Adding new range before
7393 // removing old range works because, unlike the filtering rules below, it's possible to
7394 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007395 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7396 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7397 // [1-5] & [1-2],[4-5] == [3]
7398 // Then we can do:
7399 // maybeCloseSockets([3])
7400 // mNetd.networkAddUidRanges([1-2],[4-5])
7401 // mNetd.networkRemoveUidRanges([1-5])
7402 // maybeCloseSockets([3])
7403 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7404 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007405 if (!newRanges.isEmpty()) {
Ken Chen5e65a852020-12-24 12:59:10 +08007406 updateUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007407 }
7408 if (!prevRanges.isEmpty()) {
Ken Chen5e65a852020-12-24 12:59:10 +08007409 updateUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007410 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007411 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7412 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7413 final String iface = nai.linkProperties.getInterfaceName();
7414 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007415 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007416 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7417 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7418 // were added first and then newRanges got removed later, there would be only one uid
7419 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7420 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7421 // Note that this is in contrast with the (more robust) update of VPN routing rules
7422 // above, where the addition of new ranges happens before the removal of old ranges.
7423 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7424 // to be removed will never overlap with the new range to be added.
7425 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007426 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007427 }
7428 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007429 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007430 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007431 } catch (Exception e) {
7432 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007433 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007434 }
7435 }
7436
Hugo Benichi9d35b752017-09-01 01:23:32 +00007437 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007438 ensureRunningOnConnectivityServiceThread();
7439
Serik Beketayevec8ad212020-12-07 22:43:07 -08007440 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007441 // Ignore updates for disconnected networks
7442 return;
7443 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007444 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007445 log("Update of LinkProperties for " + nai.toShortString()
7446 + "; created=" + nai.created
7447 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007448 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007449 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7450 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007451 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007452 }
7453
Paul Jensenaf94b982014-09-30 15:37:41 -04007454 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007455 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7456 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007457 // Don't send listening or track default request to factories. b/17393458
7458 if (!nr.isRequest()) continue;
Chalard Jean29d06db2018-05-02 21:14:54 +09007459 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenaf94b982014-09-30 15:37:41 -04007460 }
7461 }
7462
James Mattisa076c532020-12-02 14:12:41 -08007463 private void sendUpdatedScoreToFactories(
7464 @NonNull final NetworkReassignment.RequestReassignment event) {
7465 // If a request of type REQUEST is now being satisfied by a new network.
7466 if (null != event.mNewNetworkRequest && event.mNewNetworkRequest.isRequest()) {
7467 sendUpdatedScoreToFactories(event.mNewNetworkRequest, event.mNewNetwork);
7468 }
7469
7470 // If a previously satisfied request of type REQUEST is no longer being satisfied.
7471 if (null != event.mOldNetworkRequest && event.mOldNetworkRequest.isRequest()
7472 && event.mOldNetworkRequest != event.mNewNetworkRequest) {
7473 sendUpdatedScoreToFactories(event.mOldNetworkRequest, null);
7474 }
7475
7476 cancelMultilayerLowerPriorityNpiRequests(event.mNetworkRequestInfo);
7477 }
7478
7479 /**
7480 * Cancel with all NPIs the given NRI's multilayer requests that are a lower priority than
7481 * its currently satisfied active request.
7482 * @param nri the NRI to cancel lower priority requests for.
7483 */
7484 private void cancelMultilayerLowerPriorityNpiRequests(
7485 @NonNull final NetworkRequestInfo nri) {
7486 if (!nri.isMultilayerRequest() || null == nri.mActiveRequest) {
7487 return;
7488 }
7489
7490 final int indexOfNewRequest = nri.mRequests.indexOf(nri.mActiveRequest);
7491 for (int i = indexOfNewRequest + 1; i < nri.mRequests.size(); i++) {
7492 cancelNpiRequest(nri.mRequests.get(i));
7493 }
7494 }
7495
Chalard Jean00419ab2019-12-03 20:37:01 +09007496 private void sendUpdatedScoreToFactories(@NonNull NetworkRequest networkRequest,
7497 @Nullable NetworkAgentInfo nai) {
Chalard Jean04bc8072019-12-03 21:35:40 +09007498 final int score;
7499 final int serial;
Chalard Jean29d06db2018-05-02 21:14:54 +09007500 if (nai != null) {
7501 score = nai.getCurrentScore();
7502 serial = nai.factorySerialNumber;
Chalard Jean04bc8072019-12-03 21:35:40 +09007503 } else {
7504 score = 0;
7505 serial = 0;
Chalard Jean29d06db2018-05-02 21:14:54 +09007506 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007507 if (VDBG || DDBG){
7508 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
7509 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007510 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7511 npi.requestNetwork(networkRequest, score, serial);
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007512 }
7513 }
7514
7515 /** Sends all current NetworkRequests to the specified factory. */
James Mattisf8b661d2020-12-07 20:47:49 -08007516 private void sendAllRequestsToProvider(@NonNull final NetworkProviderInfo npi) {
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007517 ensureRunningOnConnectivityServiceThread();
James Mattisf8b661d2020-12-07 20:47:49 -08007518 for (final NetworkRequestInfo nri : getNrisFromGlobalRequests()) {
7519 for (final NetworkRequest req : nri.mRequests) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007520 if (!req.isRequest() && nri.getActiveRequest() == req) {
James Mattisf8b661d2020-12-07 20:47:49 -08007521 break;
7522 }
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007523 if (!req.isRequest()) {
James Mattisf8b661d2020-12-07 20:47:49 -08007524 continue;
7525 }
7526 // Only set the nai for the request it is satisfying.
7527 final NetworkAgentInfo nai =
7528 nri.getActiveRequest() == req ? nri.getSatisfier() : null;
7529 final int score;
7530 final int serial;
7531 if (null != nai) {
7532 score = nai.getCurrentScore();
7533 serial = nai.factorySerialNumber;
7534 } else {
7535 score = 0;
7536 serial = NetworkProvider.ID_NONE;
7537 }
7538 npi.requestNetwork(req, score, serial);
7539 // For multilayer requests, don't send lower priority requests if a higher priority
7540 // request is already satisfied.
7541 if (null != nai) {
7542 break;
7543 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007544 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007545 }
7546 }
7547
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007548 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7549 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007550 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007551 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007552 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007553 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7554 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7555 // such an API is ever implemented, there is no doubt the right request to send in
7556 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7557 // be sent as a separate extra.
7558 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007559 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007560 sendIntent(nri.mPendingIntent, intent);
7561 }
7562 // else not handled
7563 }
7564
7565 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7566 mPendingIntentWakeLock.acquire();
7567 try {
7568 if (DBG) log("Sending " + pendingIntent);
7569 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7570 } catch (PendingIntent.CanceledException e) {
7571 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7572 mPendingIntentWakeLock.release();
7573 releasePendingNetworkRequest(pendingIntent);
7574 }
7575 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7576 }
7577
7578 @Override
7579 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7580 String resultData, Bundle resultExtras) {
7581 if (DBG) log("Finished sending " + pendingIntent);
7582 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007583 // Release with a delay so the receiving client has an opportunity to put in its
7584 // own request.
7585 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007586 }
7587
James Mattis212df9e2020-12-03 19:57:41 -08007588 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7589 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7590 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007591 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007592 // Default request has no msgr. Also prevents callbacks from being invoked for
7593 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7594 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7595 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007596 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007597 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007598 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007599 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007600 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007601 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007602 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007603 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7604 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007605 }
Roshan Pius951c0032020-12-22 15:10:42 -08007606 final boolean includeLocationSensitiveInfo =
7607 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007608 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007609 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007610 final NetworkCapabilities nc =
7611 networkCapabilitiesRestrictedForCallerPermissions(
7612 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7613 putParcelable(
7614 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007615 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007616 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007617 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007618 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007619 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7620 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007621 // For this notification, arg1 contains the blocked status.
7622 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007623 break;
7624 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007625 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007626 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007627 break;
7628 }
7629 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007630 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007631 final NetworkCapabilities netCap =
7632 networkCapabilitiesRestrictedForCallerPermissions(
7633 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7634 putParcelable(
7635 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007636 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007637 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007638 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007639 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007640 break;
7641 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007642 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007643 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7644 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007645 break;
7646 }
junyulaif2c67e42018-08-07 19:50:45 +08007647 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007648 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007649 msg.arg1 = arg1;
7650 break;
7651 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007652 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007653 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007654 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007655 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007656 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007657 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007658 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007659 }
James Mattis45d81842021-01-10 14:24:24 -08007660 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007661 } catch (RemoteException e) {
7662 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007663 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007664 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007665 }
7666
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007667 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7668 bundle.putParcelable(t.getClass().getSimpleName(), t);
7669 }
7670
Paul Jensenaf94b982014-09-30 15:37:41 -04007671 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007672 if (nai.numRequestNetworkRequests() != 0) {
7673 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7674 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007675 // Ignore listening and track default requests.
7676 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007677 loge("Dead network still had at least " + nr);
7678 break;
7679 }
Paul Jensenaf94b982014-09-30 15:37:41 -04007680 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007681 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04007682 }
7683
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007684 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7685 if (oldNetwork == null) {
7686 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7687 return;
7688 }
Chalard Jean49707572019-12-10 21:07:02 +09007689 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007690
7691 // If we get here it means that the last linger timeout for this network expired. So there
7692 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08007693 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007694
Lorenzo Colitti2666be82016-09-09 18:48:56 +09007695 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007696 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007697 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007698 } else {
junyulai0ac374f2020-12-14 18:41:52 +08007699 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007700 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007701 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007702 }
7703
James Mattise3ef1912020-12-20 11:09:58 -08007704 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7705 boolean isDefaultChanged = false;
7706 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7707 final NetworkReassignment.RequestReassignment reassignment =
7708 changes.getReassignment(defaultRequestInfo);
7709 if (null == reassignment) {
7710 continue;
7711 }
7712 // reassignment only contains those instances where the satisfying network changed.
7713 isDefaultChanged = true;
7714 // Notify system services of the new default.
7715 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7716 }
Chiachang Wang087fd272018-09-28 22:42:48 +08007717
James Mattise3ef1912020-12-20 11:09:58 -08007718 if (isDefaultChanged) {
7719 // Hold a wakelock for a short time to help apps in migrating to a new default.
7720 scheduleReleaseNetworkTransitionWakelock();
7721 }
7722 }
7723
7724 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7725 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7726 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7727 if (DBG) {
7728 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7729 }
Chalard Jean8e382112019-12-03 20:45:30 +09007730
James Mattisd31bdfa2020-12-23 16:37:26 -08007731 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7732 if (newDefaultNetwork != null) {
7733 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04007734 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09007735
James Mattisd31bdfa2020-12-23 16:37:26 -08007736 // Set an app level managed default and return since further processing only applies to the
7737 // default network.
7738 if (mDefaultRequest != nri) {
7739 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7740 return;
7741 }
7742
7743 makeDefaultNetwork(newDefaultNetwork);
7744
James Mattise3ef1912020-12-20 11:09:58 -08007745 if (oldDefaultNetwork != null) {
7746 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7747 }
7748 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08007749 handleApplyDefaultProxy(null != newDefaultNetwork
7750 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7751 updateTcpBufferSizes(null != newDefaultNetwork
7752 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09007753 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04007754 }
7755
James Mattisd31bdfa2020-12-23 16:37:26 -08007756 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7757 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7758 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7759 try {
7760 if (VDBG) {
7761 log("Setting default network for " + nri
7762 + " using UIDs " + nri.getUids()
7763 + " with old network " + (oldDefaultNetwork != null
7764 ? oldDefaultNetwork.network().getNetId() : "null")
7765 + " and new network " + (newDefaultNetwork != null
7766 ? newDefaultNetwork.network().getNetId() : "null"));
7767 }
7768 if (nri.getUids().isEmpty()) {
7769 throw new IllegalStateException("makeDefaultForApps called without specifying"
7770 + " any applications to set as the default." + nri);
7771 }
7772 if (null != newDefaultNetwork) {
7773 mNetd.networkAddUidRanges(
7774 newDefaultNetwork.network.getNetId(),
7775 toUidRangeStableParcels(nri.getUids()));
7776 }
7777 if (null != oldDefaultNetwork) {
7778 mNetd.networkRemoveUidRanges(
7779 oldDefaultNetwork.network.getNetId(),
7780 toUidRangeStableParcels(nri.getUids()));
7781 }
7782 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09007783 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08007784 }
7785 }
7786
7787 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7788 try {
7789 if (null != newDefaultNetwork) {
7790 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7791 } else {
7792 mNetd.networkClearDefault();
7793 }
7794 } catch (RemoteException | ServiceSpecificException e) {
7795 loge("Exception setting default network :" + e);
7796 }
7797 }
7798
Chalard Jean05cbe972019-12-09 11:50:38 +09007799 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007800 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09007801 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09007802 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09007803 processNewlySatisfiedListenRequests(nai);
7804 }
7805
7806 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08007807 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7808 if (nri.isMultilayerRequest()) {
7809 continue;
7810 }
7811 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007812 if (!nr.isListen()) continue;
7813 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08007814 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007815 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7816 }
7817 }
Chalard Jeancd397a22019-11-22 22:33:33 +09007818 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007819
Chalard Jeancd397a22019-11-22 22:33:33 +09007820 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08007821 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7822 if (nri.isMultilayerRequest()) {
7823 continue;
7824 }
7825 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007826 if (!nr.isListen()) continue;
7827 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7828 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09007829 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007830 }
7831 }
7832 }
7833
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007834 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007835 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007836 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08007837 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09007838 @Nullable public final NetworkRequest mOldNetworkRequest;
7839 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007840 @Nullable public final NetworkAgentInfo mOldNetwork;
7841 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08007842 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09007843 @Nullable final NetworkRequest oldNetworkRequest,
7844 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007845 @Nullable final NetworkAgentInfo oldNetwork,
7846 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08007847 mNetworkRequestInfo = networkRequestInfo;
7848 mOldNetworkRequest = oldNetworkRequest;
7849 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007850 mOldNetwork = oldNetwork;
7851 mNewNetwork = newNetwork;
7852 }
Chalard Jean49707572019-12-10 21:07:02 +09007853
7854 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09007855 final NetworkRequest requestToShow = null != mNewNetworkRequest
7856 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7857 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08007858 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7859 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09007860 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007861 }
7862
Chalard Jean46a62372019-12-10 21:25:24 +09007863 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007864
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007865 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09007866 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007867 }
7868
7869 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09007870 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09007871 // The code is never supposed to add two reassignments of the same request. Make
7872 // sure this stays true, but without imposing this expensive check on all
7873 // reassignments on all user devices.
7874 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08007875 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09007876 throw new IllegalStateException("Trying to reassign ["
7877 + reassignment + "] but already have ["
7878 + existing + "]");
7879 }
7880 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09007881 }
Chalard Jean46a62372019-12-10 21:25:24 +09007882 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007883 }
7884
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007885 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09007886 // the passed request.
7887 @Nullable
7888 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007889 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08007890 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007891 }
7892 return null;
7893 }
Chalard Jean49707572019-12-10 21:07:02 +09007894
7895 public String toString() {
7896 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7897 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09007898 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09007899 for (final RequestReassignment rr : getRequestReassignments()) {
7900 sj.add(rr.toString());
7901 }
7902 return sj.toString();
7903 }
7904
7905 public String debugString() {
7906 final StringBuilder sb = new StringBuilder();
7907 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09007908 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09007909 for (final RequestReassignment rr : getRequestReassignments()) {
7910 sb.append("\n ").append(rr);
7911 }
7912 return sb.append("\n").toString();
7913 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007914 }
7915
Chalard Jean24344d72019-12-04 13:32:31 +09007916 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09007917 @Nullable final NetworkRequest previousRequest,
7918 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09007919 @Nullable final NetworkAgentInfo previousSatisfier,
7920 @Nullable final NetworkAgentInfo newSatisfier,
7921 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08007922 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09007923 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09007924 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09007925 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007926 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09007927 }
James Mattisa076c532020-12-02 14:12:41 -08007928 previousSatisfier.removeRequest(previousRequest.requestId);
7929 previousSatisfier.lingerRequest(previousRequest.requestId, now, mLingerDelayMs);
Chalard Jean24344d72019-12-04 13:32:31 +09007930 } else {
7931 if (VDBG || DDBG) log(" accepting network in place of null");
7932 }
junyulai0ac374f2020-12-14 18:41:52 +08007933
7934 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7935 // and immediately satisfies a request then remove the timer. This will happen for
7936 // all networks except in the case of an underlying network for a VCN.
7937 if (newSatisfier.isNascent()) {
7938 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
7939 }
7940
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007941 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08007942 newSatisfier.unlingerRequest(newRequest.requestId);
7943 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007944 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08007945 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09007946 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09007947 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09007948 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007949 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08007950 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09007951 }
James Mattisa076c532020-12-02 14:12:41 -08007952 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09007953 }
James Mattisa076c532020-12-02 14:12:41 -08007954 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09007955 }
7956
James Mattisa076c532020-12-02 14:12:41 -08007957 /**
7958 * This function is triggered when something can affect what network should satisfy what
7959 * request, and it computes the network reassignment from the passed collection of requests to
7960 * network match to the one that the system should now have. That data is encoded in an
7961 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
7962 * satisfier.
7963 *
7964 * After the reassignment is computed, it is applied to the state objects.
7965 *
7966 * @param networkRequests the nri objects to evaluate for possible network reassignment
7967 * @return NetworkReassignment listing of proposed network assignment changes
7968 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09007969 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08007970 private NetworkReassignment computeNetworkReassignment(
7971 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09007972 final NetworkReassignment changes = new NetworkReassignment();
7973
7974 // Gather the list of all relevant agents and sort them by score.
7975 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007976 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08007977 if (!nai.everConnected) {
7978 continue;
7979 }
Chalard Jean857a1712019-12-10 21:08:07 +09007980 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09007981 }
Chalard Jean857a1712019-12-10 21:08:07 +09007982
James Mattisa076c532020-12-02 14:12:41 -08007983 for (final NetworkRequestInfo nri : networkRequests) {
7984 // Non-multilayer listen requests can be ignored.
7985 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
7986 continue;
7987 }
7988 NetworkAgentInfo bestNetwork = null;
7989 NetworkRequest bestRequest = null;
7990 for (final NetworkRequest req : nri.mRequests) {
7991 bestNetwork = mNetworkRanker.getBestNetwork(req, nais);
7992 // Stop evaluating as the highest possible priority request is satisfied.
7993 if (null != bestNetwork) {
7994 bestRequest = req;
7995 break;
7996 }
7997 }
James Mattisd31bdfa2020-12-23 16:37:26 -08007998 if (null == bestNetwork && isDefaultBlocked(nri)) {
7999 // Remove default networking if disallowed for managed default requests.
8000 bestNetwork = mNoServiceNetwork;
8001 }
8002 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008003 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008004 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008005 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008006 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008007 }
8008 return changes;
8009 }
8010
James Mattisa076c532020-12-02 14:12:41 -08008011 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8012 return new HashSet<>(mNetworkRequests.values());
8013 }
8014
Paul Jensenc88b39b2015-06-16 14:27:36 -04008015 /**
James Mattisa076c532020-12-02 14:12:41 -08008016 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008017 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008018 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008019 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008020 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8021 }
8022
8023 /**
8024 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8025 * being disconnected.
8026 */
8027 private void rematchNetworksAndRequests(
8028 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8029 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008030 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008031 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008032 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008033 if (VDBG || DDBG) {
8034 log(changes.debugString());
8035 } else if (DBG) {
8036 log(changes.toString()); // Shorter form, only one line of log
8037 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008038 applyNetworkReassignment(changes, now);
Chalard Jeand7f762d2019-12-10 19:01:29 +09008039 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008040
Chalard Jeand7f762d2019-12-10 19:01:29 +09008041 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008042 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008043 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008044
8045 // Since most of the time there are only 0 or 1 background networks, it would probably
8046 // be more efficient to just use an ArrayList here. TODO : measure performance
8047 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8048 for (final NetworkAgentInfo nai : nais) {
8049 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8050 }
8051
Chalard Jeand7f762d2019-12-10 19:01:29 +09008052 // First, update the lists of satisfied requests in the network agents. This is necessary
8053 // because some code later depends on this state to be correct, most prominently computing
8054 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008055 for (final NetworkReassignment.RequestReassignment event :
8056 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008057 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8058 event.mOldNetworkRequest, event.mNewNetworkRequest,
8059 event.mOldNetwork, event.mNewNetwork,
8060 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008061 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008062
James Mattise3ef1912020-12-20 11:09:58 -08008063 // Process default network changes if applicable.
8064 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008065
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008066 // Notify requested networks are available after the default net is switched, but
8067 // before LegacyTypeTracker sends legacy broadcasts
8068 for (final NetworkReassignment.RequestReassignment event :
8069 changes.getRequestReassignments()) {
Chalard Jean04bc8072019-12-03 21:35:40 +09008070 // Tell NetworkProviders about the new score, so they can stop
8071 // trying to connect if they know they cannot match it.
8072 // TODO - this could get expensive if there are a lot of outstanding requests for this
8073 // network. Think of a way to reduce this. Push netid->request mapping to each factory?
James Mattisa076c532020-12-02 14:12:41 -08008074 sendUpdatedScoreToFactories(event);
Chalard Jean04bc8072019-12-03 21:35:40 +09008075
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008076 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008077 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008078 } else {
James Mattisa076c532020-12-02 14:12:41 -08008079 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008080 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008081 }
8082 }
8083
junyulai0ac374f2020-12-14 18:41:52 +08008084 // Update the inactivity state before processing listen callbacks, because the background
8085 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008086 // just yet though, because they have to be sent after the listens are processed to keep
8087 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008088 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008089 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008090 // Rematching may have altered the inactivity state of some networks, so update all
8091 // inactivity timers. updateInactivityState reads the state from the network agent
8092 // and does nothing if the state has not changed : the source of truth is controlled
8093 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8094 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008095 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008096 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008097 }
8098 }
8099
Chalard Jeanb10ab412019-12-11 14:12:30 +09008100 for (final NetworkAgentInfo nai : nais) {
8101 if (!nai.everConnected) continue;
8102 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008103 // Process listen requests and update capabilities if the background state has
8104 // changed for this network. For consistency with previous behavior, send onLost
8105 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008106 processNewlyLostListenRequests(nai);
8107 if (oldBackground != nai.isBackgroundNetwork()) {
8108 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008109 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008110 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008111 }
8112
junyulai0ac374f2020-12-14 18:41:52 +08008113 for (final NetworkAgentInfo nai : inactiveNetworks) {
8114 // For nascent networks, if connecting with no foreground request, skip broadcasting
8115 // LOSING for backward compatibility. This is typical when mobile data connected while
8116 // wifi connected with mobile data always-on enabled.
8117 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008118 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008119 }
8120
James Mattise3ef1912020-12-20 11:09:58 -08008121 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008122
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008123 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008124 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008125 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008126 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008127 // This network has active linger timers and no requests, but is not
8128 // lingering. Linger it.
8129 //
8130 // One way (the only way?) this can happen if this network is unvalidated
8131 // and became unneeded due to another network improving its score to the
8132 // point where this network will no longer be able to satisfy any requests
8133 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008134 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008135 notifyNetworkLosing(nai, now);
8136 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008137 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008138 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008139 teardownUnneededNetwork(nai);
8140 }
8141 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008142 }
8143 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008144
Chalard Jean62edfd82019-12-02 18:39:29 +09008145 /**
8146 * Apply a change in background state resulting from rematching networks with requests.
8147 *
8148 * During rematch, a network may change background states by starting to satisfy or stopping
8149 * to satisfy a foreground request. Listens don't count for this. When a network changes
8150 * background states, its capabilities need to be updated and callbacks fired for the
8151 * capability change.
8152 *
8153 * @param nai The network that changed background states
8154 */
8155 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8156 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8157 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8158 updateNetworkPermissions(nai, newNc);
8159 nai.getAndSetNetworkCapabilities(newNc);
8160 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8161 }
8162
Chalard Jeanf0344532019-11-19 19:23:38 +09008163 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008164 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008165 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008166 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8167 changes.getReassignment(mDefaultRequest);
8168 final NetworkAgentInfo oldDefaultNetwork =
8169 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8170 final NetworkAgentInfo newDefaultNetwork =
8171 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008172
Chalard Jean5b409c72021-02-04 13:12:59 +09008173 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008174 // Maintain the illusion : since the legacy API only understands one network at a time,
8175 // if the default network changed, apps should see a disconnected broadcast for the
8176 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008177 if (oldDefaultNetwork != null) {
8178 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8179 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008180 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008181 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008182 // The new default network can be newly null if and only if the old default
8183 // network doesn't satisfy the default request any more because it lost a
8184 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008185 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008186 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008187 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008188 }
8189 }
8190
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008191 // Now that all the callbacks have been sent, send the legacy network broadcasts
8192 // as needed. This is necessary so that legacy requests correctly bind dns
8193 // requests to this network. The legacy users are listening for this broadcast
8194 // and will generally do a dns request so they can ensureRouteToHost and if
8195 // they do that before the callbacks happen they'll use the default network.
8196 //
8197 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8198 // callbacks, but if apps can receive the broadcast before the callback, they still might
8199 // have an inconsistent view of networking.
8200 //
8201 // This *does* introduce a race where if the user uses the new api
8202 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8203 // they may get old info. Reverse this after the old startUsing api is removed.
8204 // This is on top of the multiple intent sequencing referenced in the todo above.
8205 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008206 if (nai.everConnected) {
8207 addNetworkToLegacyTypeTracker(nai);
8208 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008209 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008210 }
8211
Chalard Jean61c79252019-11-07 23:07:32 +09008212 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8213 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8214 NetworkRequest nr = nai.requestAt(i);
8215 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8216 // legacy type tracker filters out repeat adds
8217 mLegacyTypeTracker.add(nr.legacyType, nai);
8218 }
8219 }
8220
8221 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008222 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008223 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8224 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8225 if (nai.isVPN()) {
8226 mLegacyTypeTracker.add(TYPE_VPN, nai);
8227 }
8228 }
8229
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008230 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008231 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008232 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008233 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008234 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008235 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008236
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008237 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008238 // Don't repeat publish.
8239 if (newInetCondition == mDefaultInetConditionPublished) return;
8240
8241 mDefaultInetConditionPublished = newInetCondition;
8242 sendInetConditionBroadcast(nai.networkInfo);
8243 }
8244
Chalard Jeand61375d2020-01-14 22:46:36 +09008245 @NonNull
8246 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8247 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008248 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008249 final boolean suspended =
8250 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8251 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8252 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8253 // state. This is because the network could have been suspended before connecting,
8254 // or it could be disconnecting while being suspended, and in both these cases
8255 // the state should not be overridden. Note that the only detailed state that
8256 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8257 // worry about multiple different substates of CONNECTED.
8258 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8259 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008260 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8261 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8262 // network agent is created, then goes to suspended, then goes out of suspended without
8263 // ever setting connected. Check if network agent is ever connected to update the state.
8264 newInfo.setDetailedState(nai.everConnected
8265 ? NetworkInfo.DetailedState.CONNECTED
8266 : NetworkInfo.DetailedState.CONNECTING,
8267 info.getReason(),
8268 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008269 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008270 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008271 return newInfo;
8272 }
8273
8274 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8275 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8276
Erik Kline99f301b2017-02-15 19:59:17 +09008277 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008278 NetworkInfo oldInfo = null;
8279 synchronized (networkAgent) {
8280 oldInfo = networkAgent.networkInfo;
8281 networkAgent.networkInfo = newInfo;
8282 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008283
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008284 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008285 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8286 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008287 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008288
Robin Leea8c0b6e2016-05-01 23:00:00 +01008289 if (!networkAgent.created
8290 && (state == NetworkInfo.State.CONNECTED
8291 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008292
8293 // A network that has just connected has zero requests and is thus a foreground network.
8294 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8295
Luke Huangfdd11f82019-04-09 18:41:49 +08008296 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008297 if (networkAgent.supportsUnderlyingNetworks()) {
8298 // Initialize the network's capabilities to their starting values according to the
8299 // underlying networks. This ensures that the capabilities are correct before
8300 // anything happens to the network.
8301 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008302 }
Paul Jensen74940202014-08-04 12:21:19 -04008303 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008304 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008305 }
8306
8307 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8308 networkAgent.everConnected = true;
8309
lucaslin45e639b2019-04-03 17:09:28 +08008310 // NetworkCapabilities need to be set before sending the private DNS config to
8311 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008312 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8313
Erik Kline9a62f012018-03-21 07:18:33 -07008314 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008315 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8316 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008317
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008318 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8319 // command must be sent after updating LinkProperties to maximize chances of
8320 // NetworkMonitor seeing the correct LinkProperties when starting.
8321 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008322 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008323 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008324 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008325 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008326 new LinkProperties(networkAgent.linkProperties,
8327 true /* parcelSensitiveFields */),
8328 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008329 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008330
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008331 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8332 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8333 // capabilities, so it only needs to be done once on initial connect, not every time the
8334 // network's capabilities change. Note that we do this before rematching the network,
8335 // so we could decide to tear it down immediately afterwards. That's fine though - on
8336 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8337 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008338 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008339
junyulai0ac374f2020-12-14 18:41:52 +08008340 // Before first rematching networks, put an inactivity timer without any request, this
8341 // allows {@code updateInactivityState} to update the state accordingly and prevent
8342 // tearing down for any {@code unneeded} evaluation in this period.
8343 // Note that the timer will not be rescheduled since the expiry time is
8344 // fixed after connection regardless of the network satisfying other requests or not.
8345 // But it will be removed as soon as the network satisfies a request for the first time.
8346 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8347 SystemClock.elapsedRealtime(), mNascentDelayMs);
8348
Paul Jensen05e85ee2014-09-11 11:00:39 -04008349 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008350 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008351
8352 // This has to happen after matching the requests, because callbacks are just requests.
8353 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008354 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008355 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008356 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008357 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008358 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008359 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008360 if (networkAgent.isVPN()) {
8361 // As the active or bound network changes for apps, broadcast the default proxy, as
8362 // apps may need to update their proxy data. This is called after disconnecting from
8363 // VPN to make sure we do not broadcast the old proxy data.
8364 // TODO(b/122649188): send the broadcast only to VPN users.
8365 mProxyTracker.sendProxyBroadcast();
8366 }
Yintang Gu5014b522019-06-18 14:24:32 +08008367 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8368 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008369 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008370 }
8371 }
8372
Chalard Jean28018572020-12-21 18:36:52 +09008373 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008374 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8375 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008376 rematchAllNetworksAndRequests();
Paul Jensenaf94b982014-09-30 15:37:41 -04008377 sendUpdatedScoreToFactories(nai);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008378 }
8379
Erik Kline99f301b2017-02-15 19:59:17 +09008380 // Notify only this one new request of the current state. Transfer all the
8381 // current state by calling NetworkCapabilities and LinkProperties callbacks
8382 // so that callers can be guaranteed to have as close to atomicity in state
8383 // transfer as can be supported by this current API.
8384 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008385 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008386 if (nri.mPendingIntent != null) {
8387 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8388 // Attempt no subsequent state pushes where intents are involved.
8389 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008390 }
Erik Kline99f301b2017-02-15 19:59:17 +09008391
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008392 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008393 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008394 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8395 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8396 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008397 }
8398
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008399 // Notify the requests on this NAI that the network is now lingered.
8400 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008401 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008402 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8403 }
8404
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008405 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8406 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8407 return vpnBlocked
8408 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8409 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8410 }
8411
8412 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8413 if (blockedReasons == BLOCKED_REASON_NONE) {
8414 mUidBlockedReasons.delete(uid);
8415 } else {
8416 mUidBlockedReasons.put(uid, blockedReasons);
8417 }
8418 }
8419
junyulaif2c67e42018-08-07 19:50:45 +08008420 /**
8421 * Notify of the blocked state apps with a registered callback matching a given NAI.
8422 *
8423 * Unlike other callbacks, blocked status is different between each individual uid. So for
8424 * any given nai, all requests need to be considered according to the uid who filed it.
8425 *
8426 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008427 * @param oldMetered True if the previous network capabilities were metered.
8428 * @param newMetered True if the current network capabilities are metered.
8429 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8430 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008431 */
8432 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008433 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8434 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008435
8436 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8437 NetworkRequest nr = nai.requestAt(i);
8438 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008439
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008440 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8441 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8442 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008443 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008444 : oldVpnBlocked;
8445
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008446 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8447 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8448 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008449 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008450 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008451 }
8452 }
8453 }
8454
8455 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008456 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008457 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008458 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008459 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008460 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008461 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008462 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008463 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008464
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008465 final int oldBlockedState = getBlockedState(
8466 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8467 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8468 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008469 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008470 }
junyulaif2c67e42018-08-07 19:50:45 +08008471 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8472 NetworkRequest nr = nai.requestAt(i);
8473 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008474 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008475 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8476 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008477 }
8478 }
8479 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008480 }
8481
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008482 @VisibleForTesting
8483 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008484 // The NetworkInfo we actually send out has no bearing on the real
8485 // state of affairs. For example, if the default connection is mobile,
8486 // and a request for HIPRI has just gone away, we need to pretend that
8487 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8488 // the state to DISCONNECTED, even though the network is of type MOBILE
8489 // and is still connected.
8490 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8491 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008492 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008493 if (state != DetailedState.DISCONNECTED) {
8494 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008495 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008496 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008497 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008498 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8499 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8500 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8501 if (info.isFailover()) {
8502 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8503 nai.networkInfo.setFailover(false);
8504 }
8505 if (info.getReason() != null) {
8506 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8507 }
8508 if (info.getExtraInfo() != null) {
8509 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8510 }
8511 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008512 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008513 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008514 if (newDefaultAgent != null) {
8515 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8516 newDefaultAgent.networkInfo);
8517 } else {
8518 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8519 }
8520 }
8521 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8522 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008523 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008524 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008525 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008526 }
8527 }
8528 }
8529
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008530 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008531 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008532 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008533 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008534 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008535 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8536 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008537 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8538 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008539 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008540 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008541 } else {
8542 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8543 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008544 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008545 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008546
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008547 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8548 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8549 }
8550
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008551 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008552 * Returns the list of all interfaces that could be used by network traffic that does not
8553 * explicitly specify a network. This includes the default network, but also all VPNs that are
8554 * currently connected.
8555 *
8556 * Must be called on the handler thread.
8557 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008558 @NonNull
8559 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008560 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008561 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008562 final Set<Integer> activeNetIds = new ArraySet<>();
8563 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8564 if (nri.isBeingSatisfied()) {
8565 activeNetIds.add(nri.getSatisfier().network().netId);
8566 }
8567 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008568 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008569 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008570 defaultNetworks.add(nai.network);
8571 }
8572 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008573 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008574 }
8575
8576 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09008577 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8578 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008579 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08008580 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008581 ensureRunningOnConnectivityServiceThread();
8582 String activeIface = null;
8583 LinkProperties activeLinkProperties = getActiveLinkProperties();
8584 if (activeLinkProperties != null) {
8585 activeIface = activeLinkProperties.getInterfaceName();
8586 }
Benedict Wong9308cd32019-06-12 17:46:31 +00008587
junyulai2050bed2021-01-23 09:46:34 +08008588 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008589 try {
junyulaide41fc22021-01-22 22:46:01 +08008590 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
8591 // TODO: Directly use NetworkStateSnapshot when feasible.
8592 for (final NetworkState state : getAllNetworkState()) {
junyulai14133c12020-12-30 19:03:32 +08008593 final NetworkStateSnapshot snapshot = new NetworkStateSnapshot(state.network,
8594 state.networkCapabilities, state.linkProperties, state.subscriberId,
junyulaide41fc22021-01-22 22:46:01 +08008595 state.legacyNetworkType);
8596 snapshots.add(snapshot);
8597 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008598 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8599 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008600 } catch (Exception ignored) {
8601 }
8602 }
8603
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07008604 @Override
Udam Sainicd645462016-01-04 12:16:14 -08008605 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08008606 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008607 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008608 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008609
8610 if (!TextUtils.isEmpty(settingUrl)) {
8611 return settingUrl;
8612 }
8613
8614 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08008615 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008616 if (!TextUtils.isEmpty(settingUrl)) {
8617 return settingUrl;
8618 }
8619
8620 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08008621 }
8622
8623 @Override
junyulai070f9ff2019-01-16 20:23:34 +08008624 public void startNattKeepalive(Network network, int intervalSeconds,
8625 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008626 enforceKeepalivePermission();
8627 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08008628 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08008629 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08008630 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008631 }
8632
8633 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08008634 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08008635 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08008636 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07008637 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08008638 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07008639 mKeepaliveTracker.startNattKeepalive(
8640 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8641 intervalSeconds, cb,
8642 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8643 } finally {
8644 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8645 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08008646 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8647 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07008648 }
8649 }
junyulaid05a1922019-01-15 11:32:44 +08008650 }
8651
8652 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08008653 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08008654 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07008655 try {
8656 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08008657 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07008658 mKeepaliveTracker.startTcpKeepalive(
8659 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8660 } finally {
8661 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8662 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08008663 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8664 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07008665 }
8666 }
junyulai0835a1e2019-01-08 20:04:33 +08008667 }
8668
8669 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008670 public void stopKeepalive(Network network, int slot) {
8671 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08008672 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008673 }
8674
8675 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07008676 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08008677 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07008678
8679 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
8680 return;
8681 }
8682
lucaslin75ff7022020-12-17 04:14:35 +08008683 final long token = Binder.clearCallingIdentity();
8684 try {
Heemin Seogdb8489d2019-06-12 09:21:44 -07008685 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8686 ipMemoryStore.factoryReset();
lucaslin75ff7022020-12-17 04:14:35 +08008687 } finally {
8688 Binder.restoreCallingIdentity(token);
8689 }
Xiao Ma555e4082019-04-10 19:01:52 +09008690
Stuart Scottd5463642015-04-02 18:00:02 -07008691 // Turn airplane mode off
8692 setAirplaneMode(false);
8693
Xiao Maf94d57a2019-06-12 16:31:14 +09008694 // restore private DNS settings to default mode (opportunistic)
8695 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_PRIVATE_DNS)) {
lucaslinb1ff1b22021-04-23 21:03:39 +08008696 ConnectivitySettingsManager.setPrivateDnsMode(mContext, PRIVATE_DNS_MODE_OPPORTUNISTIC);
Xiao Maf94d57a2019-06-12 16:31:14 +09008697 }
8698
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09008699 Settings.Global.putString(mContext.getContentResolver(),
paulhu90a7a512021-03-17 17:19:09 +08008700 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottd5463642015-04-02 18:00:02 -07008701 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04008702
Ricky Wai7097cc92018-01-23 04:09:45 +00008703 @Override
8704 public byte[] getNetworkWatchlistConfigHash() {
8705 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8706 if (nwm == null) {
8707 loge("Unable to get NetworkWatchlistManager");
8708 return null;
8709 }
8710 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8711 return nwm.getWatchlistConfigHash();
8712 }
8713
Hugo Benichibe0c7652016-05-31 16:28:06 +09008714 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09008715 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08008716 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09008717 }
Hugo Benichif4210292017-04-21 15:07:12 +09008718
8719 private static boolean toBool(int encodedBoolean) {
8720 return encodedBoolean != 0; // Only 0 means false.
8721 }
8722
8723 private static int encodeBool(boolean b) {
8724 return b ? 1 : 0;
8725 }
mswest4632928412018-03-12 10:34:34 -07008726
8727 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08008728 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8729 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8730 @NonNull String[] args) {
8731 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8732 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07008733 }
8734
Chiachang Wang77ae8a02020-10-12 15:20:07 +08008735 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07008736 @Override
8737 public int onCommand(String cmd) {
8738 if (cmd == null) {
8739 return handleDefaultCommands(cmd);
8740 }
8741 final PrintWriter pw = getOutPrintWriter();
8742 try {
8743 switch (cmd) {
8744 case "airplane-mode":
8745 final String action = getNextArg();
8746 if ("enable".equals(action)) {
8747 setAirplaneMode(true);
8748 return 0;
8749 } else if ("disable".equals(action)) {
8750 setAirplaneMode(false);
8751 return 0;
8752 } else if (action == null) {
8753 final ContentResolver cr = mContext.getContentResolver();
8754 final int enabled = Settings.Global.getInt(cr,
8755 Settings.Global.AIRPLANE_MODE_ON);
8756 pw.println(enabled == 0 ? "disabled" : "enabled");
8757 return 0;
8758 } else {
8759 onHelp();
8760 return -1;
8761 }
8762 default:
8763 return handleDefaultCommands(cmd);
8764 }
8765 } catch (Exception e) {
8766 pw.println(e);
8767 }
8768 return -1;
8769 }
8770
8771 @Override
8772 public void onHelp() {
8773 PrintWriter pw = getOutPrintWriter();
8774 pw.println("Connectivity service commands:");
8775 pw.println(" help");
8776 pw.println(" Print this help text.");
8777 pw.println(" airplane-mode [enable|disable]");
8778 pw.println(" Turn airplane mode on or off.");
8779 pw.println(" airplane-mode");
8780 pw.println(" Get airplane mode.");
8781 }
8782 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008783
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09008784 private @VpnManager.VpnType int getVpnType(@Nullable NetworkAgentInfo vpn) {
8785 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8786 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8787 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08008788 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008789 }
8790
8791 /**
8792 * @param connectionInfo the connection to resolve.
8793 * @return {@code uid} if the connection is found and the app has permission to observe it
8794 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8795 * connection is not found.
8796 */
8797 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008798 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8799 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8800 }
8801
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09008802 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008803 connectionInfo.local, connectionInfo.remote);
8804
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09008805 if (uid == INVALID_UID) return uid; // Not found.
8806
8807 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8808 // VPN, if any, that applies to the UID that owns the connection.
8809 if (checkNetworkStackPermission()) return uid;
8810
8811 final NetworkAgentInfo vpn = getVpnForUid(uid);
8812 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008813 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008814 return INVALID_UID;
8815 }
8816
8817 return uid;
8818 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00008819
Benedict Wong493e04b2018-11-09 14:45:34 -08008820 /**
8821 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8822 *
8823 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8824 */
8825 @Override
8826 public IBinder startOrGetTestNetworkService() {
8827 synchronized (mTNSLock) {
8828 TestNetworkService.enforceTestNetworkPermissions(mContext);
8829
8830 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08008831 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08008832 }
8833
8834 return mTNS;
8835 }
8836 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08008837
Cody Kesting73708bf2019-12-18 10:57:50 -08008838 /**
8839 * Handler used for managing all Connectivity Diagnostics related functions.
8840 *
8841 * @see android.net.ConnectivityDiagnosticsManager
8842 *
8843 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8844 */
8845 @VisibleForTesting
8846 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08008847 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8848
Cody Kesting73708bf2019-12-18 10:57:50 -08008849 /**
8850 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8851 * android.net.ConnectivityDiagnosticsManager}.
8852 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8853 * NetworkRequestInfo to be registered
8854 */
8855 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8856
8857 /**
8858 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
8859 * android.net.ConnectivityDiagnosticsManager}.
8860 * obj = the IConnectivityDiagnosticsCallback to be unregistered
8861 * arg1 = the uid of the caller
8862 */
8863 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
8864
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008865 /**
8866 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
8867 * after processing {@link #EVENT_NETWORK_TESTED} events.
8868 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
8869 * NetworkMonitor.
8870 * data = PersistableBundle of extras passed from NetworkMonitor.
8871 *
8872 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
8873 */
8874 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
8875
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008876 /**
8877 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
8878 * been detected on the network.
8879 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
8880 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
8881 * arg2 = NetID.
8882 * data = PersistableBundle of extras passed from NetworkMonitor.
8883 */
8884 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
8885
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08008886 /**
8887 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
8888 * the platform. This event will invoke {@link
8889 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
8890 * callbacks.
8891 * obj = Network that was reported on
8892 * arg1 = boolint for the quality reported
8893 */
8894 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
8895
Cody Kesting73708bf2019-12-18 10:57:50 -08008896 private ConnectivityDiagnosticsHandler(Looper looper) {
8897 super(looper);
8898 }
8899
8900 @Override
8901 public void handleMessage(Message msg) {
8902 switch (msg.what) {
8903 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8904 handleRegisterConnectivityDiagnosticsCallback(
8905 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
8906 break;
8907 }
8908 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8909 handleUnregisterConnectivityDiagnosticsCallback(
8910 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
8911 break;
8912 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008913 case EVENT_NETWORK_TESTED: {
8914 final ConnectivityReportEvent reportEvent =
8915 (ConnectivityReportEvent) msg.obj;
8916
Aaron Huang959d3642021-01-21 15:47:41 +08008917 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008918 break;
8919 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008920 case EVENT_DATA_STALL_SUSPECTED: {
8921 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08008922 final Pair<Long, PersistableBundle> arg =
8923 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008924 if (nai == null) break;
8925
Aaron Huang959d3642021-01-21 15:47:41 +08008926 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08008927 break;
8928 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08008929 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
8930 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
8931 break;
8932 }
8933 default: {
8934 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
8935 }
Cody Kesting73708bf2019-12-18 10:57:50 -08008936 }
8937 }
8938 }
8939
8940 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
8941 @VisibleForTesting
8942 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
8943 @NonNull private final IConnectivityDiagnosticsCallback mCb;
8944 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008945 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08008946
8947 @VisibleForTesting
8948 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008949 @NonNull IConnectivityDiagnosticsCallback cb,
8950 @NonNull NetworkRequestInfo nri,
8951 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008952 mCb = cb;
8953 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008954 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08008955 }
8956
8957 @Override
8958 public void binderDied() {
8959 log("ConnectivityDiagnosticsCallback IBinder died.");
8960 unregisterConnectivityDiagnosticsCallback(mCb);
8961 }
8962 }
8963
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008964 /**
8965 * Class used for sending information from {@link
8966 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
8967 */
8968 private static class NetworkTestedResults {
8969 private final int mNetId;
8970 private final int mTestResult;
8971 private final long mTimestampMillis;
8972 @Nullable private final String mRedirectUrl;
8973
8974 private NetworkTestedResults(
8975 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
8976 mNetId = netId;
8977 mTestResult = testResult;
8978 mTimestampMillis = timestampMillis;
8979 mRedirectUrl = redirectUrl;
8980 }
8981 }
8982
8983 /**
8984 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
8985 * ConnectivityDiagnosticsHandler}.
8986 */
8987 private static class ConnectivityReportEvent {
8988 private final long mTimestampMillis;
8989 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08008990 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008991
Aaron Huang959d3642021-01-21 15:47:41 +08008992 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
8993 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008994 mTimestampMillis = timestampMillis;
8995 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08008996 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08008997 }
8998 }
8999
Cody Kesting73708bf2019-12-18 10:57:50 -08009000 private void handleRegisterConnectivityDiagnosticsCallback(
9001 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9002 ensureRunningOnConnectivityServiceThread();
9003
9004 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009005 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009006 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9007
James Mattis64b8b0f2020-11-24 17:40:49 -08009008 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9009 // confusing for these networks to change when an NRI is satisfied in another layer.
9010 if (nri.isMultilayerRequest()) {
9011 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9012 + "network requests.");
9013 }
9014
Cody Kesting73708bf2019-12-18 10:57:50 -08009015 // This means that the client registered the same callback multiple times. Do
9016 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009017 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009018 if (VDBG) log("Diagnostics callback is already registered");
9019
9020 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9021 // incremented when the NetworkRequestInfo is created as part of
9022 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009023 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009024 return;
9025 }
9026
Cody Kesting31f1ff62020-03-05 10:46:02 -08009027 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009028
9029 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009030 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009031 } catch (RemoteException e) {
9032 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009033 return;
9034 }
9035
9036 // Once registered, provide ConnectivityReports for matching Networks
9037 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9038 synchronized (mNetworkForNetId) {
9039 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9040 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009041 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9042 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009043 matchingNetworks.add(nai);
9044 }
9045 }
9046 }
9047 for (final NetworkAgentInfo nai : matchingNetworks) {
9048 final ConnectivityReport report = nai.getConnectivityReport();
9049 if (report == null) {
9050 continue;
9051 }
9052 if (!checkConnectivityDiagnosticsPermissions(
9053 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9054 continue;
9055 }
9056
9057 try {
9058 cb.onConnectivityReportAvailable(report);
9059 } catch (RemoteException e) {
9060 // Exception while sending the ConnectivityReport. Move on to the next network.
9061 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009062 }
9063 }
9064
9065 private void handleUnregisterConnectivityDiagnosticsCallback(
9066 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9067 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009068 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009069
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009070 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9071 mConnectivityDiagnosticsCallbacks.remove(iCb);
9072 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009073 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9074 return;
9075 }
9076
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009077 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009078
Cody Kesting70fa2b22020-12-02 12:16:56 -08009079 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9080 // (if the Binder died)
9081 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9082 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009083 return;
9084 }
9085
Cody Kesting46cb1672020-03-04 13:35:20 -08009086 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9087 // incremented when the NetworkRequestInfo is created as part of
9088 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009089 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009090
Cody Kesting31f1ff62020-03-05 10:46:02 -08009091 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009092 }
9093
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009094 private void handleNetworkTestedWithExtras(
9095 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9096 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009097 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009098 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009099 final ConnectivityReport report =
9100 new ConnectivityReport(
9101 reportEvent.mNai.network,
9102 reportEvent.mTimestampMillis,
9103 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009104 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009105 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009106 nai.setConnectivityReport(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009107 final List<IConnectivityDiagnosticsCallback> results =
9108 getMatchingPermissionedCallbacks(nai);
9109 for (final IConnectivityDiagnosticsCallback cb : results) {
9110 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009111 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009112 } catch (RemoteException ex) {
9113 loge("Error invoking onConnectivityReport", ex);
9114 }
9115 }
9116 }
9117
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009118 private void handleDataStallSuspected(
9119 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9120 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009121 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009122 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009123 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009124 new DataStallReport(
9125 nai.network,
9126 timestampMillis,
9127 detectionMethod,
9128 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009129 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009130 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009131 final List<IConnectivityDiagnosticsCallback> results =
9132 getMatchingPermissionedCallbacks(nai);
9133 for (final IConnectivityDiagnosticsCallback cb : results) {
9134 try {
9135 cb.onDataStallSuspected(report);
9136 } catch (RemoteException ex) {
9137 loge("Error invoking onDataStallSuspected", ex);
9138 }
9139 }
9140 }
9141
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009142 private void handleNetworkConnectivityReported(
9143 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9144 final List<IConnectivityDiagnosticsCallback> results =
9145 getMatchingPermissionedCallbacks(nai);
9146 for (final IConnectivityDiagnosticsCallback cb : results) {
9147 try {
9148 cb.onNetworkConnectivityReported(nai.network, connectivity);
9149 } catch (RemoteException ex) {
9150 loge("Error invoking onNetworkConnectivityReported", ex);
9151 }
9152 }
9153 }
9154
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009155 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009156 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9157 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009158 sanitized.setUids(null);
9159 sanitized.setAdministratorUids(new int[0]);
9160 sanitized.setOwnerUid(Process.INVALID_UID);
9161 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009162 }
9163
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009164 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9165 @NonNull NetworkAgentInfo nai) {
9166 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009167 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009168 mConnectivityDiagnosticsCallbacks.entrySet()) {
9169 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9170 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
James Mattis64b8b0f2020-11-24 17:40:49 -08009171 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9172 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009173 if (checkConnectivityDiagnosticsPermissions(
9174 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009175 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009176 }
9177 }
9178 }
9179 return results;
9180 }
9181
9182 @VisibleForTesting
9183 boolean checkConnectivityDiagnosticsPermissions(
9184 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9185 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9186 return true;
9187 }
9188
Cody Kestinga8304392020-02-07 14:49:34 -08009189 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9190 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9191 // call in a try-catch.
9192 try {
9193 if (!mLocationPermissionChecker.checkLocationPermission(
9194 callbackPackageName, null /* featureId */, callbackUid, null /* message */)) {
9195 return false;
9196 }
9197 } catch (SecurityException e) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009198 return false;
9199 }
9200
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009201 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colitti083b00b2020-11-16 23:41:21 +09009202 if (virtual.supportsUnderlyingNetworks()
9203 && virtual.networkCapabilities.getOwnerUid() == callbackUid
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09009204 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, nai.network)) {
Lorenzo Colitti083b00b2020-11-16 23:41:21 +09009205 return true;
9206 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009207 }
9208
9209 // Administrator UIDs also contains the Owner UID
Cody Kesting5ab1f552020-03-16 18:15:28 -07009210 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09009211 return CollectionUtils.contains(administratorUids, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009212 }
9213
Cody Kestingd199a9d2019-12-17 12:55:28 -08009214 @Override
9215 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009216 @NonNull IConnectivityDiagnosticsCallback callback,
9217 @NonNull NetworkRequest request,
9218 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009219 if (request.legacyType != TYPE_NONE) {
9220 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9221 + " Please use NetworkCapabilities instead.");
9222 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009223 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009224 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009225
9226 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9227 // and administrator uids to be safe.
9228 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009229 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009230
9231 final NetworkRequest requestWithId =
9232 new NetworkRequest(
9233 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9234
9235 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9236 //
9237 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9238 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9239 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009240 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009241 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009242 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009243
9244 mConnectivityDiagnosticsHandler.sendMessage(
9245 mConnectivityDiagnosticsHandler.obtainMessage(
9246 ConnectivityDiagnosticsHandler
9247 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9248 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009249 }
9250
9251 @Override
9252 public void unregisterConnectivityDiagnosticsCallback(
9253 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009254 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009255 mConnectivityDiagnosticsHandler.sendMessage(
9256 mConnectivityDiagnosticsHandler.obtainMessage(
9257 ConnectivityDiagnosticsHandler
9258 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009259 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009260 0,
9261 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009262 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009263
9264 @Override
9265 public void simulateDataStall(int detectionMethod, long timestampMillis,
9266 @NonNull Network network, @NonNull PersistableBundle extras) {
9267 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9268 android.Manifest.permission.NETWORK_STACK);
9269 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9270 if (!nc.hasTransport(TRANSPORT_TEST)) {
9271 throw new SecurityException("Data Stall simluation is only possible for test networks");
9272 }
9273
9274 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009275 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009276 throw new SecurityException("Data Stall simulation is only possible for network "
9277 + "creators");
9278 }
9279
Cody Kesting652e3ec2020-05-21 12:08:21 -07009280 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9281 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9282 // Data Stall information as a DataStallReportParcelable and passing to
9283 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9284 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009285 final DataStallReportParcelable p = new DataStallReportParcelable();
9286 p.timestampMillis = timestampMillis;
9287 p.detectionMethod = detectionMethod;
9288
9289 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9290 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9291 }
9292 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9293 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9294 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9295 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9296 }
9297
Serik Beketayevec8ad212020-12-07 22:43:07 -08009298 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009299 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009300
lucaslin66f44212021-02-23 01:12:55 +08009301 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9302 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009303 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009304 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009305 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009306 }
lucaslin37a16d92021-01-21 19:48:09 +08009307
9308 @Override
9309 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009310 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009311 nai.clatd.interfaceLinkStateChanged(iface, up);
9312 }
9313 }
9314
9315 @Override
9316 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009317 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009318 nai.clatd.interfaceRemoved(iface);
9319 }
lucaslin66f44212021-02-23 01:12:55 +08009320 }
9321 }
9322
lucaslin1a8b4c62021-01-21 02:02:55 +08009323 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9324
9325 /**
9326 * Class used for updating network activity tracking with netd and notify network activity
9327 * changes.
9328 */
9329 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009330 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009331 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009332 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009333 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9334 new RemoteCallbackList<>();
9335 // Indicate the current system default network activity is active or not.
9336 @GuardedBy("mActiveIdleTimers")
9337 private boolean mNetworkActive;
9338 @GuardedBy("mActiveIdleTimers")
9339 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9340 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009341
lucaslin1193a5d2021-01-21 02:04:15 +08009342 private class IdleTimerParams {
9343 public final int timeout;
9344 public final int transportType;
9345
9346 IdleTimerParams(int timeout, int transport) {
9347 this.timeout = timeout;
9348 this.transportType = transport;
9349 }
9350 }
9351
9352 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009353 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009354 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009355 mNetd = netd;
9356 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009357 }
9358
lucaslin66f44212021-02-23 01:12:55 +08009359 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9360 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9361 synchronized (mActiveIdleTimers) {
9362 mNetworkActive = active;
9363 // If there are no idle timers, it means that system is not monitoring
9364 // activity, so the system default network for those default network
9365 // unspecified apps is always considered active.
9366 //
9367 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9368 // any network activity change event. Whenever this event is received,
9369 // the mActiveIdleTimers should be always not empty. The legacy behavior
9370 // is no-op. Remove to refer to mNetworkActive only.
9371 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9372 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9373 }
9374 }
9375 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009376
lucaslin1193a5d2021-01-21 02:04:15 +08009377 // The network activity should only be updated from ConnectivityService handler thread
9378 // when mActiveIdleTimers lock is held.
9379 @GuardedBy("mActiveIdleTimers")
9380 private void reportNetworkActive() {
9381 final int length = mNetworkActivityListeners.beginBroadcast();
9382 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9383 try {
9384 for (int i = 0; i < length; i++) {
9385 try {
9386 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9387 } catch (RemoteException | RuntimeException e) {
9388 loge("Fail to send network activie to listener " + e);
9389 }
9390 }
9391 } finally {
9392 mNetworkActivityListeners.finishBroadcast();
9393 }
9394 }
9395
9396 @GuardedBy("mActiveIdleTimers")
9397 public void handleReportNetworkActivity() {
9398 synchronized (mActiveIdleTimers) {
9399 reportNetworkActive();
9400 }
9401 }
9402
lucaslin1a8b4c62021-01-21 02:02:55 +08009403 // This is deprecated and only to support legacy use cases.
9404 private int transportTypeToLegacyType(int type) {
9405 switch (type) {
9406 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009407 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009408 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009409 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009410 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009411 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009412 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009413 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009414 default:
9415 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9416 }
9417 return ConnectivityManager.TYPE_NONE;
9418 }
9419
9420 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9421 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9422 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9423 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9424 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9425 final long ident = Binder.clearCallingIdentity();
9426 try {
9427 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9428 RECEIVE_DATA_ACTIVITY_CHANGE,
9429 null /* resultReceiver */,
9430 null /* scheduler */,
9431 0 /* initialCode */,
9432 null /* initialData */,
9433 null /* initialExtra */);
9434 } finally {
9435 Binder.restoreCallingIdentity(ident);
9436 }
9437 }
9438
9439 /**
9440 * Setup data activity tracking for the given network.
9441 *
9442 * Every {@code setupDataActivityTracking} should be paired with a
9443 * {@link #removeDataActivityTracking} for cleanup.
9444 */
9445 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9446 final String iface = networkAgent.linkProperties.getInterfaceName();
9447
9448 final int timeout;
9449 final int type;
9450
9451 if (networkAgent.networkCapabilities.hasTransport(
9452 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9453 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009454 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009455 10);
9456 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9457 } else if (networkAgent.networkCapabilities.hasTransport(
9458 NetworkCapabilities.TRANSPORT_WIFI)) {
9459 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009460 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009461 15);
9462 type = NetworkCapabilities.TRANSPORT_WIFI;
9463 } else {
9464 return; // do not track any other networks
9465 }
9466
lucaslinb961efc2021-01-21 02:03:17 +08009467 updateRadioPowerState(true /* isActive */, type);
9468
lucaslin1a8b4c62021-01-21 02:02:55 +08009469 if (timeout > 0 && iface != null) {
9470 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009471 synchronized (mActiveIdleTimers) {
9472 // Networks start up.
9473 mNetworkActive = true;
9474 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9475 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9476 reportNetworkActive();
9477 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009478 } catch (Exception e) {
9479 // You shall not crash!
9480 loge("Exception in setupDataActivityTracking " + e);
9481 }
9482 }
9483 }
9484
9485 /**
9486 * Remove data activity tracking when network disconnects.
9487 */
9488 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9489 final String iface = networkAgent.linkProperties.getInterfaceName();
9490 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9491
lucaslinb961efc2021-01-21 02:03:17 +08009492 if (iface == null) return;
9493
9494 final int type;
9495 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9496 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9497 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9498 type = NetworkCapabilities.TRANSPORT_WIFI;
9499 } else {
9500 return; // do not track any other networks
9501 }
9502
9503 try {
9504 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +08009505 synchronized (mActiveIdleTimers) {
9506 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9507 // The call fails silently if no idle timer setup for this interface
9508 mNetd.idletimerRemoveInterface(iface, params.timeout,
9509 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +08009510 }
lucaslinb961efc2021-01-21 02:03:17 +08009511 } catch (Exception e) {
9512 // You shall not crash!
9513 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +08009514 }
9515 }
9516
9517 /**
9518 * Update data activity tracking when network state is updated.
9519 */
9520 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9521 NetworkAgentInfo oldNetwork) {
9522 if (newNetwork != null) {
9523 setupDataActivityTracking(newNetwork);
9524 }
9525 if (oldNetwork != null) {
9526 removeDataActivityTracking(oldNetwork);
9527 }
9528 }
lucaslinb961efc2021-01-21 02:03:17 +08009529
9530 private void updateRadioPowerState(boolean isActive, int transportType) {
9531 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9532 switch (transportType) {
9533 case NetworkCapabilities.TRANSPORT_CELLULAR:
9534 bs.reportMobileRadioPowerState(isActive, NO_UID);
9535 break;
9536 case NetworkCapabilities.TRANSPORT_WIFI:
9537 bs.reportWifiRadioPowerState(isActive, NO_UID);
9538 break;
9539 default:
9540 logw("Untracked transport type:" + transportType);
9541 }
9542 }
lucaslin1193a5d2021-01-21 02:04:15 +08009543
9544 public boolean isDefaultNetworkActive() {
9545 synchronized (mActiveIdleTimers) {
9546 // If there are no idle timers, it means that system is not monitoring activity,
9547 // so the default network is always considered active.
9548 //
9549 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9550 // tracking is disabled (negative idle timer value configured), or no active default
9551 // network. In the latter case, this reports active but it should report inactive.
9552 return mNetworkActive || mActiveIdleTimers.isEmpty();
9553 }
9554 }
9555
9556 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9557 mNetworkActivityListeners.register(l);
9558 }
9559
9560 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9561 mNetworkActivityListeners.unregister(l);
9562 }
lucaslin012f7a12021-01-21 02:04:35 +08009563
9564 public void dump(IndentingPrintWriter pw) {
9565 synchronized (mActiveIdleTimers) {
9566 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9567 pw.println("Idle timers:");
9568 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9569 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9570 final IdleTimerParams params = ent.getValue();
9571 pw.print(" timeout="); pw.print(params.timeout);
9572 pw.print(" type="); pw.println(params.transportType);
9573 }
9574 }
9575 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009576 }
James Mattis47db0582021-01-01 14:13:35 -08009577
Daniel Brightf9e945b2020-06-15 16:10:01 -07009578 /**
9579 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9580 *
9581 * @param socketInfo the socket information
9582 * @param callback the callback to register
9583 */
9584 @Override
9585 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9586 @NonNull final IQosCallback callback) {
9587 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9588 if (nai == null || nai.networkCapabilities == null) {
9589 try {
9590 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9591 } catch (final RemoteException ex) {
9592 loge("registerQosCallbackInternal: RemoteException", ex);
9593 }
9594 return;
9595 }
9596 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9597 }
9598
9599 /**
9600 * Register a {@link IQosCallback} with base {@link QosFilter}.
9601 *
9602 * @param filter the filter to register
9603 * @param callback the callback to register
9604 * @param nai the agent information related to the filter's network
9605 */
9606 @VisibleForTesting
9607 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9608 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9609 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9610 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9611
9612 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9613 enforceConnectivityRestrictedNetworksPermission();
9614 }
9615 mQosCallbackTracker.registerCallback(callback, filter, nai);
9616 }
9617
9618 /**
9619 * Unregisters the given callback.
9620 *
9621 * @param callback the callback to unregister
9622 */
9623 @Override
9624 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009625 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07009626 mQosCallbackTracker.unregisterCallback(callback);
9627 }
James Mattis47db0582021-01-01 14:13:35 -08009628
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009629 // Network preference per-profile and OEM network preferences can't be set at the same
9630 // time, because it is unclear what should happen if both preferences are active for
9631 // one given UID. To make it possible, the stack would have to clarify what would happen
9632 // in case both are active at the same time. The implementation may have to be adjusted
9633 // to implement the resulting rules. For example, a priority could be defined between them,
9634 // where the OEM preference would be considered less or more important than the enterprise
9635 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9636 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9637 // are set at the right level. Other solutions are possible, e.g. merging of the
9638 // preferences for the relevant UIDs.
9639 private static void throwConcurrentPreferenceException() {
9640 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9641 + "set OemNetworkPreference at the same time");
James Mattis45d81842021-01-10 14:24:24 -08009642 }
9643
9644 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +09009645 * Request that a user profile is put by default on a network matching a given preference.
9646 *
9647 * See the documentation for the individual preferences for a description of the supported
9648 * behaviors.
9649 *
9650 * @param profile the profile concerned.
9651 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9652 * constants.
9653 * @param listener an optional listener to listen for completion of the operation.
9654 */
9655 @Override
9656 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9657 @ConnectivityManager.ProfileNetworkPreference final int preference,
9658 @Nullable final IOnCompleteListener listener) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009659 Objects.requireNonNull(profile);
9660 PermissionUtils.enforceNetworkStackPermission(mContext);
9661 if (DBG) {
9662 log("setProfileNetworkPreference " + profile + " to " + preference);
9663 }
9664 if (profile.getIdentifier() < 0) {
9665 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9666 + "UserHandle.CURRENT not supported)");
9667 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +09009668 final UserManager um = mContext.getSystemService(UserManager.class);
9669 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009670 throw new IllegalArgumentException("Profile must be a managed profile");
9671 }
9672 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9673 // handler thread. However it is an immutable object, so reading the reference is
9674 // safe - it's just possible the value is slightly outdated. For the final check,
9675 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9676 // lot easier to understand, so opportunistically check it.
9677 if (!mOemNetworkPreferences.isEmpty()) {
9678 throwConcurrentPreferenceException();
9679 }
9680 final NetworkCapabilities nc;
9681 switch (preference) {
9682 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9683 nc = null;
9684 break;
9685 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9686 final UidRange uids = UidRange.createForUser(profile);
9687 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9688 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9689 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9690 break;
9691 default:
9692 throw new IllegalArgumentException(
9693 "Invalid preference in setProfileNetworkPreference");
9694 }
9695 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9696 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9697 }
9698
9699 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9700 @Nullable final NetworkCapabilities nc) {
9701 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9702 ensureRequestableCapabilities(nc);
9703 }
9704
9705 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9706 @NonNull final ProfileNetworkPreferences prefs) {
9707 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9708 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9709 // The NRI for a user should be comprised of two layers:
9710 // - The request for the capabilities
9711 // - The request for the default network, for fallback. Create an image of it to
9712 // have the correct UIDs in it (also a request can only be part of one NRI, because
9713 // of lookups in 1:1 associations like mNetworkRequests).
9714 // Note that denying a fallback can be implemented simply by not adding the second
9715 // request.
9716 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9717 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
James Mattisa117e282021-04-20 17:26:30 -07009718 nrs.add(createDefaultInternetRequestForTransport(
9719 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009720 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009721 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009722 result.add(nri);
9723 }
9724 return result;
9725 }
9726
9727 private void handleSetProfileNetworkPreference(
9728 @NonNull final ProfileNetworkPreferences.Preference preference,
9729 @Nullable final IOnCompleteListener listener) {
9730 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9731 // particular because it's not clear what preference should win in case both apply
9732 // to the same app.
9733 // The binder call has already checked this, but as mOemNetworkPreferences is only
9734 // touched on the handler thread, it's theoretically not impossible that it has changed
9735 // since.
9736 if (!mOemNetworkPreferences.isEmpty()) {
Chalard Jean0f57a492021-03-09 21:09:20 +09009737 // This may happen on a device with an OEM preference set when a user is removed.
9738 // In this case, it's safe to ignore. In particular this happens in the tests.
9739 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009740 return;
9741 }
9742
9743 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9744
9745 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
James Mattis20a4a8b2021-03-28 17:41:09 -07009746 mSystemNetworkRequestCounter.transact(
9747 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9748 () -> {
9749 final ArraySet<NetworkRequestInfo> nris =
9750 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9751 replaceDefaultNetworkRequestsForPreference(nris);
9752 });
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009753 // Finally, rematch.
9754 rematchAllNetworksAndRequests();
9755
9756 if (null != listener) {
9757 try {
9758 listener.onComplete();
9759 } catch (RemoteException e) {
9760 loge("Listener for setProfileNetworkPreference has died");
9761 }
9762 }
9763 }
9764
James Mattis45d81842021-01-10 14:24:24 -08009765 private void enforceAutomotiveDevice() {
9766 final boolean isAutomotiveDevice =
9767 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9768 if (!isAutomotiveDevice) {
9769 throw new UnsupportedOperationException(
9770 "setOemNetworkPreference() is only available on automotive devices.");
9771 }
9772 }
9773
9774 /**
9775 * Used by automotive devices to set the network preferences used to direct traffic at an
9776 * application level as per the given OemNetworkPreferences. An example use-case would be an
9777 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9778 * vehicle via a particular network.
9779 *
9780 * Calling this will overwrite the existing preference.
9781 *
James Mattisda32cfe2021-01-26 16:23:52 -08009782 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +09009783 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -08009784 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -08009785 */
James Mattis47db0582021-01-01 14:13:35 -08009786 @Override
James Mattis45d81842021-01-10 14:24:24 -08009787 public void setOemNetworkPreference(
9788 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +09009789 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -08009790
James Mattis45d81842021-01-10 14:24:24 -08009791 enforceAutomotiveDevice();
James Mattisda32cfe2021-01-26 16:23:52 -08009792 enforceOemNetworkPreferencesPermission();
James Mattis45d81842021-01-10 14:24:24 -08009793
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009794 if (!mProfileNetworkPreferences.isEmpty()) {
9795 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9796 // handler thread. However it is an immutable object, so reading the reference is
9797 // safe - it's just possible the value is slightly outdated. For the final check,
9798 // see #handleSetOemPreference. But if this can be caught here it is a
9799 // lot easier to understand, so opportunistically check it.
9800 throwConcurrentPreferenceException();
9801 }
9802
James Mattis45d81842021-01-10 14:24:24 -08009803 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9804 validateOemNetworkPreferences(preference);
9805 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9806 new Pair<>(preference, listener)));
9807 }
9808
9809 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9810 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9811 : preference.getNetworkPreferences().values()) {
9812 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9813 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9814 throw new IllegalArgumentException(msg);
9815 }
9816 }
9817 }
9818
9819 private void handleSetOemNetworkPreference(
9820 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +09009821 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -08009822 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9823 if (DBG) {
9824 log("set OEM network preferences :" + preference.toString());
9825 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009826 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9827 // particular because it's not clear what preference should win in case both apply
9828 // to the same app.
9829 // The binder call has already checked this, but as mOemNetworkPreferences is only
9830 // touched on the handler thread, it's theoretically not impossible that it has changed
9831 // since.
9832 if (!mProfileNetworkPreferences.isEmpty()) {
9833 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9834 return;
9835 }
9836
James Mattiscb1e0362021-04-06 17:07:42 -07009837 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
James Mattis20a4a8b2021-03-28 17:41:09 -07009838 final int uniquePreferenceCount = new ArraySet<>(
9839 preference.getNetworkPreferences().values()).size();
9840 mSystemNetworkRequestCounter.transact(
9841 mDeps.getCallingUid(), uniquePreferenceCount,
9842 () -> {
9843 final ArraySet<NetworkRequestInfo> nris =
9844 new OemNetworkRequestFactory()
9845 .createNrisFromOemNetworkPreferences(preference);
9846 replaceDefaultNetworkRequestsForPreference(nris);
9847 });
James Mattis45d81842021-01-10 14:24:24 -08009848 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -08009849
9850 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009851 try {
9852 listener.onComplete();
9853 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -08009854 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009855 }
James Mattis45d81842021-01-10 14:24:24 -08009856 }
9857 }
9858
Chalard Jean17215832021-03-01 14:06:28 +09009859 private void replaceDefaultNetworkRequestsForPreference(
James Mattis3ce3d3c2021-02-09 18:18:28 -08009860 @NonNull final Set<NetworkRequestInfo> nris) {
James Mattisc12c1f12021-02-20 14:40:51 -08009861 // Pass in a defensive copy as this collection will be updated on remove.
9862 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
James Mattis3ce3d3c2021-02-09 18:18:28 -08009863 addPerAppDefaultNetworkRequests(nris);
James Mattis45d81842021-01-10 14:24:24 -08009864 }
9865
James Mattis3ce3d3c2021-02-09 18:18:28 -08009866 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9867 ensureRunningOnConnectivityServiceThread();
9868 mDefaultNetworkRequests.addAll(nris);
9869 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9870 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -08009871 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
James Mattis20a4a8b2021-03-28 17:41:09 -07009872 mSystemNetworkRequestCounter.transact(
9873 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9874 () -> {
9875 nrisToRegister.addAll(
9876 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9877 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9878 handleRegisterNetworkRequests(nrisToRegister);
9879 });
James Mattis3ce3d3c2021-02-09 18:18:28 -08009880 }
9881
9882 /**
9883 * All current requests that are tracking the default network need to be assessed as to whether
9884 * or not the current set of per-application default requests will be changing their default
9885 * network. If so, those requests will need to be updated so that they will send callbacks for
9886 * default network changes at the appropriate time. Additionally, those requests tracking the
9887 * default that were previously updated by this flow will need to be reassessed.
9888 * @return the nris which will need to be updated.
9889 */
9890 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9891 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9892 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9893 // same nri in the map's values for each of its NetworkRequest objects.
9894 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -08009895 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009896 // Include this nri if it is currently being tracked.
9897 if (isPerAppTrackedNri(nri)) {
9898 defaultCallbackRequests.add(nri);
9899 continue;
9900 }
9901 // We only track callbacks for requests tracking the default.
9902 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9903 continue;
9904 }
9905 // Include this nri if it will be tracked by the new per-app default requests.
9906 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009907 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08009908 if (isNriGoingToBeTracked) {
9909 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -08009910 }
9911 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08009912 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -08009913 }
9914
James Mattis3ce3d3c2021-02-09 18:18:28 -08009915 /**
9916 * Create nris for those network requests that are currently tracking the default network that
9917 * are being controlled by a per-application default.
9918 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
9919 * foundation when creating the nri. Important items include the calling uid's original
9920 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
9921 * requests are assumed to have already been validated as needing to be updated.
9922 * @return the Set of nris to use when registering network requests.
9923 */
9924 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
9925 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
9926 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
9927 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
9928 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009929 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08009930
9931 // If this nri is not being tracked, the change it back to an untracked nri.
9932 if (trackingNri == mDefaultRequest) {
9933 callbackRequestsToRegister.add(new NetworkRequestInfo(
9934 callbackRequest,
9935 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
9936 continue;
9937 }
9938
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009939 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -08009940 callbackRequestsToRegister.add(new NetworkRequestInfo(
9941 callbackRequest,
9942 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009943 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09009944 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -08009945 }
9946 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -08009947 }
9948
Chalard Jean17215832021-03-01 14:06:28 +09009949 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
9950 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +09009951 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009952 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +09009953 }
9954 }
9955
James Mattis45d81842021-01-10 14:24:24 -08009956 /**
9957 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
9958 */
9959 @VisibleForTesting
9960 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009961 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -08009962 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009963 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -08009964 final SparseArray<Set<Integer>> uids =
9965 createUidsFromOemNetworkPreferences(preference);
9966 for (int i = 0; i < uids.size(); i++) {
9967 final int key = uids.keyAt(i);
9968 final Set<Integer> value = uids.valueAt(i);
9969 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
9970 // No need to add an nri without any requests.
9971 if (0 == nri.mRequests.size()) {
9972 continue;
9973 }
9974 nris.add(nri);
9975 }
9976
9977 return nris;
9978 }
9979
9980 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
9981 @NonNull final OemNetworkPreferences preference) {
9982 final SparseArray<Set<Integer>> uids = new SparseArray<>();
9983 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -08009984 final List<UserHandle> users =
9985 mContext.getSystemService(UserManager.class).getUserHandles(true);
9986 if (null == users || users.size() == 0) {
9987 if (VDBG || DDBG) {
9988 log("No users currently available for setting the OEM network preference.");
9989 }
9990 return uids;
9991 }
James Mattis45d81842021-01-10 14:24:24 -08009992 for (final Map.Entry<String, Integer> entry :
9993 preference.getNetworkPreferences().entrySet()) {
9994 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
9995 try {
9996 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
9997 if (!uids.contains(pref)) {
9998 uids.put(pref, new ArraySet<>());
9999 }
James Mattisae9aeb02021-03-01 17:09:11 -080010000 for (final UserHandle ui : users) {
10001 // Add the rules for all users as this policy is device wide.
Chiachang Wang612cc032021-04-08 11:10:51 +080010002 uids.get(pref).add(ui.getUid(uid));
James Mattisae9aeb02021-03-01 17:09:11 -080010003 }
James Mattis45d81842021-01-10 14:24:24 -080010004 } catch (PackageManager.NameNotFoundException e) {
10005 // Although this may seem like an error scenario, it is ok that uninstalled
10006 // packages are sent on a network preference as the system will watch for
10007 // package installations associated with this network preference and update
10008 // accordingly. This is done so as to minimize race conditions on app install.
James Mattis45d81842021-01-10 14:24:24 -080010009 continue;
10010 }
10011 }
10012 return uids;
10013 }
10014
10015 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10016 @OemNetworkPreferences.OemNetworkPreference final int preference,
10017 @NonNull final Set<Integer> uids) {
10018 final List<NetworkRequest> requests = new ArrayList<>();
10019 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10020 switch (preference) {
10021 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10022 requests.add(createUnmeteredNetworkRequest());
10023 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010024 requests.add(createDefaultInternetRequestForTransport(
10025 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010026 break;
10027 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10028 requests.add(createUnmeteredNetworkRequest());
10029 requests.add(createOemPaidNetworkRequest());
10030 break;
10031 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10032 requests.add(createOemPaidNetworkRequest());
10033 break;
10034 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10035 requests.add(createOemPrivateNetworkRequest());
10036 break;
10037 default:
10038 // This should never happen.
10039 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10040 + " called with invalid preference of " + preference);
10041 }
10042
Chalard Jean17215832021-03-01 14:06:28 +090010043 final ArraySet ranges = new ArraySet<Integer>();
10044 for (final int uid : uids) {
10045 ranges.add(new UidRange(uid, uid));
10046 }
10047 setNetworkRequestUids(requests, ranges);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010048 return new NetworkRequestInfo(Process.myUid(), requests);
James Mattis45d81842021-01-10 14:24:24 -080010049 }
10050
10051 private NetworkRequest createUnmeteredNetworkRequest() {
10052 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10053 .addCapability(NET_CAPABILITY_NOT_METERED)
10054 .addCapability(NET_CAPABILITY_VALIDATED);
10055 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10056 }
10057
10058 private NetworkRequest createOemPaidNetworkRequest() {
10059 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10060 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10061 .addCapability(NET_CAPABILITY_OEM_PAID)
10062 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10063 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10064 }
10065
10066 private NetworkRequest createOemPrivateNetworkRequest() {
10067 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10068 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10069 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10070 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10071 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10072 }
10073
10074 private NetworkCapabilities createDefaultPerAppNetCap() {
10075 final NetworkCapabilities netCap = new NetworkCapabilities();
10076 netCap.addCapability(NET_CAPABILITY_INTERNET);
10077 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10078 return netCap;
10079 }
James Mattis47db0582021-01-01 14:13:35 -080010080 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010081}