blob: 05bacfaeaf0719a980a88e645a96d2394454a869 [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;
Cody Kesting7474f672021-05-11 14:22:40 -070080import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080081import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
James Mattisfa270db2021-05-31 17:11:10 -070082import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
83import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +090084import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070085import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080086import static android.os.Process.VPN_UID;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070087import static android.system.OsConstants.IPPROTO_TCP;
88import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060089
Cody Kesting83bb5fa2020-01-05 14:06:39 -080090import static java.util.Map.Entry;
91
Chalard Jean5b639762020-03-09 21:25:37 +090092import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +000093import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -080094import android.annotation.Nullable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080095import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -080096import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -070097import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +080098import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070099import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800100import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101import android.content.ContentResolver;
102import android.content.Context;
103import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700104import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800105import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700106import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900107import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900108import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700109import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800110import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800111import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800112import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900113import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800114import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900115import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900116import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800117import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900118import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800119import android.net.DnsResolverServiceManager;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900120import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800121import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800123import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800124import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800125import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900126import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900127import android.net.INetworkMonitor;
128import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900129import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900130import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700131import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800132import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900133import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900134import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900135import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800136import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100137import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800138import android.net.NativeNetworkConfig;
139import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800140import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700141import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700142import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900143import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700144import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700146import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900147import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900148import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000149import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900150import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700151import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900152import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700153import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900154import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700155import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800156import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900157import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700158import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000159import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800160import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.PrivateDnsConfigParcel;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400162import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700163import android.net.QosCallbackException;
164import android.net.QosFilter;
165import android.net.QosSocketFilter;
166import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700167import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800168import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800169import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800170import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900171import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400172import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800173import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800174import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400175import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800176import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900177import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900178import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900179import android.net.metrics.NetworkEvent;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700180import android.net.netlink.InetDiagMessage;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900181import android.net.networkstack.ModuleNetworkStackClient;
182import android.net.networkstack.NetworkStackClientBase;
paulhu7c0a2e62021-01-08 00:51:49 +0800183import android.net.resolv.aidl.DnsHealthEventParcel;
184import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
185import android.net.resolv.aidl.Nat64PrefixEventParcel;
186import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900187import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900188import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800189import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800190import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800191import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700192import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800193import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700194import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700195import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800196import android.os.Looper;
197import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700198import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700199import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900200import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800201import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700202import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700203import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800204import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700205import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900206import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900207import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700208import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700209import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400210import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800211import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900212import android.sysprop.NetworkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -0700213import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700214import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800215import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900216import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000217import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600218import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900219import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700220import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700221import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900223import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400224import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400225import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700226import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900227import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800228import com.android.modules.utils.BasicShellCommandHandler;
lucaslin66f44212021-02-23 01:12:55 +0800229import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900230import com.android.net.module.util.CollectionUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900231import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
232import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900233import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800234import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800235import com.android.net.module.util.PermissionUtils;
Chalard Jean7284daa2019-05-30 14:58:29 +0900236import com.android.server.connectivity.AutodestructReference;
Erik Kline32120082017-12-13 19:40:49 +0900237import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500238import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900239import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900240import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100241import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700242import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700243import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600244import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900245import com.android.server.connectivity.NetworkNotificationManager;
246import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900247import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900248import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700249import com.android.server.connectivity.PermissionMonitor;
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900250import com.android.server.connectivity.ProfileNetworkPreferences;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900251import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700252import com.android.server.connectivity.QosCallbackTracker;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600253
Josh Gao461a1222020-06-16 15:58:11 -0700254import libcore.io.IoUtils;
255
The Android Open Source Project28527d22009-03-03 19:31:44 -0800256import java.io.FileDescriptor;
257import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700258import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700259import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900260import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700261import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700262import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700263import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700264import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800265import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900266import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800267import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700268import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700269import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700270import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700271import java.util.Map;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700272import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900273import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600274import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900275import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600276import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900277import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800278
279/**
280 * @hide
281 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800282public class ConnectivityService extends IConnectivityManager.Stub
283 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900284 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800285
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900286 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900287 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900288 private static final String NETWORK_ARG = "networks";
289 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900290
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900291 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900292 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
293 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800294
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900295 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700296
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100297 /**
298 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
299 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800300 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100301 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
302 * (preferably via runtime resource overlays).
303 */
304 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
305 "http://connectivitycheck.gstatic.com/generate_204";
306
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700307 // TODO: create better separation between radio types and network types
308
Robert Greenwalt2034b912009-08-12 16:08:25 -0700309 // how long to wait before switching back to a radio's default network
310 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
311 // system property that can override the above value
312 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
313 "android.telephony.apn-restore";
314
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900315 // How long to wait before putting up a "This network doesn't have an Internet connection,
316 // connect anyway?" dialog after the user selects a network that doesn't validate.
317 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
318
junyulai0ac374f2020-12-14 18:41:52 +0800319 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900320 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
321 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800322 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700323
324 // The maximum number of network request allowed per uid before an exception is thrown.
325 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
326
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900327 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700328 @VisibleForTesting
329 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900330
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900331 @VisibleForTesting
332 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800333 @VisibleForTesting
334 protected int mNascentDelayMs;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900335
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800336 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800337 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800338 private final int mReleasePendingIntentDelayMs;
339
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900340 private MockableSystemProperties mSystemProperties;
341
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000342 @VisibleForTesting
343 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700344
Daniel Brightf9e945b2020-06-15 16:10:01 -0700345 private final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700346 @VisibleForTesting
347 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700348
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900349 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700350
junyulaif2c67e42018-08-07 19:50:45 +0800351 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000352 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
353 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800354 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000355 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800356
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900357 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900358 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000359 // The Context is created for UserHandle.ALL.
360 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900361 private final Dependencies mDeps;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700362 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700363 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800364
Chenbo Feng15416292018-11-08 17:36:21 -0800365 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800366 protected IDnsResolver mDnsResolver;
367 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800368 protected INetd mNetd;
junyulaie7c7d2a2021-01-26 15:29:15 +0800369 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800370 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800371 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700372
Benedict Wong493e04b2018-11-09 14:45:34 -0800373 /**
374 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
375 * instances.
376 */
377 @GuardedBy("mTNSLock")
378 private TestNetworkService mTNS;
379
380 private final Object mTNSLock = new Object();
381
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700382 private String mCurrentTcpBufferSizes;
383
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900384 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800385 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900386
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500387 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400388 // Tear down networks that have no chance (e.g. even if validated) of becoming
389 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500390 // all networks have been rematched against all NetworkRequests.
391 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400392 // Don't reap networks. This should be passed when some networks have not yet been
393 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500394 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900395 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500396
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900397 private enum UnneededFor {
398 LINGER, // Determine whether this network is unneeded and should be lingered.
399 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
400 }
401
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700402 /**
paulhue9913722021-05-26 15:19:20 +0800403 * The priority value is used when issue uid ranges rules to netd. Netd will use the priority
404 * value and uid ranges to generate corresponding ip rules specific to the given preference.
405 * Thus, any device originated data traffic of the applied uids can be routed to the altered
406 * default network which has highest priority.
407 *
408 * Note: The priority value should be in 0~1000. Larger value means lower priority, see
409 * {@link NativeUidRangeConfig}.
410 */
411 // This is default priority value for those NetworkRequests which doesn't have preference to
412 // alter default network and use the global one.
413 @VisibleForTesting
414 static final int DEFAULT_NETWORK_PRIORITY_NONE = 0;
415 // Used by automotive devices to set the network preferences used to direct traffic at an
416 // application level. See {@link #setOemNetworkPreference}.
417 @VisibleForTesting
418 static final int DEFAULT_NETWORK_PRIORITY_OEM = 10;
419 // Request that a user profile is put by default on a network matching a given preference.
420 // See {@link #setProfileNetworkPreference}.
421 @VisibleForTesting
422 static final int DEFAULT_NETWORK_PRIORITY_PROFILE = 20;
423 // Set by MOBILE_DATA_PREFERRED_UIDS setting. Use mobile data in preference even when
424 // higher-priority networks are connected.
425 @VisibleForTesting
426 static final int DEFAULT_NETWORK_PRIORITY_MOBILE_DATA_PREFERRED = 30;
427
428 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700429 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700430 * from one net to another. Clear happens when we get a new
431 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
432 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700433 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700434 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700435
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700436 /**
437 * used internally to reload global proxy settings
438 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700439 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700440
Robert Greenwalt34848c02011-03-25 13:09:25 -0700441 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400442 * PAC manager has received new port.
443 */
444 private static final int EVENT_PROXY_HAS_CHANGED = 16;
445
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700446 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900447 * used internally when registering NetworkProviders
448 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700449 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900450 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700451
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700452 /**
453 * used internally when registering NetworkAgents
454 * obj = Messenger
455 */
456 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
457
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700458 /**
459 * used to add a network request
460 * includes a NetworkRequestInfo
461 */
462 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
463
464 /**
465 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900466 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700467 * cancel it.
468 * includes a NetworkRequestInfo
469 */
470 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
471
472 /**
473 * used to add a network listener - no request
474 * includes a NetworkRequestInfo
475 */
476 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
477
478 /**
479 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400480 * arg1 = UID of caller
481 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700482 */
483 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
484
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700485 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900486 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700487 * obj = Messenger
488 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900489 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700490
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700491 /**
492 * used internally to expire a wakelock when transitioning
493 * from one net to another. Expire happens when we fail to find
494 * a new network (typically after 1 minute) -
495 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
496 * a replacement network.
497 */
498 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
499
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700500 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800501 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400502 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800503 */
504 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
505
506 /**
507 * used to remove a pending intent and its associated network request.
508 * arg1 = UID of caller
509 * obj = PendingIntent
510 */
511 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
512
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900513 /**
514 * used to specify whether a network should be used even if unvalidated.
515 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
516 * arg2 = whether to remember this choice in the future (1 or 0)
517 * obj = network
518 */
519 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
520
521 /**
522 * used to ask the user to confirm a connection to an unvalidated network.
523 * obj = network
524 */
525 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700526
Erik Kline05f2b402015-04-30 12:58:40 +0900527 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700528 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900529 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700530 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900531
Paul Jensenc8873fc2015-06-17 14:15:39 -0400532 /**
533 * used to add a network listener with a pending intent
534 * obj = NetworkRequestInfo
535 */
536 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
537
Hugo Benichid6b510a2017-04-06 17:22:18 +0900538 /**
539 * used to specify whether a network should not be penalized when it becomes unvalidated.
540 */
541 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
542
543 /**
544 * used to trigger revalidation of a network.
545 */
546 private static final int EVENT_REVALIDATE_NETWORK = 36;
547
Erik Kline31b4a9e2018-01-11 21:07:29 +0900548 // Handle changes in Private DNS settings.
549 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
550
dalyk1720e542018-03-05 12:42:22 -0500551 // Handle private DNS validation status updates.
552 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
553
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900554 /**
555 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
556 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800557 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
558 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
559 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900560 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900561 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900562
563 /**
564 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
565 * config was resolved.
566 * obj = PrivateDnsConfig
567 * arg2 = netid
568 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900569 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900570
571 /**
572 * Request ConnectivityService display provisioning notification.
573 * arg1 = Whether to make the notification visible.
574 * arg2 = NetID.
575 * obj = Intent to be launched when notification selected by user, null if !arg1.
576 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900577 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900578
579 /**
lucaslin2240ef62019-03-12 13:08:03 +0800580 * Used to specify whether a network should be used even if connectivity is partial.
581 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
582 * false)
583 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
584 * obj = network
585 */
lucaslin444d43a2020-02-20 16:56:59 +0800586 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800587
588 /**
lucasline117e2e2019-10-22 18:27:33 +0800589 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
590 * Both of the arguments are bitmasks, and the value of bits come from
591 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
592 * arg1 = A bitmask to describe which probes are completed.
593 * arg2 = A bitmask to describe which probes are successful.
594 */
lucaslin444d43a2020-02-20 16:56:59 +0800595 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800596
597 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900598 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
599 * arg1 = unused
600 * arg2 = netId
601 * obj = captive portal data
602 */
lucaslin444d43a2020-02-20 16:56:59 +0800603 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900604
605 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900606 * Used by setRequireVpnForUids.
607 * arg1 = whether the specified UID ranges are required to use a VPN.
608 * obj = Array of UidRange objects.
609 */
610 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
611
612 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900613 * Used internally when setting the default networks for OemNetworkPreferences.
614 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800615 */
616 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
617
618 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800619 * Used to indicate the system default network becomes active.
620 */
621 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
622
623 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900624 * Used internally when setting a network preference for a user profile.
625 * obj = Pair<ProfileNetworkPreference, Listener>
626 */
627 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
628
629 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000630 * Event to specify that reasons for why an uid is blocked changed.
631 * arg1 = uid
632 * arg2 = blockedReasons
633 */
634 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
635
636 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900637 * Event to register a new network offer
638 * obj = NetworkOffer
639 */
640 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
641
642 /**
643 * Event to unregister an existing network offer
644 * obj = INetworkOfferCallback
645 */
646 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
647
648 /**
paulhu51f77dc2021-06-07 02:34:20 +0000649 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
650 */
651 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
652
653 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800654 * Event to set temporary allow bad wifi within a limited time to override
655 * {@code config_networkAvoidBadWifi}.
656 */
657 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
658
659 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900660 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
661 * should be shown.
662 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900663 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900664
665 /**
666 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
667 * should be hidden.
668 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900669 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900670
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800671 /**
672 * The maximum alive time to allow bad wifi configuration for testing.
673 */
674 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
675
Hugo Benichi47011212017-03-30 10:46:05 +0900676 private static String eventName(int what) {
677 return sMagicDecoderRing.get(what, Integer.toString(what));
678 }
679
paulhua10d8212020-11-10 15:32:56 +0800680 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900681 final DnsResolverServiceManager dsm = context.getSystemService(
682 DnsResolverServiceManager.class);
683 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800684 }
685
Cody Kesting73708bf2019-12-18 10:57:50 -0800686 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900687 @VisibleForTesting
688 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700689 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700690 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700691 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700692 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800693 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
694 @VisibleForTesting
695 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
696
Erik Kline32120082017-12-13 19:40:49 +0900697 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900698 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700699
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400700 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800701 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400702
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700703 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800704 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700705
Chalard Jean5d70ba42018-06-07 16:44:04 +0900706 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
707 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000708 @VisibleForTesting
709 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400710
Erik Kline05f2b402015-04-30 12:58:40 +0900711 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700712
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400713 private UserManager mUserManager;
714
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700715 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900716 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700717
Valentin Iftime9fa35092019-09-24 13:32:13 +0200718 private Set<String> mWolSupportedInterfaces;
719
Roshan Pius08c94fb2020-01-16 12:17:17 -0800720 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800721 private final AppOpsManager mAppOpsManager;
722
723 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400724
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900725 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700726 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900727 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900728 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900729
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700730 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800731 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700732
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900733 // Sequence number for NetworkProvider IDs.
734 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
735 NetworkProvider.FIRST_PROVIDER_ID);
736
Erik Klineedf878b2015-07-09 18:24:03 +0900737 // NetworkRequest activity String log entries.
738 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
739 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
740
Hugo Benichid159fdd2016-07-11 11:05:12 +0900741 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900742 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900743 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
744
Hugo Benichi47011212017-03-30 10:46:05 +0900745 private static final int MAX_WAKELOCK_LOGS = 20;
746 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900747 private int mTotalWakelockAcquisitions = 0;
748 private int mTotalWakelockReleases = 0;
749 private long mTotalWakelockDurationMs = 0;
750 private long mMaxWakelockDurationMs = 0;
751 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900752
Hugo Benichi208c0102016-07-28 17:53:06 +0900753 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900754
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700755 @GuardedBy("mBandwidthRequests")
756 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
757
Erik Kline95ecfee2016-10-02 18:02:14 +0900758 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900759 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900760
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900761 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800762 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
763 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800764
Robert Greenwalt802c1102014-06-02 15:32:02 -0700765 /**
766 * Implements support for the legacy "one network per network type" model.
767 *
768 * We used to have a static array of NetworkStateTrackers, one for each
769 * network type, but that doesn't work any more now that we can have,
770 * for example, more that one wifi network. This class stores all the
771 * NetworkAgentInfo objects that support a given type, but the legacy
772 * API will only see the first one.
773 *
774 * It serves two main purposes:
775 *
776 * 1. Provide information about "the network for a given type" (since this
777 * API only supports one).
778 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
779 * the first network for a given type changes, or if the default network
780 * changes.
781 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900782 @VisibleForTesting
783 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900784
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900785 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900786 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900787
Robert Greenwalt802c1102014-06-02 15:32:02 -0700788 /**
789 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
790 * Each list holds references to all NetworkAgentInfos that are used to
791 * satisfy requests for that network type.
792 *
793 * This array is built out at startup such that an unsupported network
794 * doesn't get an ArrayList instance, making this a tristate:
795 * unsupported, supported but not active and active.
796 *
797 * The actual lists are populated when we scan the network types that
798 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900799 *
800 * Threading model:
801 * - addSupportedType() is only called in the constructor
802 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
803 * They are therefore not thread-safe with respect to each other.
804 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
805 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900806 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900807 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700808 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900809 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900810 @NonNull
811 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700812
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900813 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
814 // an entry have no timer (equivalent to -1). Lazily loaded.
815 @NonNull
816 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
817
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900818 LegacyTypeTracker(@NonNull ConnectivityService service) {
819 mService = service;
820 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700821 }
822
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900823 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
824 final PackageManager pm = ctx.getPackageManager();
825 if (pm.hasSystemFeature(FEATURE_WIFI)) {
826 addSupportedType(TYPE_WIFI);
827 }
828 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
829 addSupportedType(TYPE_WIFI_P2P);
830 }
831 if (tm.isDataCapable()) {
832 // Telephony does not have granular support for these types: they are either all
833 // supported, or none is supported
834 addSupportedType(TYPE_MOBILE);
835 addSupportedType(TYPE_MOBILE_MMS);
836 addSupportedType(TYPE_MOBILE_SUPL);
837 addSupportedType(TYPE_MOBILE_DUN);
838 addSupportedType(TYPE_MOBILE_HIPRI);
839 addSupportedType(TYPE_MOBILE_FOTA);
840 addSupportedType(TYPE_MOBILE_IMS);
841 addSupportedType(TYPE_MOBILE_CBS);
842 addSupportedType(TYPE_MOBILE_IA);
843 addSupportedType(TYPE_MOBILE_EMERGENCY);
844 }
845 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
846 addSupportedType(TYPE_BLUETOOTH);
847 }
848 if (pm.hasSystemFeature(FEATURE_WATCH)) {
849 // TYPE_PROXY is only used on Wear
850 addSupportedType(TYPE_PROXY);
851 }
852 // Ethernet is often not specified in the configs, although many devices can use it via
853 // USB host adapters. Add it as long as the ethernet service is here.
854 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
855 addSupportedType(TYPE_ETHERNET);
856 }
857
858 // Always add TYPE_VPN as a supported type
859 addSupportedType(TYPE_VPN);
860 }
861
862 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700863 if (mTypeLists[type] != null) {
864 throw new IllegalStateException(
865 "legacy list for type " + type + "already initialized");
866 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900867 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700868 }
869
Robert Greenwalt802c1102014-06-02 15:32:02 -0700870 public boolean isTypeSupported(int type) {
871 return isNetworkTypeValid(type) && mTypeLists[type] != null;
872 }
873
874 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900875 synchronized (mTypeLists) {
876 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
877 return mTypeLists[type].get(0);
878 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700879 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900880 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700881 }
882
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900883 public int getRestoreTimerForType(int type) {
884 synchronized (mTypeLists) {
885 if (mRestoreTimers == null) {
886 mRestoreTimers = loadRestoreTimers();
887 }
888 return mRestoreTimers.getOrDefault(type, -1);
889 }
890 }
891
892 private ArrayMap<Integer, Integer> loadRestoreTimers() {
893 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900894 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900895 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
896 for (final String config : configs) {
897 final String[] splits = TextUtils.split(config, ",");
898 if (splits.length != 2) {
899 logwtf("Invalid restore timer token count: " + config);
900 continue;
901 }
902 try {
903 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
904 } catch (NumberFormatException e) {
905 logwtf("Invalid restore timer number format: " + config, e);
906 }
907 }
908 return ret;
909 }
910
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700911 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900912 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900913 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900914 log("Sending " + state
915 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900916 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900917 }
918 }
919
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900920 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
921 // network type, to preserve previous behaviour.
922 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
923 if (vpnNai != mService.getLegacyLockdownNai()) return;
924
925 if (vpnNai.declaredUnderlyingNetworks == null
926 || vpnNai.declaredUnderlyingNetworks.length != 1) {
927 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
928 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
929 return;
930 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900931 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900932 vpnNai.declaredUnderlyingNetworks[0]);
933 if (underlyingNai == null) return;
934
935 final int type = underlyingNai.networkInfo.getType();
936 final DetailedState state = DetailedState.CONNECTED;
937 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
938 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
939 }
940
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900941 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700942 public void add(int type, NetworkAgentInfo nai) {
943 if (!isTypeSupported(type)) {
944 return; // Invalid network type.
945 }
946 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
947
948 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
949 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700950 return;
951 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900952 synchronized (mTypeLists) {
953 list.add(nai);
954 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +0900955
Chalard Jean5b409c72021-02-04 13:12:59 +0900956 // Send a broadcast if this is the first network of its type or if it's the default.
957 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900958
959 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
960 // to preserve previous behaviour.
961 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +0900962 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900963 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
964 mService.sendLegacyNetworkBroadcast(nai, state, type);
965 }
966
967 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
968 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -0700969 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700970 }
971
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900972 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +0900973 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900974 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
975 if (list == null || list.isEmpty()) {
976 return;
977 }
Lorenzo Colitti49767722015-05-01 00:30:10 +0900978 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900979
Hugo Benichi389633f2016-06-21 09:48:07 +0900980 synchronized (mTypeLists) {
981 if (!list.remove(nai)) {
982 return;
983 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900984 }
985
Lorenzo Colitti49767722015-05-01 00:30:10 +0900986 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +0900987 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
988 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900989 }
990
991 if (!list.isEmpty() && wasFirstNetwork) {
992 if (DBG) log("Other network available for type " + type +
993 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +0900994 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +0900995 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900996 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +0900997 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900998 }
999 }
1000
1001 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001002 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1003 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001004 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001005 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001006 }
1007 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001008
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001009 // send out another legacy broadcast - currently only used for suspend/unsuspend
1010 // toggle
1011 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001012 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001013 final DetailedState state = nai.networkInfo.getDetailedState();
1014 for (int type = 0; type < mTypeLists.length; type++) {
1015 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001016 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001017 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001018 if (isFirst || contains && isDefault) {
1019 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001020 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001021 }
1022 }
1023 }
1024
Robert Greenwalt94e22142014-07-30 16:31:24 -07001025 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001026 pw.println("mLegacyTypeTracker:");
1027 pw.increaseIndent();
1028 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001029 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001030 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001031 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001032 pw.println();
1033 pw.println("Current state:");
1034 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001035 synchronized (mTypeLists) {
1036 for (int type = 0; type < mTypeLists.length; type++) {
1037 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1038 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001039 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001040 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001041 }
1042 }
1043 pw.decreaseIndent();
1044 pw.decreaseIndent();
1045 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001046 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001047 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001048 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001049
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001050 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001051 /**
1052 * Helper class which parses out priority arguments and dumps sections according to their
1053 * priority. If priority arguments are omitted, function calls the legacy dump command.
1054 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001055 private class LocalPriorityDump {
1056 private static final String PRIORITY_ARG = "--dump-priority";
1057 private static final String PRIORITY_ARG_HIGH = "HIGH";
1058 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1059
1060 LocalPriorityDump() {}
1061
1062 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1063 doDump(fd, pw, new String[] {DIAG_ARG});
1064 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001065 }
1066
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001067 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1068 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001069 }
1070
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001071 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1072 if (args == null) {
1073 dumpNormal(fd, pw, args);
1074 return;
1075 }
1076
1077 String priority = null;
1078 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1079 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1080 argIndex++;
1081 priority = args[argIndex];
1082 }
1083 }
1084
1085 if (PRIORITY_ARG_HIGH.equals(priority)) {
1086 dumpHigh(fd, pw);
1087 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1088 dumpNormal(fd, pw, args);
1089 } else {
1090 // ConnectivityService publishes binder service using publishBinderService() with
1091 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001092 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1093 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001094 // TODO: Integrate into signal dump.
1095 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001096 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001097 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001098 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001099
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001100 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001101 * Keeps track of the number of requests made under different uids.
1102 */
1103 public static class PerUidCounter {
1104 private final int mMaxCountPerUid;
1105
1106 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001107 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001108 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001109 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001110
1111 /**
1112 * Constructor
1113 *
1114 * @param maxCountPerUid the maximum count per uid allowed
1115 */
1116 public PerUidCounter(final int maxCountPerUid) {
1117 mMaxCountPerUid = maxCountPerUid;
1118 }
1119
1120 /**
1121 * Increments the request count of the given uid. Throws an exception if the number
1122 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1123 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1124 *
1125 * @throws ServiceSpecificException with
1126 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1127 * the uid exceed the allowed number.
1128 *
1129 * @param uid the uid that the request was made under
1130 */
1131 public void incrementCountOrThrow(final int uid) {
1132 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001133 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001134 }
1135 }
1136
James Mattis20a4a8b2021-03-28 17:41:09 -07001137 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1138 final int newRequestCount =
1139 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1140 if (newRequestCount >= mMaxCountPerUid) {
1141 throw new ServiceSpecificException(
1142 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1143 }
1144 mUidToNetworkRequestCount.put(uid, newRequestCount);
1145 }
1146
Daniel Brightf9e945b2020-06-15 16:10:01 -07001147 /**
1148 * Decrements the request count of the given uid.
1149 *
1150 * @param uid the uid that the request was made under
1151 */
1152 public void decrementCount(final int uid) {
1153 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001154 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001155 }
1156 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001157
1158 private void decrementCount(final int uid, final int numToDecrement) {
1159 final int newRequestCount =
1160 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1161 if (newRequestCount < 0) {
1162 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1163 } else if (newRequestCount == 0) {
1164 mUidToNetworkRequestCount.delete(uid);
1165 } else {
1166 mUidToNetworkRequestCount.put(uid, newRequestCount);
1167 }
1168 }
1169
1170 /**
1171 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1172 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1173 * are used to create the new nris upon set. Therefore the request count limit can be
1174 * artificially hit. This method is used as a workaround for this particular case so that
1175 * the request counts are accounted for correctly.
1176 * @param uid the uid to adjust counts for
1177 * @param numOfNewRequests the new request count to account for
1178 * @param r the runnable to execute
1179 */
1180 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1181 // This should only be used on the handler thread as per all current and foreseen
1182 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1183 // no ref to the outer ConnectivityService.
1184 synchronized (mUidToNetworkRequestCount) {
1185 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1186 decrementCount(uid, reqCountOverage);
1187 r.run();
1188 incrementCountOrThrow(uid, reqCountOverage);
1189 }
1190 }
1191
1192 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1193 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1194 + numOfNewRequests;
1195 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1196 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1197 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001198 }
1199
1200 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001201 * Dependencies of ConnectivityService, for injection in tests.
1202 */
1203 @VisibleForTesting
1204 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001205 public int getCallingUid() {
1206 return Binder.getCallingUid();
1207 }
1208
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001209 /**
1210 * Get system properties to use in ConnectivityService.
1211 */
1212 public MockableSystemProperties getSystemProperties() {
1213 return new MockableSystemProperties();
1214 }
1215
1216 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001217 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1218 */
1219 public ConnectivityResources getResources(@NonNull Context ctx) {
1220 return new ConnectivityResources(ctx);
1221 }
1222
1223 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001224 * Create a HandlerThread to use in ConnectivityService.
1225 */
1226 public HandlerThread makeHandlerThread() {
1227 return new HandlerThread("ConnectivityServiceThread");
1228 }
1229
1230 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001231 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001232 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001233 public NetworkStackClientBase getNetworkStack() {
1234 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001235 }
1236
1237 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001238 * @see ProxyTracker
1239 */
1240 public ProxyTracker makeProxyTracker(@NonNull Context context,
1241 @NonNull Handler connServiceHandler) {
1242 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1243 }
1244
1245 /**
1246 * @see NetIdManager
1247 */
1248 public NetIdManager makeNetIdManager() {
1249 return new NetIdManager();
1250 }
1251
1252 /**
1253 * @see NetworkUtils#queryUserAccess(int, int)
1254 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001255 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1256 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001257 }
1258
1259 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001260 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1261 * requires CAP_NET_ADMIN, which the unit tests do not have.
1262 */
1263 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1264 InetSocketAddress remote) {
1265 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1266 }
1267
1268 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001269 * @see MultinetworkPolicyTracker
1270 */
1271 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1272 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1273 return new MultinetworkPolicyTracker(c, h, r);
1274 }
1275
Aaron Huang330a4c02020-10-27 03:36:19 +08001276 /**
1277 * @see BatteryStatsManager
1278 */
1279 public void reportNetworkInterfaceForTransports(Context context, String iface,
1280 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001281 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001282 context.getSystemService(BatteryStatsManager.class);
1283 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1284 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001285
1286 public boolean getCellular464XlatEnabled() {
1287 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1288 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001289
1290 /**
1291 * @see PendingIntent#intentFilterEquals
1292 */
1293 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1294 return a.intentFilterEquals(b);
1295 }
1296
1297 /**
1298 * @see LocationPermissionChecker
1299 */
1300 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1301 return new LocationPermissionChecker(context);
1302 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001303 }
1304
junyulaie7c7d2a2021-01-26 15:29:15 +08001305 public ConnectivityService(Context context) {
1306 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001307 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1308 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001309 }
1310
1311 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001312 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1313 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001314 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001315
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001316 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001317 mSystemProperties = mDeps.getSystemProperties();
1318 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001319 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001320 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001321 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001322 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001323
Hugo Benichi208c0102016-07-28 17:53:06 +09001324 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001325 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001326 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1327 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001328 Process.myUid(), defaultInternetRequest, null,
Roshan Pius951c0032020-12-22 15:10:42 -08001329 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001330 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001331 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1332 mDefaultNetworkRequests.add(mDefaultRequest);
1333 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001334
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001335 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001336 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001337
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001338 // The default WiFi request is a background request so that apps using WiFi are
1339 // migrated to a better network (typically ethernet) when one comes up, instead
1340 // of staying on WiFi forever.
1341 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1342 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1343
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001344 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1345 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1346 NetworkRequest.Type.BACKGROUND_REQUEST);
1347
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001348 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001349 mHandlerThread.start();
1350 mHandler = new InternalHandler(mHandlerThread.getLooper());
1351 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001352 mConnectivityDiagnosticsHandler =
1353 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001354
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001355 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001356 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001357
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001358 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
junyulai0ac374f2020-12-14 18:41:52 +08001359 // TODO: Consider making the timer customizable.
1360 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09001361
junyulaie7c7d2a2021-01-26 15:29:15 +08001362 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001363 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001364 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001365 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001366
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001367 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001368 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001369 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001370 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001371
Sudheer Shanka9967d462021-03-18 19:09:25 +00001372 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001373 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1374 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001375 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001376
1377 final PowerManager powerManager = (PowerManager) context.getSystemService(
1378 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001379 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001380 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001381
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001382 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1383 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001384 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001385 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001386 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001387 mProtectedNetworks.add(p);
1388 } else {
1389 if (DBG) loge("Ignoring protectedNetwork " + p);
1390 }
1391 }
1392
soma, kawata29444ae2019-05-23 09:30:40 +09001393 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1394
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001395 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001396
James Mattis02220e22021-03-13 19:27:21 -08001397 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001398 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001399 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001400 final IntentFilter userIntentFilter = new IntentFilter();
1401 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1402 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1403 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1404 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001405
James Mattis02220e22021-03-13 19:27:21 -08001406 // Listen to package add/removes for netd
1407 final IntentFilter packageIntentFilter = new IntentFilter();
1408 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1409 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1410 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1411 packageIntentFilter.addDataScheme("package");
1412 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001413 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001414
lucaslind5c2d072021-02-20 18:59:47 +08001415 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001416
lucaslin66f44212021-02-23 01:12:55 +08001417 mNetdCallback = new NetdCallback();
1418 try {
1419 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1420 } catch (RemoteException | ServiceSpecificException e) {
1421 loge("Error registering event listener :" + e);
1422 }
1423
Erik Kline05f2b402015-04-30 12:58:40 +09001424 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1425 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001426
junyulai7e06ad42019-03-04 22:45:36 +08001427 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001428 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001429 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001430
1431 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001432 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001433 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1434 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001435 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001436 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1437 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001438
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001439 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001440 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001441 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001442
Chiachang Wangc1215d32020-10-20 15:38:58 +08001443 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001444 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001445
Chalard Jean28018572020-12-21 18:36:52 +09001446 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1447 // request that doesn't allow fallback to the default network. It should never be visible
1448 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1449 // arguments like the handler or the DnsResolver.
1450 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001451 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001452 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001453 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001454 new LinkProperties(), new NetworkCapabilities(),
1455 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001456 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1457 mLingerDelayMs, mQosCallbackTracker, mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001458 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001459
Chalard Jean46adcf32018-04-18 20:18:38 +09001460 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001461 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1462 }
1463
1464 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1465 @NonNull final UidRange uids) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001466 final NetworkCapabilities netCap = new NetworkCapabilities();
1467 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001468 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001469 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Chiachang Wang8156c4e2021-03-19 00:45:39 +00001470 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
Chalard Jean46adcf32018-04-18 20:18:38 +09001471 return netCap;
1472 }
1473
James Mattis45d81842021-01-10 14:24:24 -08001474 private NetworkRequest createDefaultRequest() {
1475 return createDefaultInternetRequestForTransport(
1476 TYPE_NONE, NetworkRequest.Type.REQUEST);
1477 }
1478
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001479 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001480 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001481 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001482 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001483 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001484 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001485 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001486 netCap.addTransportType(transportType);
1487 }
James Mattis45d81842021-01-10 14:24:24 -08001488 return createNetworkRequest(type, netCap);
1489 }
1490
1491 private NetworkRequest createNetworkRequest(
1492 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001493 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001494 }
1495
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001496 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1497 NetworkRequest.Type type) {
1498 final NetworkCapabilities netCap = new NetworkCapabilities();
1499 netCap.clearAll();
1500 netCap.addCapability(capability);
1501 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1502 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1503 }
1504
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001505 // Used only for testing.
1506 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001507 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001508 // changing ContentResolver to make registerContentObserver non-final).
1509 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1510 // by subclassing SettingsObserver.
1511 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001512 void updateAlwaysOnNetworks() {
1513 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001514 }
1515
Erik Kline9a62f012018-03-21 07:18:33 -07001516 // See FakeSettingsProvider comment above.
1517 @VisibleForTesting
1518 void updatePrivateDnsSettings() {
1519 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1520 }
1521
paulhu51f77dc2021-06-07 02:34:20 +00001522 @VisibleForTesting
1523 void updateMobileDataPreferredUids() {
1524 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1525 }
1526
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001527 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001528 final boolean enable = mContext.getResources().getBoolean(id);
1529 handleAlwaysOnNetworkRequest(networkRequest, enable);
1530 }
1531
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001532 private void handleAlwaysOnNetworkRequest(
1533 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001534 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001535 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001536 handleAlwaysOnNetworkRequest(networkRequest, enable);
1537 }
1538
1539 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001540 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001541 if (enable == isEnabled) {
1542 return; // Nothing to do.
1543 }
1544
1545 if (enable) {
1546 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001547 Process.myUid(), networkRequest, null, new Binder(),
Roshan Pius951c0032020-12-22 15:10:42 -08001548 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001549 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001550 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001551 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1552 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001553 }
1554 }
1555
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001556 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001557 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1558 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1559 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1560 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001561 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1562 R.bool.config_vehicleInternalNetworkAlwaysRequested);
1563 // TODO (b/183076074): remove legacy fallback after migrating overlays
1564 final boolean legacyAlwaysRequested = mContext.getResources().getBoolean(
1565 mContext.getResources().getIdentifier(
1566 "config_vehicleInternalNetworkAlwaysRequested", "bool", "android"));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001567 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001568 vehicleAlwaysRequested || legacyAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001569 }
1570
paulhu51f77dc2021-06-07 02:34:20 +00001571 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001572 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001573 private void registerSettingsCallbacks() {
1574 // Watch for global HTTP proxy changes.
1575 mSettingsObserver.observe(
1576 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1577 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1578
1579 // Watch for whether or not to keep mobile data always on.
1580 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001581 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001582 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1583
1584 // Watch for whether or not to keep wifi always on.
1585 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001586 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001587 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001588
1589 // Watch for mobile data preferred uids changes.
1590 mSettingsObserver.observe(
1591 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1592 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001593 }
1594
Erik Kline31b4a9e2018-01-11 21:07:29 +09001595 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001596 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1597 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001598 }
1599 }
1600
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001601 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001602 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1603 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001604 return mNextNetworkRequestId++;
1605 }
1606
junyulai74f9a8b2018-06-13 15:00:37 +08001607 @VisibleForTesting
1608 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001609 if (network == null) {
1610 return null;
1611 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001612 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001613 }
1614
1615 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001616 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001617 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001618 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001619 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001620
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001621 // TODO: determine what to do when more than one VPN applies to |uid|.
1622 private NetworkAgentInfo getVpnForUid(int uid) {
1623 synchronized (mNetworkForNetId) {
1624 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1625 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1626 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1627 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001628 }
1629 }
1630 }
1631 return null;
1632 }
1633
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001634 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001635 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001636 final NetworkAgentInfo nai = getVpnForUid(uid);
1637 if (nai != null) return nai.declaredUnderlyingNetworks;
1638 return null;
1639 }
1640
Lorenzo Colittia7574052021-01-19 01:33:05 +09001641 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001642 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001643
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001644 final Network[] networks = getVpnUnderlyingNetworks(uid);
1645 if (networks != null) {
1646 // getUnderlyingNetworks() returns:
1647 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1648 // empty array => the VPN explicitly said "no default network".
1649 // non-empty array => the VPN specified one or more default networks; we use the
1650 // first one.
1651 if (networks.length > 0) {
1652 nai = getNetworkAgentInfoForNetwork(networks[0]);
1653 } else {
1654 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001655 }
1656 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001657 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001658 }
1659
1660 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001661 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001662 */
paulhu7aeba372020-12-30 00:42:19 +08001663 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1664 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001665 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001666 if (ignoreBlocked) {
1667 return false;
1668 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001669 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001670 final long ident = Binder.clearCallingIdentity();
1671 try {
1672 final boolean metered = nc == null ? true : nc.isMetered();
1673 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1674 } finally {
1675 Binder.restoreCallingIdentity(ident);
1676 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001677 }
1678
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001679 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001680 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1681 return;
1682 }
Hugo Benichi47011212017-03-30 10:46:05 +09001683 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001684 synchronized (mBlockedAppUids) {
1685 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001686 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001687 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001688 blocked = false;
1689 } else {
1690 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001691 }
1692 }
Hugo Benichi47011212017-03-30 10:46:05 +09001693 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1694 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1695 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001696 }
1697
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001698 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001699 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1700 return;
1701 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001702 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001703 final int requestId = nri.getActiveRequest() != null
1704 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001705 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001706 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001707 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001708 }
1709
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001710 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001711 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001712 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001713 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001714 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001715 @NonNull
1716 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1717 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001718 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1719 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1720 // but only exists if an app asks about them or requests them. Ensure the requesting app
1721 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001722 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001723 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1724 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1725 null /* extraInfo */);
1726 }
1727 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001728 return filtered;
1729 }
1730
1731 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1732 boolean ignoreBlocked) {
1733 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1734 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001735 }
1736
1737 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001738 * Return NetworkInfo for the active (i.e., connected) network interface.
1739 * It is assumed that at most one network is active at a time. If more
1740 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001741 * @return the info for the active network, or {@code null} if none is
1742 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001743 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001744 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001745 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001746 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001747 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001748 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1749 if (nai == null) return null;
1750 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1751 maybeLogBlockedNetworkInfo(networkInfo, uid);
1752 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001753 }
1754
Paul Jensen1f567382015-02-13 14:18:39 -05001755 @Override
1756 public Network getActiveNetwork() {
1757 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001758 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001759 }
1760
1761 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001762 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001763 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001764 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001765 }
1766
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001767 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001768 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1769 if (vpnNai != null) {
1770 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1771 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1772 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001773 }
Paul Jensen1f567382015-02-13 14:18:39 -05001774 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001775
James Mattis2516da32021-01-31 17:06:19 -08001776 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001777 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1778 ignoreBlocked)) {
1779 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001780 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001781 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001782 }
1783
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001784 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001785 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001786 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001787 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1788 if (nai == null) return null;
1789 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001790 }
1791
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001792 /** Returns a NetworkInfo object for a network that doesn't exist. */
1793 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1794 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1795 getNetworkTypeName(networkType), "" /* subtypeName */);
1796 info.setIsAvailable(true);
1797 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1798 // background data is restricted.
1799 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1800 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1801 ? DetailedState.BLOCKED
1802 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001803 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1804 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001805 return info;
1806 }
1807
Lorenzo Colittia7574052021-01-19 01:33:05 +09001808 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001809 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1810 return null;
1811 }
1812 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001813 if (nai == null) {
1814 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001815 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001816 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1817 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001818 }
1819
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001820 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001821 public NetworkInfo getNetworkInfo(int networkType) {
1822 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001823 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001824 if (getVpnUnderlyingNetworks(uid) != null) {
1825 // A VPN is active, so we may need to return one of its underlying networks. This
1826 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001827 // getNetworkAgentInfoForUid.
1828 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1829 if (nai == null) return null;
1830 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1831 if (networkInfo.getType() == networkType) {
1832 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001833 }
1834 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001835 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001836 }
1837
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001838 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001839 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001840 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001841 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001842 if (nai == null) return null;
1843 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001844 }
1845
1846 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001847 public NetworkInfo[] getAllNetworkInfo() {
1848 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001849 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001850 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1851 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001852 NetworkInfo info = getNetworkInfo(networkType);
1853 if (info != null) {
1854 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001855 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001856 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001857 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001858 }
1859
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001860 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001861 public Network getNetworkForType(int networkType) {
1862 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001863 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1864 return null;
1865 }
1866 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1867 if (nai == null) {
1868 return null;
1869 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001870 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001871 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1872 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001873 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001874 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001875 }
1876
1877 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001878 public Network[] getAllNetworks() {
1879 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001880 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001881 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001882 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001883 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001884 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001885 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001886 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001887 }
1888
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001889 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001890 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001891 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001892 // The basic principle is: if an app's traffic could possibly go over a
1893 // network, without the app doing anything multinetwork-specific,
1894 // (hence, by "default"), then include that network's capabilities in
1895 // the array.
1896 //
1897 // In the normal case, app traffic only goes over the system's default
1898 // network connection, so that's the only network returned.
1899 //
1900 // With a VPN in force, some app traffic may go into the VPN, and thus
1901 // over whatever underlying networks the VPN specifies, while other app
1902 // traffic may go over the system default network (e.g.: a split-tunnel
1903 // VPN, or an app disallowed by the VPN), so the set of networks
1904 // returned includes the VPN's underlying networks and the system
1905 // default.
1906 enforceAccessPermission();
1907
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001908 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001909
James Mattis2516da32021-01-31 17:06:19 -08001910 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1911 if (!nri.isBeingSatisfied()) {
1912 continue;
1913 }
1914 final NetworkAgentInfo nai = nri.getSatisfier();
1915 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1916 if (null != nc
1917 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1918 && !result.containsKey(nai.network)) {
1919 result.put(
1920 nai.network,
1921 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001922 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001923 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1924 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001925 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001926 }
1927
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001928 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001929 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001930 if (null != networks) {
1931 for (final Network network : networks) {
1932 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1933 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001934 result.put(
1935 network,
1936 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001937 nc,
1938 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001939 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001940 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001941 }
1942 }
1943 }
1944
1945 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1946 out = result.values().toArray(out);
1947 return out;
1948 }
1949
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001950 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001951 public boolean isNetworkSupported(int networkType) {
1952 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001953 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001954 }
1955
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001956 /**
1957 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08001958 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001959 * @return the ip properties for the active network, or {@code null} if
1960 * none is active
1961 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001962 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001963 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001964 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001965 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001966 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1967 if (nai == null) return null;
1968 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001969 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001970 }
1971
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001972 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001973 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001974 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001975 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001976 final LinkProperties lp = getLinkProperties(nai);
1977 if (lp == null) return null;
1978 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001979 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001980 }
1981
Robert Greenwaltbe46b752014-05-13 21:41:06 -07001982 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07001983 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001984 public LinkProperties getLinkProperties(Network network) {
1985 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001986 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1987 if (lp == null) return null;
1988 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001989 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09001990 }
1991
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001992 @Nullable
1993 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09001994 if (nai == null) {
1995 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001996 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09001997 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001998 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09001999 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002000 }
2001
Qingxi Lib2748102020-01-08 12:51:49 -08002002 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2003 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2004 }
2005
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002006 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002007 if (nai == null) return null;
2008 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002009 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002010 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002011 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002012 }
2013
2014 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002015 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2016 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002017 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002018 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002019 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002020 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002021 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002022 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002023 }
2024
Qingxi Libb8da982020-01-17 17:54:27 -08002025 @VisibleForTesting
2026 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002027 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002028 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002029 if (!checkSettingsPermission(callerPid, callerUid)) {
2030 newNc.setUids(null);
2031 newNc.setSSID(null);
2032 }
Etan Cohen107ae952018-12-30 17:59:59 -08002033 if (newNc.getNetworkSpecifier() != null) {
2034 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2035 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002036 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002037 if (!checkAnyPermissionOf(
2038 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08002039 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002040 }
Qingxi Libb8da982020-01-17 17:54:27 -08002041
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002042 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002043 }
2044
Roshan Pius98f59ec2021-02-23 08:47:39 -08002045 /**
2046 * Wrapper used to cache the permission check results performed for the corresponding
2047 * app. This avoid performing multiple permission checks for different fields in
2048 * NetworkCapabilities.
2049 * Note: This wrapper does not support any sort of invalidation and thus must not be
2050 * persistent or long-lived. It may only be used for the time necessary to
2051 * compute the redactions required by one particular NetworkCallback or
2052 * synchronous call.
2053 */
2054 private class RedactionPermissionChecker {
2055 private final int mCallingPid;
2056 private final int mCallingUid;
2057 @NonNull private final String mCallingPackageName;
2058 @Nullable private final String mCallingAttributionTag;
2059
2060 private Boolean mHasLocationPermission = null;
2061 private Boolean mHasLocalMacAddressPermission = null;
2062 private Boolean mHasSettingsPermission = null;
2063
2064 RedactionPermissionChecker(int callingPid, int callingUid,
2065 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2066 mCallingPid = callingPid;
2067 mCallingUid = callingUid;
2068 mCallingPackageName = callingPackageName;
2069 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002070 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002071
2072 private boolean hasLocationPermissionInternal() {
2073 final long token = Binder.clearCallingIdentity();
2074 try {
2075 return mLocationPermissionChecker.checkLocationPermission(
2076 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2077 null /* message */);
2078 } finally {
2079 Binder.restoreCallingIdentity(token);
2080 }
2081 }
2082
2083 /**
2084 * Returns whether the app holds location permission or not (might return cached result
2085 * if the permission was already checked before).
2086 */
2087 public boolean hasLocationPermission() {
2088 if (mHasLocationPermission == null) {
2089 // If there is no cached result, perform the check now.
2090 mHasLocationPermission = hasLocationPermissionInternal();
2091 }
2092 return mHasLocationPermission;
2093 }
2094
2095 /**
2096 * Returns whether the app holds local mac address permission or not (might return cached
2097 * result if the permission was already checked before).
2098 */
2099 public boolean hasLocalMacAddressPermission() {
2100 if (mHasLocalMacAddressPermission == null) {
2101 // If there is no cached result, perform the check now.
2102 mHasLocalMacAddressPermission =
2103 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2104 }
2105 return mHasLocalMacAddressPermission;
2106 }
2107
2108 /**
2109 * Returns whether the app holds settings permission or not (might return cached
2110 * result if the permission was already checked before).
2111 */
2112 public boolean hasSettingsPermission() {
2113 if (mHasSettingsPermission == null) {
2114 // If there is no cached result, perform the check now.
2115 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2116 }
2117 return mHasSettingsPermission;
2118 }
2119 }
2120
2121 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2122 @NetworkCapabilities.NetCapability long redaction) {
2123 return (redactions & redaction) != 0;
2124 }
2125
2126 /**
2127 * Use the provided |applicableRedactions| to check the receiving app's
2128 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2129 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2130 * before being sent to the corresponding app.
2131 */
2132 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2133 @NetworkCapabilities.RedactionType long applicableRedactions,
2134 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2135 boolean includeLocationSensitiveInfo) {
2136 long redactions = applicableRedactions;
2137 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2138 if (includeLocationSensitiveInfo
2139 && redactionPermissionChecker.hasLocationPermission()) {
2140 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2141 }
2142 }
2143 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2144 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2145 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2146 }
2147 }
2148 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2149 if (redactionPermissionChecker.hasSettingsPermission()) {
2150 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2151 }
2152 }
2153 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002154 }
2155
Qingxi Lib2748102020-01-08 12:51:49 -08002156 @VisibleForTesting
2157 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002158 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002159 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002160 int callingPid, int callingUid, @NonNull String callingPkgName,
2161 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002162 if (nc == null) {
2163 return null;
2164 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002165 // Avoid doing location permission check if the transport info has no location sensitive
2166 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002167 final RedactionPermissionChecker redactionPermissionChecker =
2168 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2169 callingAttributionTag);
2170 final long redactions = retrieveRequiredRedactions(
2171 nc.getApplicableRedactions(), redactionPermissionChecker,
2172 includeLocationSensitiveInfo);
2173 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002174 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002175 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002176 newNc.setOwnerUid(INVALID_UID);
2177 return newNc;
2178 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002179 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2180 if (nc.hasTransport(TRANSPORT_VPN)) {
2181 // Owner UIDs already checked above. No need to re-check.
2182 return newNc;
2183 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002184 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2185 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002186 // compatibility for older apps.
2187 if (!includeLocationSensitiveInfo
2188 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002189 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002190 newNc.setOwnerUid(INVALID_UID);
2191 return newNc;
2192 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002193 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002194 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002195 newNc.setOwnerUid(INVALID_UID);
2196 }
Qingxi Lib2748102020-01-08 12:51:49 -08002197 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002198 }
2199
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002200 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2201 LinkProperties lp, int callerPid, int callerUid) {
2202 if (lp == null) return new LinkProperties();
2203
2204 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2205 final boolean needsSanitization =
2206 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2207 if (!needsSanitization) {
2208 return new LinkProperties(lp);
2209 }
2210
2211 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002212 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002213 }
2214
2215 final LinkProperties newLp = new LinkProperties(lp);
2216 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2217 // object gets parceled.
2218 newLp.setCaptivePortalApiUrl(null);
2219 newLp.setCaptivePortalData(null);
2220 return newLp;
2221 }
2222
Roshan Pius08c94fb2020-01-16 12:17:17 -08002223 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2224 int callerUid, String callerPackageName) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09002225 if (!checkSettingsPermission()) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09002226 // There is no need to track the effective UID of the request here. If the caller lacks
2227 // the settings permission, the effective UID is the same as the calling ID.
Roshan Pius08c94fb2020-01-16 12:17:17 -08002228 nc.setSingleUid(callerUid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002229 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002230 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002231 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002232
2233 // Clear owner UID; this can never come from an app.
2234 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002235 }
2236
Chalard Jean38354d12018-03-20 19:13:57 +09002237 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002238 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002239 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2240 }
2241 }
2242
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002243 @Override
2244 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2245 enforceAccessPermission();
2246 final int callerUid = Binder.getCallingUid();
2247 final long token = Binder.clearCallingIdentity();
2248 try {
2249 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2250 } finally {
2251 Binder.restoreCallingIdentity(token);
2252 }
2253 }
2254
junyulaiebd15162021-03-03 12:09:05 +08002255 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002256 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002257 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002258 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002259 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002260
Serik Beketayev05130302021-01-15 16:47:25 -08002261 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002262 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002263 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2264 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002265 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002266 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002267 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002268 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2269 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002270 }
2271 }
2272 return result.toArray(new NetworkState[result.size()]);
2273 }
2274
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002275 @Override
junyulaiebd15162021-03-03 12:09:05 +08002276 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002277 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002278 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002279 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002280
2281 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2282 for (Network network : getAllNetworks()) {
2283 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2284 // TODO: Consider include SUSPENDED networks, which should be considered as
2285 // temporary shortage of connectivity of a connected network.
2286 if (nai != null && nai.networkInfo.isConnected()) {
2287 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2288 // NetworkCapabilities, which may contain UIDs of apps to which the
2289 // network applies. Should the UIDs be cleared so as not to leak or
2290 // interfere ?
2291 result.add(nai.getNetworkStateSnapshot());
2292 }
2293 }
2294 return result;
2295 }
2296
2297 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002298 public boolean isActiveNetworkMetered() {
2299 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002300
Qingxi Lib2748102020-01-08 12:51:49 -08002301 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002302 if (caps != null) {
2303 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2304 } else {
2305 // Always return the most conservative value
2306 return true;
2307 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002308 }
2309
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002310 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002311 * Ensures that the system cannot call a particular method.
2312 */
2313 private boolean disallowedBecauseSystemCaller() {
2314 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002315 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2316 // for devices launched with Q and above. However, existing devices upgrading to Q and
2317 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002318 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002319 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002320 log("This method exists only for app backwards compatibility"
2321 + " and must not be called by system services.");
2322 return true;
2323 }
2324 return false;
2325 }
2326
2327 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002328 * Ensure that a network route exists to deliver traffic to the specified
2329 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002330 * @param networkType the type of the network over which traffic to the
2331 * specified host is to be routed
2332 * @param hostAddress the IP address of the host to which the route is
2333 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002334 * @return {@code true} on success, {@code false} on failure
2335 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002336 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002337 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2338 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002339 if (disallowedBecauseSystemCaller()) {
2340 return false;
2341 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002342 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002343 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002344 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002345 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002346
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002347 InetAddress addr;
2348 try {
2349 addr = InetAddress.getByAddress(hostAddress);
2350 } catch (UnknownHostException e) {
2351 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2352 return false;
2353 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002354
The Android Open Source Project28527d22009-03-03 19:31:44 -08002355 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002356 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002357 return false;
2358 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002359
2360 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2361 if (nai == null) {
2362 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2363 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2364 } else {
2365 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2366 }
2367 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002368 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002369
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002370 DetailedState netState;
2371 synchronized (nai) {
2372 netState = nai.networkInfo.getDetailedState();
2373 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002374
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002375 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002376 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002377 log("requestRouteToHostAddress on down network "
2378 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002379 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002380 }
2381 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002382 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002383
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002384 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002385 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002386 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002387 LinkProperties lp;
2388 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002389 synchronized (nai) {
2390 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002391 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002392 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002393 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002394 if (DBG) {
2395 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2396 }
Wink Saville32506bc2013-06-29 21:10:57 -07002397 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002398 } finally {
2399 Binder.restoreCallingIdentity(token);
2400 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002401 }
2402
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002403 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002404 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002405 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002406 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002407 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002408 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002409 if (bestRoute.getGateway().equals(addr)) {
2410 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002411 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002412 } else {
2413 // if we will connect to this through another route, add a direct route
2414 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002415 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002416 }
2417 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002418 if (DBG) log("Adding legacy route " + bestRoute +
2419 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002420
2421 final String dst = bestRoute.getDestinationLinkAddress().toString();
2422 final String nextHop = bestRoute.hasGateway()
2423 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002424 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002425 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2426 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002427 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002428 return false;
2429 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002430 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002431 }
2432
paulhu7c0a2e62021-01-08 00:51:49 +08002433 class DnsResolverUnsolicitedEventCallback extends
2434 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002435 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002436 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002437 try {
2438 mHandler.sendMessage(mHandler.obtainMessage(
2439 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002440 new PrivateDnsValidationUpdate(event.netId,
2441 InetAddresses.parseNumericAddress(event.ipAddress),
2442 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002443 } catch (IllegalArgumentException e) {
2444 loge("Error parsing ip address in validation event");
2445 }
2446 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002447
2448 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002449 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2450 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002451 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2452 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2453 // event callback for certain nai. e.g. cellular. Register here to pass to
2454 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002455 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2456 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2457 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002458 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002459 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002460 }
2461 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002462
2463 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002464 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2465 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2466 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002467 }
dalyk1720e542018-03-05 12:42:22 -05002468
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002469 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002470 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002471 return this.VERSION;
2472 }
2473
2474 @Override
2475 public String getInterfaceHash() {
2476 return this.HASH;
2477 }
paulhu7c0a2e62021-01-08 00:51:49 +08002478 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002479
2480 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002481 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2482 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002483
paulhu7c0a2e62021-01-08 00:51:49 +08002484 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002485 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002486 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002487 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002488 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002489 }
2490 }
2491
Sudheer Shanka9967d462021-03-18 19:09:25 +00002492 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002493 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002494 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002495 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2496 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002497 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002498 };
2499
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002500 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002501 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002502 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002503 }
2504
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002505 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002506 for (String permission : permissions) {
2507 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002508 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002509 }
2510 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002511 return false;
2512 }
2513
paulhu1a407652019-03-22 16:35:06 +08002514 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2515 for (String permission : permissions) {
2516 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2517 return true;
2518 }
2519 }
2520 return false;
2521 }
2522
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002523 private void enforceAnyPermissionOf(String... permissions) {
2524 if (!checkAnyPermissionOf(permissions)) {
2525 throw new SecurityException("Requires one of the following permissions: "
2526 + String.join(", ", permissions) + ".");
2527 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002528 }
2529
Paul Jensen83f5d572014-08-29 09:54:01 -04002530 private void enforceInternetPermission() {
2531 mContext.enforceCallingOrSelfPermission(
2532 android.Manifest.permission.INTERNET,
2533 "ConnectivityService");
2534 }
2535
The Android Open Source Project28527d22009-03-03 19:31:44 -08002536 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002537 mContext.enforceCallingOrSelfPermission(
2538 android.Manifest.permission.ACCESS_NETWORK_STATE,
2539 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002540 }
2541
paulhua6ee2122021-02-22 15:40:43 +08002542 /**
2543 * Performs a strict and comprehensive check of whether a calling package is allowed to
2544 * change the state of network, as the condition differs for pre-M, M+, and
2545 * privileged/preinstalled apps. The caller is expected to have either the
2546 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2547 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2548 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2549 * permission and cannot be revoked. See http://b/23597341
2550 *
2551 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2552 * of this app will be updated to the current time.
2553 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002554 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002555 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2556 == PackageManager.PERMISSION_GRANTED) {
2557 return;
2558 }
2559
2560 if (callingPkg == null) {
2561 throw new SecurityException("Calling package name is null.");
2562 }
2563
2564 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2565 final int uid = mDeps.getCallingUid();
2566 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2567 callingPkg, callingAttributionTag, null /* message */);
2568
2569 if (mode == AppOpsManager.MODE_ALLOWED) {
2570 return;
2571 }
2572
2573 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2574 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2575 return;
2576 }
2577
2578 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2579 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2580 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002581 }
2582
Charles He9369e612017-05-15 17:07:18 +01002583 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002584 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002585 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002586 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002587 }
2588
paulhu8e96a752019-08-12 16:25:11 +08002589 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002590 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002591 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002592 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002593 }
2594
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002595 private void enforceNetworkFactoryOrSettingsPermission() {
2596 enforceAnyPermissionOf(
2597 android.Manifest.permission.NETWORK_SETTINGS,
2598 android.Manifest.permission.NETWORK_FACTORY,
2599 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2600 }
2601
2602 private void enforceNetworkFactoryOrTestNetworksPermission() {
2603 enforceAnyPermissionOf(
2604 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2605 android.Manifest.permission.NETWORK_FACTORY,
2606 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2607 }
2608
Chalard Jean9a396cc2018-02-21 18:43:54 +09002609 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002610 return checkAnyPermissionOf(
2611 android.Manifest.permission.NETWORK_SETTINGS,
2612 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002613 }
2614
2615 private boolean checkSettingsPermission(int pid, int uid) {
2616 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002617 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2618 || PERMISSION_GRANTED == mContext.checkPermission(
2619 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002620 }
2621
paulhu8e96a752019-08-12 16:25:11 +08002622 private void enforceNetworkStackOrSettingsPermission() {
2623 enforceAnyPermissionOf(
2624 android.Manifest.permission.NETWORK_SETTINGS,
2625 android.Manifest.permission.NETWORK_STACK,
2626 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2627 }
2628
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002629 private void enforceNetworkStackSettingsOrSetup() {
2630 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002631 android.Manifest.permission.NETWORK_SETTINGS,
2632 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002633 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002634 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002635 }
2636
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002637 private void enforceAirplaneModePermission() {
2638 enforceAnyPermissionOf(
2639 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2640 android.Manifest.permission.NETWORK_SETTINGS,
2641 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2642 android.Manifest.permission.NETWORK_STACK,
2643 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2644 }
2645
James Mattis8378aec2021-01-26 14:05:36 -08002646 private void enforceOemNetworkPreferencesPermission() {
2647 mContext.enforceCallingOrSelfPermission(
2648 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2649 "ConnectivityService");
2650 }
2651
James Mattisfa270db2021-05-31 17:11:10 -07002652 private void enforceManageTestNetworksPermission() {
2653 mContext.enforceCallingOrSelfPermission(
2654 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2655 "ConnectivityService");
2656 }
2657
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002658 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002659 return checkAnyPermissionOf(
2660 android.Manifest.permission.NETWORK_STACK,
2661 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002662 }
2663
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002664 private boolean checkNetworkStackPermission(int pid, int uid) {
2665 return checkAnyPermissionOf(pid, uid,
2666 android.Manifest.permission.NETWORK_STACK,
2667 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2668 }
2669
paulhu1a407652019-03-22 16:35:06 +08002670 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2671 return checkAnyPermissionOf(pid, uid,
2672 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002673 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2674 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002675 }
2676
Hugo Benichibd0cc762016-07-19 15:59:27 +09002677 private void enforceConnectivityRestrictedNetworksPermission() {
2678 try {
2679 mContext.enforceCallingOrSelfPermission(
2680 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2681 "ConnectivityService");
2682 return;
2683 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002684 // TODO: Remove this fallback check after all apps have declared
2685 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2686 mContext.enforceCallingOrSelfPermission(
2687 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2688 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002689 }
2690
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002691 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002692 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002693 }
2694
Roshan Pius98f59ec2021-02-23 08:47:39 -08002695 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2696 return PERMISSION_GRANTED == mContext.checkPermission(
2697 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2698 }
2699
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002700 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002701 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002702 }
2703
2704 private void sendInetConditionBroadcast(NetworkInfo info) {
2705 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2706 }
2707
Wink Saville4f0de1e2011-08-04 15:01:58 -07002708 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002709 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002710 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002711 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002712 if (info.isFailover()) {
2713 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2714 info.setFailover(false);
2715 }
2716 if (info.getReason() != null) {
2717 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2718 }
2719 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002720 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2721 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002722 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002723 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002724 return intent;
2725 }
2726
2727 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2728 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2729 }
2730
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002731 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002732 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002733 if (!mSystemReady
2734 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002735 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002736 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002737 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002738 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002739 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002740 }
2741
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002742 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002743 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002744 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002745 final NetworkInfo ni = intent.getParcelableExtra(
2746 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002747 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2748 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2749 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002750 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002751 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002752 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002753 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002754 } finally {
2755 Binder.restoreCallingIdentity(ident);
2756 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002757 }
2758 }
2759
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002760 /**
Aaron Huang96011892020-06-27 07:18:23 +08002761 * Called by SystemServer through ConnectivityManager when the system is ready.
2762 */
2763 @Override
2764 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002765 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002766 throw new SecurityException("Calling Uid is not system uid.");
2767 }
2768 systemReadyInternal();
2769 }
2770
2771 /**
2772 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002773 */
2774 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002775 public void systemReadyInternal() {
Aaron Huang9a57acf2020-12-08 10:03:29 +08002776 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2777 // listening network request which is sent by MultipathPolicyTracker won't be added
2778 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2779 // be called after PermissionMonitor#startMonitoring().
2780 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2781 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2782 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002783 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002784 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002785 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002786
Hugo Benichie5220992017-04-26 14:53:28 +09002787 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002788 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002789 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002790 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002791 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002792 }
2793 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002794
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002795 // Create network requests for always-on networks.
2796 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002797
2798 // Update mobile data preference if necessary.
2799 // Note that empty uid list can be skip here only because no uid rules applied before system
2800 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2801 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2802 updateMobileDataPreferredUids();
2803 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002804 }
2805
The Android Open Source Project28527d22009-03-03 19:31:44 -08002806 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002807 * Start listening for default data network activity state changes.
2808 */
2809 @Override
2810 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002811 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002812 }
2813
2814 /**
2815 * Stop listening for default data network activity state changes.
2816 */
2817 @Override
2818 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002819 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002820 }
2821
2822 /**
2823 * Check whether the default network radio is currently active.
2824 */
2825 @Override
2826 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002827 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002828 }
2829
2830 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002831 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002832 * and set it on it's iface.
2833 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002834 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2835 final String iface = newLp.getInterfaceName();
2836 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002837 if (oldLp == null && mtu == 0) {
2838 // Silently ignore unset MTU value.
2839 return;
2840 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002841 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2842 if (VDBG) log("identical MTU - not setting");
2843 return;
2844 }
paulhucbbc3db2019-03-08 16:35:20 +08002845 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002846 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002847 return;
2848 }
sy.yun4aa73922013-09-02 05:24:09 +09002849
w19976e714f1d2014-08-05 15:18:11 -07002850 // Cannot set MTU without interface name
2851 if (TextUtils.isEmpty(iface)) {
2852 loge("Setting MTU size with null iface.");
2853 return;
2854 }
2855
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002856 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002857 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002858 mNetd.interfaceSetMtu(iface, mtu);
2859 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002860 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002861 }
2862 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002863
Chenbo Feng15416292018-11-08 17:36:21 -08002864 @VisibleForTesting
2865 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002866
lucaslin821c9782018-11-28 19:27:52 +08002867 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002868 String[] values = null;
2869 if (tcpBufferSizes != null) {
2870 values = tcpBufferSizes.split(",");
2871 }
2872
2873 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002874 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002875 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2876 values = tcpBufferSizes.split(",");
2877 }
2878
2879 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2880
2881 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002882 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002883
Chenbo Feng15416292018-11-08 17:36:21 -08002884 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2885 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2886 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002887 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002888 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002889 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002890 }
2891 }
2892
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002893 @Override
2894 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002895 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002896 NETWORK_RESTORE_DELAY_PROP_NAME);
2897 if(restoreDefaultNetworkDelayStr != null &&
2898 restoreDefaultNetworkDelayStr.length() != 0) {
2899 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002900 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002901 } catch (NumberFormatException e) {
2902 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002903 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002904 // if the system property isn't set, use the value for the apn type
2905 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2906
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002907 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2908 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002909 }
2910 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002911 }
2912
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002913 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2914 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2915 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09002916 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08002917 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002918 // Start gathering diagnostic information.
2919 netDiags.add(new NetworkDiagnostics(
2920 nai.network,
2921 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08002922 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002923 DIAG_TIME_MS));
2924 }
2925
2926 for (NetworkDiagnostics netDiag : netDiags) {
2927 pw.println();
2928 netDiag.waitForMeasurements();
2929 netDiag.dump(pw);
2930 }
2931 }
2932
The Android Open Source Project28527d22009-03-03 19:31:44 -08002933 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09002934 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2935 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08002936 if (!checkDumpPermission(mContext, TAG, writer)) return;
2937
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08002938 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07002939 }
2940
lucaslin99473f62020-12-10 15:10:54 +08002941 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2942 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2943 != PackageManager.PERMISSION_GRANTED) {
2944 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002945 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08002946 + " due to missing android.permission.DUMP permission");
2947 return false;
2948 } else {
2949 return true;
2950 }
2951 }
2952
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08002953 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002954 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002955
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002956 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002957 dumpNetworkDiagnostics(pw);
2958 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002959 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002960 dumpNetworks(pw);
2961 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09002962 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002963 dumpNetworkRequests(pw);
2964 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002965 }
Erik Kline9647f382015-06-05 17:47:34 +09002966
Lorenzo Colittia86fae72020-01-10 00:40:28 +09002967 pw.print("NetworkProviders for:");
2968 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2969 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07002970 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09002971 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07002972 pw.println();
2973
Chalard Jean5b409c72021-02-04 13:12:59 +09002974 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002975 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09002976 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002977 pw.println("none");
2978 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09002979 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002980 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08002981 pw.println();
2982
James Mattis45d81842021-01-10 14:24:24 -08002983 pw.print("Current per-app default networks: ");
2984 pw.increaseIndent();
2985 dumpPerAppNetworkPreferences(pw);
2986 pw.decreaseIndent();
2987 pw.println();
2988
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002989 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002990 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09002991 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002992 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07002993 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002994
junyulaif2c67e42018-08-07 19:50:45 +08002995 pw.println("Status for known UIDs:");
2996 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00002997 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08002998 for (int i = 0; i < size; i++) {
2999 // Don't crash if the array is modified while dumping in bugreports.
3000 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003001 final int uid = mUidBlockedReasons.keyAt(i);
3002 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3003 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003004 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003005 } catch (ArrayIndexOutOfBoundsException e) {
3006 pw.println(" ArrayIndexOutOfBoundsException");
3007 } catch (ConcurrentModificationException e) {
3008 pw.println(" ConcurrentModificationException");
3009 }
3010 }
3011 pw.println();
3012 pw.decreaseIndent();
3013
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003014 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003015 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003016 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003017 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003018 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003019
Robert Greenwalt94e22142014-07-30 16:31:24 -07003020 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003021
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003022 pw.println();
markchien5e866652019-09-30 14:40:57 +08003023 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003024
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003025 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003026 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003027
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003028 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003029
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003030 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003031 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003032 pw.println("mNetworkRequestInfoLogs (most recent first):");
3033 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003034 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003035 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003036
3037 pw.println();
3038 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3039 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003040 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003041 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003042
3043 pw.println();
3044 pw.println("NetTransition WakeLock activity (most recent first):");
3045 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003046 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3047 pw.println("total releases: " + mTotalWakelockReleases);
3048 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3049 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3050 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3051 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3052 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3053 }
James Mattiscb1e0362021-04-06 17:07:42 -07003054 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003055
3056 pw.println();
3057 pw.println("bandwidth update requests (by uid):");
3058 pw.increaseIndent();
3059 synchronized (mBandwidthRequests) {
3060 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3061 pw.println("[" + mBandwidthRequests.keyAt(i)
3062 + "]: " + mBandwidthRequests.valueAt(i));
3063 }
3064 }
3065 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003066 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003067
James Mattiscb1e0362021-04-06 17:07:42 -07003068 pw.println();
3069 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3070 pw.increaseIndent();
3071 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003072 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003073 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003074
3075 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003076
3077 pw.println();
3078 pw.println("Permission Monitor:");
3079 pw.increaseIndent();
3080 mPermissionMonitor.dump(pw);
3081 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003082
3083 pw.println();
3084 pw.println("Legacy network activity:");
3085 pw.increaseIndent();
3086 mNetworkActivityTracker.dump(pw);
3087 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003088 }
3089
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003090 private void dumpNetworks(IndentingPrintWriter pw) {
3091 for (NetworkAgentInfo nai : networksSortedById()) {
3092 pw.println(nai.toString());
3093 pw.increaseIndent();
3094 pw.println(String.format(
3095 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3096 nai.numForegroundNetworkRequests(),
3097 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3098 nai.numBackgroundNetworkRequests(),
3099 nai.numNetworkRequests()));
3100 pw.increaseIndent();
3101 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3102 pw.println(nai.requestAt(i).toString());
3103 }
3104 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003105 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003106 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003107 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003108 pw.decreaseIndent();
3109 pw.decreaseIndent();
3110 }
3111 }
3112
James Mattis45d81842021-01-10 14:24:24 -08003113 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3114 pw.println("Per-App Network Preference:");
3115 pw.increaseIndent();
3116 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3117 pw.println("none");
3118 } else {
3119 pw.println(mOemNetworkPreferences.toString());
3120 }
3121 pw.decreaseIndent();
3122
3123 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3124 if (mDefaultRequest == defaultRequest) {
3125 continue;
3126 }
3127
3128 final boolean isActive = null != defaultRequest.getSatisfier();
3129 pw.println("Is per-app network active:");
3130 pw.increaseIndent();
3131 pw.println(isActive);
3132 if (isActive) {
3133 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3134 }
3135 pw.println("Tracked UIDs:");
3136 pw.increaseIndent();
3137 if (0 == defaultRequest.mRequests.size()) {
3138 pw.println("none, this should never occur.");
3139 } else {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00003140 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
James Mattis45d81842021-01-10 14:24:24 -08003141 }
3142 pw.decreaseIndent();
3143 pw.decreaseIndent();
3144 }
3145 }
3146
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003147 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3148 for (NetworkRequestInfo nri : requestsSortedById()) {
3149 pw.println(nri.toString());
3150 }
3151 }
3152
Hugo Benichia480ba52018-09-03 08:19:02 +09003153 /**
3154 * Return an array of all current NetworkAgentInfos sorted by network id.
3155 */
3156 private NetworkAgentInfo[] networksSortedById() {
3157 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003158 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003159 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003160 return networks;
3161 }
3162
3163 /**
3164 * Return an array of all current NetworkRequest sorted by request id.
3165 */
James Mattis258ea3c2020-11-15 15:04:40 -08003166 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003167 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003168 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003169 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003170 // Sort the array based off the NRI containing the min requestId in its requests.
3171 Arrays.sort(requests,
3172 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3173 Comparator.comparingInt(req -> req.requestId)).requestId
3174 )
3175 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003176 return requests;
3177 }
3178
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003179 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003180 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003181 if (officialNai != null && officialNai.equals(nai)) return true;
3182 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003183 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003184 " - " + nai);
3185 }
3186 return false;
3187 }
3188
Robert Greenwalt2034b912009-08-12 16:08:25 -07003189 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003190 private class NetworkStateTrackerHandler extends Handler {
3191 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003192 super(looper);
3193 }
3194
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003195 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003196 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3197 final NetworkAgentInfo nai = arg.first;
3198 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003199 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003200 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003201 }
3202 return;
3203 }
3204
3205 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003206 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003207 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003208 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003209 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003210 }
Chalard Jean5b639762020-03-09 21:25:37 +09003211 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3212 // Make sure the original object is not mutated. NetworkAgent normally
3213 // makes a copy of the capabilities when sending the message through
3214 // the Messenger, but if this ever changes, not making a defensive copy
3215 // here will give attack vectors to clients using this code path.
3216 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Cody Kestingfc7cad32020-04-07 16:07:33 -07003217 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003218 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003219 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003220 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003221 break;
3222 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003223 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003224 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003225 processLinkPropertiesFromAgent(nai, newLp);
3226 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003227 break;
3228 }
3229 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003230 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003231 updateNetworkInfo(nai, info);
3232 break;
3233 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003234 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003235 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003236 break;
3237 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003238 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003239 if (nai.everConnected) {
3240 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003241 // Note that if the NAI had been connected, this would affect the
3242 // score, and therefore would require re-mixing the score and performing
3243 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003244 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003245 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3246 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003247 // Mark the network as temporarily accepting partial connectivity so that it
3248 // will be validated (and possibly become default) even if it only provides
3249 // partial internet access. Note that if user connects to partial connectivity
3250 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3251 // out of wifi coverage) and if the same wifi is available again, the device
3252 // will auto connect to this wifi even though the wifi has "no internet".
3253 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003254 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003255 break;
3256 }
junyulai011b1f12019-01-03 18:50:15 +08003257 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003258 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003259 break;
3260 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003261 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003262 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003263 if (!nai.supportsUnderlyingNetworks()) {
3264 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3265 break;
3266 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003267
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003268 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003269
3270 if (isLegacyLockdownNai(nai)
3271 && (underlying == null || underlying.size() != 1)) {
3272 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3273 + " must have exactly one underlying network: " + underlying);
3274 }
3275
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003276 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3277 nai.declaredUnderlyingNetworks = (underlying != null)
3278 ? underlying.toArray(new Network[0]) : null;
3279
3280 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3281 if (DBG) {
3282 log(nai.toShortString() + " changed underlying networks to "
3283 + Arrays.toString(nai.declaredUnderlyingNetworks));
3284 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003285 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003286 notifyIfacesChangedForNetworkStats();
3287 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003288 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003289 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003290 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3291 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3292 nai.teardownDelayMs = msg.arg1;
3293 } else {
3294 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3295 }
Chalard Jean550b5212021-03-05 23:07:53 +09003296 break;
3297 }
3298 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3299 nai.setLingerDuration((int) arg.second);
3300 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003301 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003302 }
3303 }
3304
3305 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3306 switch (msg.what) {
3307 default:
3308 return false;
lucasline117e2e2019-10-22 18:27:33 +08003309 case EVENT_PROBE_STATUS_CHANGED: {
3310 final Integer netId = (Integer) msg.obj;
3311 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3312 if (nai == null) {
3313 break;
3314 }
3315 final boolean probePrivateDnsCompleted =
3316 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3317 final boolean privateDnsBroken =
3318 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3319 if (probePrivateDnsCompleted) {
3320 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3321 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003322 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003323 }
3324 // Only show the notification when the private DNS is broken and the
3325 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003326 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003327 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3328 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003329 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003330 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3331 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3332 // private DNS is broken, it means this network is being reevaluated.
3333 // Either probing private DNS is not necessary any more or it hasn't been
3334 // done yet. In either case, the networkCapabilities should be updated to
3335 // reflect the new status.
3336 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003337 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003338 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003339 }
3340 break;
3341 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003342 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003343 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3344
3345 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003346 if (nai == null) break;
3347
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003348 handleNetworkTested(nai, results.mTestResult,
3349 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003350 break;
3351 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003352 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003353 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003354 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003355 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003356 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003357 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3358 nai.lastCaptivePortalDetected = visible;
3359 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003360 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003361 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3362 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003363 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003364 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003365 teardownUnneededNetwork(nai);
3366 break;
3367 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003368 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003369 }
3370 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003371 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003372 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003373 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3374 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003375 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003376 if (nai == null) {
3377 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3378 break;
3379 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003380 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003381 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003382 (PendingIntent) msg.obj,
3383 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003384 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003385 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003386 break;
3387 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003388 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003389 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003390 if (nai == null) break;
3391
Erik Kline9a62f012018-03-21 07:18:33 -07003392 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003393 break;
3394 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003395 case EVENT_CAPPORT_DATA_CHANGED: {
3396 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3397 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003398 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003399 break;
3400 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003401 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003402 return true;
3403 }
3404
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003405 private void handleNetworkTested(
3406 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3407 final boolean wasPartial = nai.partialConnectivity;
3408 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3409 final boolean partialConnectivityChanged =
3410 (wasPartial != nai.partialConnectivity);
3411
3412 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3413 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003414 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003415
3416 if (DBG) {
3417 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3418 ? " with redirect to " + redirectUrl
3419 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003420 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003421 }
3422 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003423 final int oldScore = nai.getCurrentScore();
3424 nai.lastValidated = valid;
3425 nai.everValidated |= valid;
3426 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003427 if (valid) {
3428 handleFreshlyValidatedNetwork(nai);
3429 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3430 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003431 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003432 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003433 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003434 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003435 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003436 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003437 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003438 NotificationType.PRIVATE_DNS_BROKEN);
3439 // If network becomes valid, the hasShownBroken should be reset for
3440 // that network so that the notification will be fired when the private
3441 // DNS is broken again.
3442 nai.networkAgentConfig.hasShownBroken = false;
3443 }
3444 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003445 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003446 }
3447 updateInetCondition(nai);
3448 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003449 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003450 nai.onValidationStatusChanged(
3451 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3452 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003453
3454 // If NetworkMonitor detects partial connectivity before
3455 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3456 // immediately. Re-notify partial connectivity silently if no internet
3457 // notification already there.
3458 if (!wasPartial && nai.partialConnectivity) {
3459 // Remove delayed message if there is a pending message.
3460 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3461 handlePromptUnvalidated(nai.network);
3462 }
3463
3464 if (wasValidated && !nai.lastValidated) {
3465 handleNetworkUnvalidated(nai);
3466 }
3467 }
3468
Calvin Ondada1452016-10-11 15:10:46 -07003469 private int getCaptivePortalMode() {
3470 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003471 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3472 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003473 }
3474
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003475 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3476 switch (msg.what) {
3477 default:
3478 return false;
3479 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3480 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3481 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3482 handleLingerComplete(nai);
3483 }
3484 break;
3485 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003486 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3487 handleNetworkAgentRegistered(msg);
3488 break;
3489 }
3490 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3491 handleNetworkAgentDisconnected(msg);
3492 break;
3493 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003494 }
3495 return true;
3496 }
3497
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003498 @Override
3499 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003500 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003501 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003502 maybeHandleNetworkAgentMessage(msg);
3503 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003504 }
3505 }
3506
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003507 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003508 private final int mNetId;
3509 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003510
3511 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003512 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003513 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003514 }
3515
3516 @Override
3517 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3518 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003519 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003520 }
3521
3522 @Override
3523 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003524 // Legacy version of notifyNetworkTestedWithExtras.
3525 // Would only be called if the system has a NetworkStack module older than the
3526 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003527 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003528 }
3529
3530 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003531 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003532 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3533 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003534 final Message msg = mTrackerHandler.obtainMessage(
3535 EVENT_NETWORK_TESTED,
3536 new NetworkTestedResults(
3537 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003538 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003539
3540 // Invoke ConnectivityReport generation for this Network test event.
3541 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3542 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003543
3544 final PersistableBundle extras = new PersistableBundle();
3545 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3546 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3547 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3548
Aaron Huang959d3642021-01-21 15:47:41 +08003549 ConnectivityReportEvent reportEvent =
3550 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3551 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3552 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003553 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003554 }
3555
3556 @Override
3557 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3558 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3559 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003560 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003561 }
3562
3563 @Override
lucasline117e2e2019-10-22 18:27:33 +08003564 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3565 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3566 EVENT_PROBE_STATUS_CHANGED,
3567 probesCompleted, probesSucceeded, new Integer(mNetId)));
3568 }
3569
3570 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003571 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3572 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3573 EVENT_CAPPORT_DATA_CHANGED,
3574 0, mNetId, data));
3575 }
3576
3577 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003578 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003579 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003580 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003581
3582 final PendingIntent pendingIntent;
3583 // Only the system server can register notifications with package "android"
3584 final long token = Binder.clearCallingIdentity();
3585 try {
paulhu7746e4e2020-06-09 19:07:03 +08003586 pendingIntent = PendingIntent.getBroadcast(
3587 mContext,
3588 0 /* requestCode */,
3589 intent,
3590 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003591 } finally {
3592 Binder.restoreCallingIdentity(token);
3593 }
3594 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3595 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003596 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003597 }
3598
3599 @Override
3600 public void hideProvisioningNotification() {
3601 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003602 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003603 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003604
3605 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003606 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003607 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003608 }
3609
3610 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003611 public int getInterfaceVersion() {
3612 return this.VERSION;
3613 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003614
3615 @Override
3616 public String getInterfaceHash() {
3617 return this.HASH;
3618 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003619 }
3620
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003621 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003622 log("Data stall detected with methods: " + p.detectionMethod);
3623
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003624 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003625 int detectionMethod = 0;
3626 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3627 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3628 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3629 }
3630 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3631 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3632 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3633 p.tcpMetricsCollectionPeriodMillis);
3634 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003635 }
3636
Cody Kestingf53a0752020-04-15 12:33:28 -07003637 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003638 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003639 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003640
3641 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3642 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3643 // the cost of going through two handlers.
3644 mConnectivityDiagnosticsHandler.sendMessage(msg);
3645 }
3646
Cody Kestingb37958e2020-05-15 10:36:01 -07003647 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3648 return (p.detectionMethod & detectionMethod) != 0;
3649 }
3650
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003651 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3652 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003653 }
3654
Erik Klinea73af002018-06-26 18:53:43 +09003655 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3656 if (nai == null) return;
3657 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3658 // in order to restart a validation pass from within netd.
3659 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3660 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003661 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003662 }
3663 }
3664
Erik Kline31b4a9e2018-01-11 21:07:29 +09003665 private void handlePrivateDnsSettingsChanged() {
3666 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3667
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003668 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003669 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003670 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003671 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3672 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003673 }
3674 }
3675
Erik Kline9a62f012018-03-21 07:18:33 -07003676 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3677 // Private DNS only ever applies to networks that might provide
3678 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003679 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003680
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003681 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003682 // schedule DNS resolutions. If a DNS resolution is required the
3683 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003684 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003685
3686 // With Private DNS bypass support, we can proceed to update the
3687 // Private DNS config immediately, even if we're in strict mode
3688 // and have not yet resolved the provider name into a set of IPs.
3689 updatePrivateDns(nai, cfg);
3690 }
3691
3692 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3693 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003694 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003695 }
3696
dalyk1720e542018-03-05 12:42:22 -05003697 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3698 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3699 if (nai == null) {
3700 return;
3701 }
3702 mDnsManager.updatePrivateDnsValidation(update);
3703 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3704 }
3705
paulhu7c0a2e62021-01-08 00:51:49 +08003706 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003707 int prefixLength) {
3708 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3709 if (nai == null) return;
3710
paulhu7c0a2e62021-01-08 00:51:49 +08003711 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3712 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003713
3714 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003715 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003716 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003717 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003718 prefixLength);
3719 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003720 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003721 return;
3722 }
3723 }
3724
Lorenzo Colittid523d142020-04-01 20:16:30 +09003725 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003726 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3727 }
3728
Hai Shalome58bdc62021-01-11 18:45:34 -08003729 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003730 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003731 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003732 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3733 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3734 }
3735
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003736 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003737 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003738 * @param nai the agent info to update
3739 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003740 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003741 */
junyulai2b6f0c22021-02-03 20:15:30 +08003742 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3743 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3744 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003745 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003746 // one lingered request, set inactive.
3747 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003748 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003749 if (DBG) log("Unsetting inactive " + nai.toShortString());
3750 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003751 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003752 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003753 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003754 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3755 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003756 }
junyulai2b6f0c22021-02-03 20:15:30 +08003757 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003758 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003759 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003760 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003761 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003762 }
3763
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003764 private void handleNetworkAgentRegistered(Message msg) {
3765 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3766 if (!mNetworkAgentInfos.contains(nai)) {
3767 return;
3768 }
3769
3770 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3771 if (VDBG) log("NetworkAgent registered");
3772 } else {
3773 loge("Error connecting NetworkAgent");
3774 mNetworkAgentInfos.remove(nai);
3775 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003776 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003777 synchronized (mNetworkForNetId) {
3778 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003779 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003780 mNetIdManager.releaseNetId(nai.network.getNetId());
3781 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003782 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003783 }
3784 }
3785 }
Paul Jensend5f53392014-11-25 15:26:53 -05003786
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003787 private void handleNetworkAgentDisconnected(Message msg) {
3788 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3789 if (mNetworkAgentInfos.contains(nai)) {
3790 disconnectAndDestroyNetwork(nai);
3791 }
3792 }
3793
Chalard Jeand9fffc32018-05-11 20:19:20 +09003794 // Destroys a network, remove references to it from the internal state managed by
3795 // ConnectivityService, free its interfaces and clean up.
3796 // Must be called on the Handler thread.
3797 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003798 ensureRunningOnConnectivityServiceThread();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003799 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003800 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003801 }
lucaslinb25c9a62019-02-12 15:30:13 +08003802 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003803 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003804 // A network agent has disconnected.
3805 // TODO - if we move the logic to the network agent (have them disconnect
3806 // because they lost all their requests or because their score isn't good)
3807 // then they would disconnect organically, report their new state and then
3808 // disconnect the channel.
3809 if (nai.networkInfo.isConnected()) {
3810 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3811 null, null);
3812 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003813 final boolean wasDefault = isDefaultNetwork(nai);
3814 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003815 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003816 }
3817 notifyIfacesChangedForNetworkStats();
3818 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3819 // by other networks that are already connected. Perhaps that can be done by
3820 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3821 // of rematchAllNetworksAndRequests
3822 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003823 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003824
3825 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003826 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3827 // Disable wakeup packet monitoring for each interface.
3828 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3829 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003830 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003831 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003832 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003833 synchronized (mNetworkForNetId) {
3834 // Remove the NetworkAgent, but don't mark the netId as
3835 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003836 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003837 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09003838 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003839 // Remove all previously satisfied requests.
3840 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003841 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09003842 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08003843 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08003844 if (currentNetwork != null
3845 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003846 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09003847 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3848 // rematch not to keep disconnected agents instead of setting it here ; this
3849 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08003850 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09003851 for (final NetworkOfferInfo noi : mNetworkOffers) {
3852 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08003853 }
James Mattise3ef1912020-12-20 11:09:58 -08003854
Chalard Jean5b409c72021-02-04 13:12:59 +09003855 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08003856 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09003857 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08003858 // network, because while incorrect this is the closest to the old (also
3859 // incorrect) behavior.
3860 mNetworkActivityTracker.updateDataActivityTracking(
3861 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08003862 ensureNetworkTransitionWakelock(nai.toShortString());
3863 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09003864 }
3865 }
junyulai2b6f0c22021-02-03 20:15:30 +08003866 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08003867 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09003868 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08003869 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09003870 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09003871 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003872 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003873
3874 // Immediate teardown.
3875 if (nai.teardownDelayMs == 0) {
3876 destroyNetwork(nai);
3877 return;
3878 }
3879
3880 // Delayed teardown.
3881 try {
3882 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3883 } catch (RemoteException e) {
3884 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3885 }
3886 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3887 }
3888
3889 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003890 if (nai.created) {
3891 // Tell netd to clean up the configuration for this network
3892 // (routing rules, DNS, etc).
3893 // This may be slow as it requires a lot of netd shelling out to ip and
3894 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09003895 // after we've rematched networks with requests (which might change the default
3896 // network or service a new request from an app), so network traffic isn't interrupted
3897 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08003898 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003899 mDnsManager.removeNetwork(nai.network);
3900 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08003901 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003902 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003903 }
3904
Ken Chen6df7a902021-04-09 15:08:42 +08003905 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08003906 try {
3907 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08003908 final NativeNetworkConfig config;
3909 if (nai.isVPN()) {
3910 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08003911 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08003912 return false;
3913 }
3914 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3915 INetd.PERMISSION_NONE,
3916 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3917 getVpnType(nai));
Luke Huangfdd11f82019-04-09 18:41:49 +08003918 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08003919 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3920 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3921 VpnManager.TYPE_VPN_NONE);
Luke Huangfdd11f82019-04-09 18:41:49 +08003922 }
Ken Chen6df7a902021-04-09 15:08:42 +08003923 mNetd.networkCreate(config);
3924 mDnsResolver.createNetworkCache(nai.network.getNetId());
3925 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3926 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08003927 return true;
3928 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08003929 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08003930 return false;
3931 }
3932 }
3933
Ken Chen6df7a902021-04-09 15:08:42 +08003934 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08003935 try {
Ken Chen6df7a902021-04-09 15:08:42 +08003936 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09003937 } catch (RemoteException | ServiceSpecificException e) {
3938 loge("Exception destroying network(networkDestroy): " + e);
3939 }
3940 try {
Ken Chen6df7a902021-04-09 15:08:42 +08003941 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08003942 } catch (RemoteException | ServiceSpecificException e) {
3943 loge("Exception destroying network: " + e);
3944 }
3945 }
3946
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003947 // If this method proves to be too slow then we can maintain a separate
3948 // pendingIntent => NetworkRequestInfo map.
3949 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3950 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003951 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3952 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3953 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09003954 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003955 return entry.getValue();
3956 }
3957 }
3958 return null;
3959 }
3960
James Mattisf7027322020-12-13 16:28:14 -08003961 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003962 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08003963 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3964 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3965 final NetworkRequestInfo existingRequest =
3966 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003967 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08003968 if (DBG) {
3969 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3970 + nri.mRequests.get(0) + " because their intents matched.");
3971 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09003972 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08003973 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003974 }
Erik Kline05f2b402015-04-30 12:58:40 +09003975 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08003976 }
3977
James Mattisf7027322020-12-13 16:28:14 -08003978 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08003979 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08003980 }
3981
James Mattis3ce3d3c2021-02-09 18:18:28 -08003982 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003983 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08003984 for (final NetworkRequestInfo nri : nris) {
3985 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3986 for (final NetworkRequest req : nri.mRequests) {
3987 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08003988 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08003989 if (req.isListen()) {
3990 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3991 if (req.networkCapabilities.hasSignalStrength()
3992 && network.satisfiesImmutableCapabilitiesOf(req)) {
3993 updateSignalStrengthThresholds(network, "REGISTER", req);
3994 }
James Mattisf7027322020-12-13 16:28:14 -08003995 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09003996 }
3997 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09003998 // If this NRI has a satisfier already, it is replacing an older request that
3999 // has been removed. Track it.
4000 final NetworkRequest activeRequest = nri.getActiveRequest();
4001 if (null != activeRequest) {
4002 // If there is an active request, then for sure there is a satisfier.
4003 nri.getSatisfier().addRequest(activeRequest);
4004 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004005 }
James Mattisf7027322020-12-13 16:28:14 -08004006
James Mattis45d81842021-01-10 14:24:24 -08004007 rematchAllNetworksAndRequests();
James Mattis45d81842021-01-10 14:24:24 -08004008
Chalard Jean0354d8c2021-01-12 10:58:56 +09004009 // Requests that have not been matched to a network will not have been sent to the
4010 // providers, because the old satisfier and the new satisfier are the same (null in this
4011 // case). Send these requests to the providers.
4012 for (final NetworkRequestInfo nri : nris) {
4013 for (final NetworkOfferInfo noi : mNetworkOffers) {
4014 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004015 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004016 }
4017 }
4018
James Mattisf7027322020-12-13 16:28:14 -08004019 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4020 final int callingUid) {
4021 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004022 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004023 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4024 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4025 handleReleaseNetworkRequest(
4026 nri.mRequests.get(0),
4027 callingUid,
4028 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004029 }
4030 }
4031
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004032 // Determines whether the network is the best (or could become the best, if it validated), for
4033 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4034 // on the value of reason:
4035 //
4036 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4037 // then it should be torn down.
4038 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4039 // then it should be lingered.
4040 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004041 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004042
4043 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4044 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4045 return false;
4046 }
4047
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004048 final int numRequests;
4049 switch (reason) {
4050 case TEARDOWN:
4051 numRequests = nai.numRequestNetworkRequests();
4052 break;
4053 case LINGER:
4054 numRequests = nai.numForegroundNetworkRequests();
4055 break;
4056 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004057 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004058 return true;
4059 }
4060
Chalard Jean947acd42021-03-08 22:29:27 +09004061 if (numRequests > 0) return false;
4062
Paul Jensende49eb12015-06-25 15:30:08 -04004063 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004064 if (reason == UnneededFor.LINGER
4065 && !nri.isMultilayerRequest()
4066 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004067 // Background requests don't affect lingering.
4068 continue;
4069 }
4070
James Mattis3d229892020-11-16 16:46:28 -08004071 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004072 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004073 }
4074 }
Paul Jensende49eb12015-06-25 15:30:08 -04004075 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004076 }
4077
James Mattis3d229892020-11-16 16:46:28 -08004078 private boolean isNetworkPotentialSatisfier(
4079 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4080 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004081 // request, return immediately. For multilayer requests, check to see if any of the
4082 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004083 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4084 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004085 return false;
4086 }
4087 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004088 // This multilayer listen request is satisfied therefore no further requests need to be
4089 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004090 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004091 return false;
4092 }
James Mattis3d229892020-11-16 16:46:28 -08004093 // As non-multilayer listen requests have already returned, the below would only happen
4094 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004095 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004096 continue;
4097 }
4098 // If this Network is already the highest scoring Network for a request, or if
4099 // there is hope for it to become one if it validated, then it is needed.
4100 if (candidate.satisfies(req)) {
4101 // As soon as a network is found that satisfies a request, return. Specifically for
4102 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4103 // is important so as to not evaluate lower priority requests further in
4104 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004105 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4106 ? nri.getSatisfier() : null;
4107 // Note that this catches two important cases:
4108 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4109 // is currently satisfying the request. This is desirable when
4110 // cellular ends up validating but WiFi does not.
4111 // 2. Unvalidated WiFi will not be reaped when validated cellular
4112 // is currently satisfying the request. This is desirable when
4113 // WiFi ends up validating and out scoring cellular.
4114 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004115 }
4116 }
4117
4118 return false;
4119 }
4120
Erik Kline0c04b742016-07-07 16:50:58 +09004121 private NetworkRequestInfo getNriForAppRequest(
4122 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004123 // Looking up the app passed param request in mRequests isn't possible since it may return
4124 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4125 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004126 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4127 // to avoid potential race conditions when validating a package->uid mapping when sending
4128 // the callback on the very low-chance that an application shuts down prior to the callback
4129 // being sent.
4130 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4131 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004132
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004133 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004134 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004135 log(String.format("UID %d attempted to %s for unowned request %s",
4136 callingUid, requestedOperation, nri));
4137 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004138 }
Erik Kline0c04b742016-07-07 16:50:58 +09004139 }
4140
4141 return nri;
4142 }
4143
James Mattisf7027322020-12-13 16:28:14 -08004144 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4145 final String callingMethod) {
4146 if (nri.isMultilayerRequest()) {
4147 throw new IllegalStateException(
4148 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004149 }
4150 }
4151
James Mattisf7027322020-12-13 16:28:14 -08004152 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004153 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004154 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4155 // single NetworkRequest and thus does not apply to multilayer requests.
4156 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4157 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004158 return;
4159 }
James Mattis2516da32021-01-31 17:06:19 -08004160 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004161 return;
4162 }
James Mattisf7027322020-12-13 16:28:14 -08004163 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4164 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004165 }
4166 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004167 callCallbackForRequest(
4168 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004169 }
4170
James Mattisf7027322020-12-13 16:28:14 -08004171 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4172 final int callingUid,
4173 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004174 final NetworkRequestInfo nri =
4175 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4176 if (nri == null) {
4177 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004178 }
James Mattisf7027322020-12-13 16:28:14 -08004179 if (VDBG || (DBG && request.isRequest())) {
4180 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004181 }
4182 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004183 if (callOnUnavailable) {
4184 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4185 }
Erik Kline155a59a2015-11-25 12:49:38 +09004186 }
Erik Kline0c04b742016-07-07 16:50:58 +09004187
James Mattisa076c532020-12-02 14:12:41 -08004188 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004189 ensureRunningOnConnectivityServiceThread();
Erik Kline0c04b742016-07-07 16:50:58 +09004190 nri.unlinkDeathRecipient();
James Mattisa076c532020-12-02 14:12:41 -08004191 for (final NetworkRequest req : nri.mRequests) {
4192 mNetworkRequests.remove(req);
4193 if (req.isListen()) {
4194 removeListenRequestFromNetworks(req);
4195 }
4196 }
Chalard Jean738c5bf2021-03-01 22:08:57 +09004197 if (mDefaultNetworkRequests.remove(nri)) {
4198 // If this request was one of the defaults, then the UID rules need to be updated
4199 // WARNING : if the app(s) for which this network request is the default are doing
4200 // traffic, this will kill their connected sockets, even if an equivalent request
4201 // is going to be reinstated right away ; unconnected traffic will go on the default
4202 // until the new default is set, which will happen very soon.
4203 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4204 // remove ranges for those requests that won't have a replacement
4205 final NetworkAgentInfo satisfier = nri.getSatisfier();
4206 if (null != satisfier) {
4207 try {
paulhue9913722021-05-26 15:19:20 +08004208 // TODO: Passing default network priority to netd.
Chalard Jean738c5bf2021-03-01 22:08:57 +09004209 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
paulhue9913722021-05-26 15:19:20 +08004210 toUidRangeStableParcels(nri.getUids())
4211 /* nri.getDefaultNetworkPriority() */);
Chalard Jean738c5bf2021-03-01 22:08:57 +09004212 } catch (RemoteException e) {
4213 loge("Exception setting network preference default network", e);
4214 }
4215 }
4216 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004217 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004218 mNetworkRequestInfoLogs.log("RELEASE " + nri);
James Mattisa076c532020-12-02 14:12:41 -08004219
4220 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004221 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004222 removeSatisfiedNetworkRequestFromNetwork(nri);
4223 } else {
4224 nri.setSatisfier(null, null);
4225 }
4226 }
4227
Chalard Jean0354d8c2021-01-12 10:58:56 +09004228 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4229 // needed for this offer.
4230 for (final NetworkOfferInfo noi : mNetworkOffers) {
4231 for (final NetworkRequest req : nri.mRequests) {
4232 if (req.isRequest() && noi.offer.neededFor(req)) {
4233 noi.offer.onNetworkUnneeded(req);
4234 }
4235 }
4236 }
James Mattisa076c532020-12-02 14:12:41 -08004237 }
4238
James Mattis3ce3d3c2021-02-09 18:18:28 -08004239 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4240 for (final NetworkRequestInfo nri : nris) {
4241 if (mDefaultRequest == nri) {
4242 // Make sure we never remove the default request.
4243 continue;
4244 }
4245 handleRemoveNetworkRequest(nri);
4246 }
4247 }
4248
James Mattisa076c532020-12-02 14:12:41 -08004249 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4250 // listens don't have a singular affected Network. Check all networks to see
4251 // if this listen request applies and remove it.
4252 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4253 nai.removeRequest(req.requestId);
4254 if (req.networkCapabilities.hasSignalStrength()
4255 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4256 updateSignalStrengthThresholds(nai, "RELEASE", req);
4257 }
4258 }
4259 }
4260
4261 /**
4262 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4263 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4264 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4265 */
4266 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4267 boolean wasKept = false;
4268 final NetworkAgentInfo nai = nri.getSatisfier();
4269 if (nai != null) {
4270 final int requestLegacyType = nri.getActiveRequest().legacyType;
4271 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4272 nai.removeRequest(nri.getActiveRequest().requestId);
4273 if (VDBG || DDBG) {
4274 log(" Removing from current network " + nai.toShortString()
4275 + ", leaving " + nai.numNetworkRequests() + " requests.");
4276 }
4277 // If there are still lingered requests on this network, don't tear it down,
4278 // but resume lingering instead.
4279 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004280 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004281 notifyNetworkLosing(nai, now);
4282 }
4283 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4284 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4285 teardownUnneededNetwork(nai);
4286 } else {
4287 wasKept = true;
4288 }
4289 nri.setSatisfier(null, null);
4290 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4291 // Went from foreground to background.
4292 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004293 }
4294
Erik Kline0c04b742016-07-07 16:50:58 +09004295 // Maintain the illusion. When this request arrived, we might have pretended
4296 // that a network connected to serve it, even though the network was already
4297 // connected. Now that this request has gone away, we might have to pretend
4298 // that the network disconnected. LegacyTypeTracker will generate that
4299 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004300 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004301 boolean doRemove = true;
4302 if (wasKept) {
4303 // check if any of the remaining requests for this network are for the
4304 // same legacy type - if so, don't remove the nai
4305 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4306 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004307 if (otherRequest.legacyType == requestLegacyType
4308 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004309 if (DBG) log(" still have other legacy request - leaving");
4310 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004311 }
4312 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004313 }
4314
Erik Kline0c04b742016-07-07 16:50:58 +09004315 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004316 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004317 }
4318 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004319 }
4320 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004321
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004322 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4323 return checkAnyPermissionOf(
4324 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4325 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4326 }
4327
Lorenzo Colittid6459092016-07-04 12:55:44 +09004328 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004329 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004330 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004331 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004332 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004333 }
4334
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004335 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004336 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4337 enforceNetworkStackSettingsOrSetup();
4338 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4339 encodeBool(accept), encodeBool(always), network));
4340 }
4341
4342 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004343 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004344 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004345 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4346 }
4347
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004348 @Override
4349 public void setTestAllowBadWifiUntil(long timeMs) {
4350 enforceSettingsPermission();
4351 if (!Build.isDebuggable()) {
4352 throw new IllegalStateException("Does not support in non-debuggable build");
4353 }
4354
4355 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4356 throw new IllegalArgumentException("It should not exceed "
4357 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4358 }
4359
4360 mHandler.sendMessage(
4361 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4362 }
4363
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004364 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4365 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4366 " accept=" + accept + " always=" + always);
4367
4368 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4369 if (nai == null) {
4370 // Nothing to do.
4371 return;
4372 }
4373
4374 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004375 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004376 return;
4377 }
4378
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004379 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004380 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004381 }
4382
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004383 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4384 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004385 // If network becomes partial connectivity and user already accepted to use this
4386 // network, we should respect the user's option and don't need to popup the
4387 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004388 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004389 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004390 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004391 }
4392
4393 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004394 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004395 }
4396
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004397 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004398 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004399 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004400 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004401 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004402 }
4403
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004404 }
4405
lucaslin2240ef62019-03-12 13:08:03 +08004406 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4407 boolean always) {
4408 if (DBG) {
4409 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4410 + " always=" + always);
4411 }
4412
4413 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4414 if (nai == null) {
4415 // Nothing to do.
4416 return;
4417 }
4418
4419 if (nai.lastValidated) {
4420 // The network validated while the dialog box was up. Take no action.
4421 return;
4422 }
4423
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004424 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4425 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004426 }
4427
4428 // TODO: Use the current design or save the user choice into IpMemoryStore.
4429 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004430 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004431 }
4432
4433 if (!accept) {
4434 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004435 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004436 // Tear down the network.
4437 teardownUnneededNetwork(nai);
4438 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004439 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4440 // result in a partial connectivity result which will be processed by
4441 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004442 //
4443 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4444 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004445 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004446 }
4447 }
4448
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004449 private void handleSetAvoidUnvalidated(Network network) {
4450 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4451 if (nai == null || nai.lastValidated) {
4452 // Nothing to do. The network either disconnected or revalidated.
4453 return;
4454 }
4455 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004456 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004457 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004458 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004459 }
4460 }
4461
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004462 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004463 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004464 mHandler.sendMessageDelayed(
4465 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4466 PROMPT_UNVALIDATED_DELAY_MS);
4467 }
4468
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004469 @Override
4470 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004471 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004472 mHandler.post(() -> {
4473 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4474 if (nai == null) return;
4475 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004476 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004477 });
4478 }
4479
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004480 /**
4481 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4482 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004483 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004484 * @param appExtras Bundle to use as intent extras for the captive portal application.
4485 * Must be treated as opaque to avoid preventing the captive portal app to
4486 * update its arguments.
4487 */
4488 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004489 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004490 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4491 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004492
4493 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4494 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004495 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4496 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004497 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4498
lucaslin75ff7022020-12-17 04:14:35 +08004499 final long token = Binder.clearCallingIdentity();
4500 try {
4501 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4502 } finally {
4503 Binder.restoreCallingIdentity(token);
4504 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004505 }
4506
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004507 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4508 private final Network mNetwork;
4509
4510 private CaptivePortalImpl(Network network) {
4511 mNetwork = network;
4512 }
4513
4514 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004515 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004516 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4517 enforceSettingsPermission();
4518 }
4519
Chiachang Wang938bfba2020-01-09 13:50:55 +08004520 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004521 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004522 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004523 }
4524
4525 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004526 public void appRequest(final int request) {
4527 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4528 if (nm == null) return;
4529
4530 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004531 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004532 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004533 }
4534 }
4535
4536 @Nullable
4537 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4538 // getNetworkAgentInfoForNetwork is thread-safe
4539 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4540 if (nai == null) return null;
4541
4542 // nai.networkMonitor() is thread-safe
4543 return nai.networkMonitor();
4544 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004545 }
4546
Hugo Benichic9048bc2016-09-14 23:23:08 +00004547 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004548 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004549 }
4550
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004551 /**
4552 * Return whether the device should maintain continuous, working connectivity by switching away
4553 * from WiFi networks having no connectivity.
4554 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4555 */
4556 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004557 if (!checkNetworkStackPermission()) {
4558 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4559 }
4560 return avoidBadWifi();
4561 }
4562
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004563 private void updateAvoidBadWifi() {
4564 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004565 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004566 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004567 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004568 }
4569
Erik Kline95ecfee2016-10-02 18:02:14 +09004570 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004571 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004572 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004573 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004574 if (!configRestrict) {
4575 pw.println("Bad Wi-Fi avoidance: unrestricted");
4576 return;
4577 }
4578
4579 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4580 pw.increaseIndent();
4581 pw.println("Config restrict: " + configRestrict);
4582
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004583 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004584 String description;
4585 // Can't use a switch statement because strings are legal case labels, but null is not.
4586 if ("0".equals(value)) {
4587 description = "get stuck";
4588 } else if (value == null) {
4589 description = "prompt";
4590 } else if ("1".equals(value)) {
4591 description = "avoid";
4592 } else {
4593 description = value + " (?)";
4594 }
4595 pw.println("User setting: " + description);
4596 pw.println("Network overrides:");
4597 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004598 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004599 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004600 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004601 }
4602 }
4603 pw.decreaseIndent();
4604 pw.decreaseIndent();
4605 }
4606
paulhu7746e4e2020-06-09 19:07:03 +08004607 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4608 // unify the method.
4609 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4610 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4611 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4612 return settingsComponent != null
4613 ? settingsComponent.getPackageName() : "com.android.settings";
4614 }
4615
lucaslinb1e8e382019-01-24 15:55:30 +08004616 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004617 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004618 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004619 switch (type) {
4620 case NO_INTERNET:
4621 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004622 // High priority because it is only displayed for explicitly selected networks.
4623 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004624 break;
lucasline117e2e2019-10-22 18:27:33 +08004625 case PRIVATE_DNS_BROKEN:
4626 action = Settings.ACTION_WIRELESS_SETTINGS;
4627 // High priority because we should let user know why there is no internet.
4628 highPriority = true;
4629 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004630 case LOST_INTERNET:
4631 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004632 // High priority because it could help the user avoid unexpected data usage.
4633 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004634 break;
lucaslin2240ef62019-03-12 13:08:03 +08004635 case PARTIAL_CONNECTIVITY:
4636 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004637 // Don't bother the user with a high-priority notification if the network was not
4638 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004639 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004640 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004641 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004642 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004643 return;
4644 }
4645
4646 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004647 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004648 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004649 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004650 // Some OEMs have their own Settings package. Thus, need to get the current using
4651 // Settings package name instead of just use default name "com.android.settings".
4652 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4653 intent.setClassName(settingsPkgName,
4654 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004655 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004656
paulhu2af50222020-10-11 22:52:27 +08004657 PendingIntent pendingIntent = PendingIntent.getActivity(
4658 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004659 0 /* requestCode */,
4660 intent,
paulhu2af50222020-10-11 22:52:27 +08004661 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004662
Serik Beketayevec8ad212020-12-07 22:43:07 -08004663 mNotifier.showNotification(
4664 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004665 }
4666
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004667 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4668 // Don't prompt if the network is validated, and don't prompt on captive portals
4669 // because we're already prompting the user to sign in.
4670 if (nai.everValidated || nai.everCaptivePortalDetected) {
4671 return false;
4672 }
4673
4674 // If a network has partial connectivity, always prompt unless the user has already accepted
4675 // partial connectivity and selected don't ask again. This ensures that if the device
4676 // automatically connects to a network that has partial Internet access, the user will
4677 // always be able to use it, either because they've already chosen "don't ask again" or
4678 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004679 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004680 return true;
4681 }
4682
4683 // If a network has no Internet access, only prompt if the network was explicitly selected
4684 // and if the user has not already told us to use the network regardless of whether it
4685 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004686 if (nai.networkAgentConfig.explicitlySelected
4687 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004688 return true;
4689 }
4690
4691 return false;
4692 }
4693
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004694 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004695 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004696 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4697
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004698 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004699 return;
4700 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004701
4702 // Stop automatically reconnecting to this network in the future. Automatically connecting
4703 // to a network that provides no or limited connectivity is not useful, because the user
4704 // cannot use that network except through the notification shown by this method, and the
4705 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004706 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004707
lucaslin2240ef62019-03-12 13:08:03 +08004708 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4709 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4710 // popup the notification immediately when the network is partial connectivity.
4711 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004712 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004713 } else {
4714 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4715 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004716 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004717
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004718 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4719 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004720 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004721
lucaslin2240ef62019-03-12 13:08:03 +08004722 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4723 return;
4724 }
4725
4726 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004727 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004728 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004729 }
4730
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004731 @Override
4732 public int getMultipathPreference(Network network) {
4733 enforceAccessPermission();
4734
4735 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004736 if (nai != null && nai.networkCapabilities
4737 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004738 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4739 }
4740
Aaron Huang9a57acf2020-12-08 10:03:29 +08004741 final NetworkPolicyManager netPolicyManager =
4742 mContext.getSystemService(NetworkPolicyManager.class);
4743
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004744 final long token = Binder.clearCallingIdentity();
4745 final int networkPreference;
4746 try {
4747 networkPreference = netPolicyManager.getMultipathPreference(network);
4748 } finally {
4749 Binder.restoreCallingIdentity(token);
4750 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004751 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004752 return networkPreference;
4753 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004754 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4755 }
4756
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004757 @Override
4758 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004759 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004760 }
4761
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004762 private class InternalHandler extends Handler {
4763 public InternalHandler(Looper looper) {
4764 super(looper);
4765 }
4766
4767 @Override
4768 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004769 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004770 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004771 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004772 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004773 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004774 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004775 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004776 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004777 break;
4778 }
Jason Monka69f1b02013-10-10 14:02:51 -04004779 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004780 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4781 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004782 break;
4783 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004784 case EVENT_REGISTER_NETWORK_PROVIDER: {
4785 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004786 break;
4787 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004788 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4789 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004790 break;
4791 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004792 case EVENT_REGISTER_NETWORK_OFFER: {
4793 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4794 break;
4795 }
4796 case EVENT_UNREGISTER_NETWORK_OFFER: {
4797 final NetworkOfferInfo offer =
4798 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4799 if (null != offer) {
4800 handleUnregisterNetworkOffer(offer);
4801 }
4802 break;
4803 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004804 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004805 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4806 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4807 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004808 break;
4809 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004810 case EVENT_REGISTER_NETWORK_REQUEST:
4811 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09004812 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004813 break;
4814 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004815 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4816 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004817 handleRegisterNetworkRequestWithIntent(msg);
4818 break;
4819 }
Erik Kline155a59a2015-11-25 12:49:38 +09004820 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4821 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4822 handleTimedOutNetworkRequest(nri);
4823 break;
4824 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004825 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4826 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4827 break;
4828 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004829 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08004830 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4831 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004832 break;
4833 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004834 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09004835 Network network = (Network) msg.obj;
4836 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004837 break;
4838 }
lucaslin2240ef62019-03-12 13:08:03 +08004839 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4840 Network network = (Network) msg.obj;
4841 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4842 toBool(msg.arg2));
4843 break;
4844 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004845 case EVENT_SET_AVOID_UNVALIDATED: {
4846 handleSetAvoidUnvalidated((Network) msg.obj);
4847 break;
4848 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004849 case EVENT_PROMPT_UNVALIDATED: {
4850 handlePromptUnvalidated((Network) msg.obj);
4851 break;
4852 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07004853 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4854 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09004855 break;
4856 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004857 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08004858 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004859 mKeepaliveTracker.handleStartKeepalive(msg);
4860 break;
4861 }
4862 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08004863 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004864 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4865 int slot = msg.arg1;
4866 int reason = msg.arg2;
4867 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4868 break;
4869 }
Hugo Benichid6b510a2017-04-06 17:22:18 +09004870 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichif4210292017-04-21 15:07:12 +09004871 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09004872 break;
4873 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004874 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4875 handlePrivateDnsSettingsChanged();
4876 break;
dalyk1720e542018-03-05 12:42:22 -05004877 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4878 handlePrivateDnsValidationUpdate(
4879 (PrivateDnsValidationUpdate) msg.obj);
4880 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00004881 case EVENT_UID_BLOCKED_REASON_CHANGED:
4882 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08004883 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09004884 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4885 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4886 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004887 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09004888 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4889 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004890 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08004891 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09004892 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09004893 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4894 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4895 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4896 msg.obj;
4897 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08004898 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09004899 }
lucaslin1193a5d2021-01-21 02:04:15 +08004900 case EVENT_REPORT_NETWORK_ACTIVITY:
4901 mNetworkActivityTracker.handleReportNetworkActivity();
4902 break;
paulhu51f77dc2021-06-07 02:34:20 +00004903 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
4904 handleMobileDataPreferredUidsChanged();
4905 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004906 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
4907 final long timeMs = ((Long) msg.obj).longValue();
4908 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
4909 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004910 }
4911 }
4912 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004913
Lorenzo Colittid6459092016-07-04 12:55:44 +09004914 @Override
markchien5776f962019-12-16 20:15:20 +08004915 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004916 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08004917 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4918 Context.TETHERING_SERVICE);
4919 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004920 }
4921
Lorenzo Colittid6459092016-07-04 12:55:44 +09004922 @Override
markchien5776f962019-12-16 20:15:20 +08004923 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004924 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08004925 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4926 Context.TETHERING_SERVICE);
4927 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004928 }
4929
Lorenzo Colittid6459092016-07-04 12:55:44 +09004930 @Override
markchien5776f962019-12-16 20:15:20 +08004931 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004932 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08004933 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4934 Context.TETHERING_SERVICE);
4935 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08004936 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004937
markchien5776f962019-12-16 20:15:20 +08004938
Lorenzo Colittid6459092016-07-04 12:55:44 +09004939 @Override
markchien5776f962019-12-16 20:15:20 +08004940 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004941 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08004942 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4943 Context.TETHERING_SERVICE);
4944
4945 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08004946 }
4947
Lorenzo Colittid6459092016-07-04 12:55:44 +09004948 @Override
markchien5776f962019-12-16 20:15:20 +08004949 @Deprecated
4950 public String[] getTetherableUsbRegexs() {
4951 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4952 Context.TETHERING_SERVICE);
4953
4954 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07004955 }
4956
Udam Saini8f7d6a72017-06-07 12:06:28 -07004957 @Override
markchien5776f962019-12-16 20:15:20 +08004958 @Deprecated
4959 public String[] getTetherableWifiRegexs() {
4960 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4961 Context.TETHERING_SERVICE);
4962 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08004963 }
4964
Robert Greenwalte0b00512014-07-02 09:59:16 -07004965 // Called when we lose the default network and have no replacement yet.
4966 // This will automatically be cleared after X seconds or a new default network
4967 // becomes CONNECTED, whichever happens first. The timer is started by the
4968 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09004969 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004970 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004971 if (mNetTransitionWakeLock.isHeld()) {
4972 return;
4973 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004974 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004975 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4976 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004977 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004978 mWakelockLogs.log("ACQUIRE for " + forWhom);
4979 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09004980 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09004981 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09004982 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07004983 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07004984
Hugo Benichi471b62a2017-03-30 23:18:10 +09004985 // Called when we gain a new default network to release the network transition wakelock in a
4986 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4987 // message is cancelled.
4988 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09004989 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004990 if (!mNetTransitionWakeLock.isHeld()) {
4991 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09004992 }
4993 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09004994 // Cancel self timeout on wakelock hold.
4995 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4996 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4997 mHandler.sendMessageDelayed(msg, 1000);
4998 }
4999
5000 // Called when either message of ensureNetworkTransitionWakelock or
5001 // scheduleReleaseNetworkTransitionWakelock is processed.
5002 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5003 String event = eventName(eventId);
5004 synchronized (this) {
5005 if (!mNetTransitionWakeLock.isHeld()) {
5006 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005007 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005008 return;
5009 }
5010 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005011 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5012 mTotalWakelockDurationMs += lockDuration;
5013 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5014 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005015 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005016 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005017 }
5018
Robert Greenwalt986c7412010-09-08 15:24:47 -07005019 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005020 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005021 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005022 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005023 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005024 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005025 }
5026
Lorenzo Colittid6459092016-07-04 12:55:44 +09005027 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005028 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005029 enforceAccessPermission();
5030 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005031 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005032 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005033
Cody Kesting3d1df812020-06-25 11:13:39 -07005034 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
5035 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
5036 // does not match the known connectivity of the network - this causes NetworkMonitor to
5037 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005038 final NetworkAgentInfo nai;
5039 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005040 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005041 } else {
5042 nai = getNetworkAgentInfoForNetwork(network);
5043 }
5044 if (nai != null) {
5045 mConnectivityDiagnosticsHandler.sendMessage(
5046 mConnectivityDiagnosticsHandler.obtainMessage(
5047 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5048 connectivityInfo, 0, nai));
5049 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005050
5051 mHandler.sendMessage(
5052 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005053 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005054
Hugo Benichid6b510a2017-04-06 17:22:18 +09005055 private void handleReportNetworkConnectivity(
5056 Network network, int uid, boolean hasConnectivity) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005057 final NetworkAgentInfo nai;
Paul Jensenb95d7952015-04-07 12:43:13 -04005058 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005059 nai = getDefaultNetwork();
Paul Jensenb95d7952015-04-07 12:43:13 -04005060 } else {
5061 nai = getNetworkAgentInfoForNetwork(network);
5062 }
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005063 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
5064 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
5065 return;
5066 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005067 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005068 if (hasConnectivity == nai.lastValidated) {
5069 return;
5070 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005071 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005072 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005073 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005074 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005075 // Validating a network that has not yet connected could result in a call to
5076 // rematchNetworkAndRequests() which is not meant to work on such networks.
5077 if (!nai.everConnected) {
5078 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005079 }
paulhu7aeba372020-12-30 00:42:19 +08005080 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5081 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005082 return;
5083 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005084 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005085 }
5086
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005087 // TODO: call into netd.
5088 private boolean queryUserAccess(int uid, Network network) {
5089 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5090 if (nai == null) return false;
5091
5092 // Any UID can use its default network.
5093 if (nai == getDefaultNetworkForUid(uid)) return true;
5094
5095 // Privileged apps can use any network.
5096 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5097 return true;
5098 }
5099
5100 // An unprivileged UID can use a VPN iff the VPN applies to it.
5101 if (nai.isVPN()) {
5102 return nai.networkCapabilities.appliesToUid(uid);
5103 }
5104
5105 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5106 // sockets, i.e., if it is the owner.
5107 final NetworkAgentInfo vpn = getVpnForUid(uid);
5108 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5109 && uid != vpn.networkCapabilities.getOwnerUid()) {
5110 return false;
5111 }
5112
5113 // The UID's permission must be at least sufficient for the network. Since the restricted
5114 // permission was already checked above, that just leaves background networks.
5115 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5116 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5117 }
5118
5119 // Unrestricted network. Anyone gets to use it.
5120 return true;
5121 }
5122
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005123 /**
5124 * Returns information about the proxy a certain network is using. If given a null network, it
5125 * it will return the proxy for the bound network for the caller app or the default proxy if
5126 * none.
5127 *
5128 * @param network the network we want to get the proxy information for.
5129 * @return Proxy information if a network has a proxy configured, or otherwise null.
5130 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005131 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005132 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005133 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005134 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005135 if (network == null) {
5136 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005137 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005138 true);
5139 if (activeNetwork == null) {
5140 return null;
5141 }
5142 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005143 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005144 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5145 // caller may not have.
5146 return getLinkPropertiesProxyInfo(network);
5147 }
5148 // No proxy info available if the calling UID does not have network access.
5149 return null;
5150 }
5151
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005152
5153 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005154 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5155 if (nai == null) return null;
5156 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005157 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5158 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005159 }
5160 }
5161
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005162 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005163 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005164 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005165 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005166 }
5167
Chalard Jean777e2e52018-06-07 18:02:37 +09005168 @Override
5169 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005170 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005171 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005172 }
5173
Jason Monk4d5e20f2014-04-25 15:00:09 -04005174 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005175 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005176 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005177 proxy = null;
5178 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005179 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005180 }
5181
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005182 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5183 // when any network changes proxy.
5184 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5185 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005186 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005187 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5188 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5189
Chalard Jean7d97afc2018-06-07 17:41:29 +09005190 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005191 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005192 }
5193 }
5194
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005195 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005196 final private HashMap<Uri, Integer> mUriEventMap;
5197 final private Context mContext;
5198 final private Handler mHandler;
5199
5200 SettingsObserver(Context context, Handler handler) {
5201 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005202 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005203 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005204 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005205 }
5206
Erik Kline05f2b402015-04-30 12:58:40 +09005207 void observe(Uri uri, int what) {
5208 mUriEventMap.put(uri, what);
5209 final ContentResolver resolver = mContext.getContentResolver();
5210 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005211 }
5212
5213 @Override
5214 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005215 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005216 }
5217
5218 @Override
5219 public void onChange(boolean selfChange, Uri uri) {
5220 final Integer what = mUriEventMap.get(uri);
5221 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005222 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005223 } else {
5224 loge("No matching event to send for URI=" + uri);
5225 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005226 }
5227 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005228
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005229 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005230 Log.d(TAG, s);
5231 }
5232
5233 private static void logw(String s) {
5234 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005235 }
5236
Daniel Brightf9e945b2020-06-15 16:10:01 -07005237 private static void logwtf(String s) {
5238 Log.wtf(TAG, s);
5239 }
5240
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005241 private static void logwtf(String s, Throwable t) {
5242 Log.wtf(TAG, s, t);
5243 }
5244
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005245 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005246 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005247 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005248
Hugo Benichi39621362017-02-11 17:04:43 +09005249 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005250 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005251 }
5252
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005253 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005254 * Return the information of all ongoing VPNs.
5255 *
5256 * <p>This method is used to update NetworkStatsService.
5257 *
5258 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005259 */
junyulai2050bed2021-01-23 09:46:34 +08005260 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005261 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005262 if (mLockdownEnabled) {
5263 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005264 }
junyulai2050bed2021-01-23 09:46:34 +08005265 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005266 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005267 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005268 if (info != null) {
5269 infoList.add(info);
5270 }
5271 }
junyulai2050bed2021-01-23 09:46:34 +08005272 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005273 }
5274
5275 /**
5276 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005277 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005278 */
junyulai2050bed2021-01-23 09:46:34 +08005279 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005280 if (!nai.isVPN()) return null;
5281
5282 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005283 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5284 // the underlyingNetworks list.
5285 if (underlyingNetworks == null) {
James Mattis2516da32021-01-31 17:06:19 -08005286 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5287 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005288 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005289 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005290 }
5291 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005292
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005293 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005294
5295 List<String> interfaces = new ArrayList<>();
5296 for (Network network : underlyingNetworks) {
5297 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5298 if (underlyingNai == null) continue;
5299 LinkProperties lp = underlyingNai.linkProperties;
5300 for (String iface : lp.getAllInterfaceNames()) {
5301 if (!TextUtils.isEmpty(iface)) {
5302 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005303 }
5304 }
Benedict Wong34857f82019-06-12 17:46:15 +00005305 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005306
5307 if (interfaces.isEmpty()) return null;
5308
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005309 // Must be non-null or NetworkStatsService will crash.
5310 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5311 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005312 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005313 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005314
junyulai2050bed2021-01-23 09:46:34 +08005315 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5316 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005317 }
5318
James Mattisd31bdfa2020-12-23 16:37:26 -08005319 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005320 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5321 Network[] underlyingNetworks) {
5322 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005323 if (underlyingNetworks == null && defaultNetwork != null) {
5324 // null underlying networks means to track the default.
5325 underlyingNetworks = new Network[] { defaultNetwork };
5326 }
5327 return underlyingNetworks;
5328 }
5329
5330 // Returns true iff |network| is an underlying network of |nai|.
5331 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5332 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5333 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5334 if (!nai.supportsUnderlyingNetworks()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005335 final Network[] underlying = underlyingNetworksOrDefault(
5336 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005337 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005338 }
5339
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005340 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005341 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005342 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005343 * When underlying networks change, such networks may have to update capabilities to reflect
5344 * things like the metered bit, their transports, and so on. The capabilities are calculated
5345 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005346 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005347 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005348 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005349 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005350 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005351 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005352 }
5353 }
5354 }
5355
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005356 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5357 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5358 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5359 // a VPN is not up.
5360 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5361 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5362 for (UidRange range : blockedUidRanges) {
5363 if (range.contains(uid)) return true;
5364 }
5365 return false;
5366 }
5367
5368 @Override
5369 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005370 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005371 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5372 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5373 }
5374
5375 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5376 if (DBG) {
5377 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5378 + Arrays.toString(ranges));
5379 }
5380 // Cannot use a Set since the list of UID ranges might contain duplicates.
5381 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5382 for (int i = 0; i < ranges.length; i++) {
5383 if (requireVpn) {
5384 newVpnBlockedUidRanges.add(ranges[i]);
5385 } else {
5386 newVpnBlockedUidRanges.remove(ranges[i]);
5387 }
5388 }
5389
5390 try {
5391 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5392 } catch (RemoteException | ServiceSpecificException e) {
5393 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5394 + Arrays.toString(ranges) + "): netd command failed: " + e);
5395 }
5396
5397 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5398 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005399 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5400 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005401 }
5402
5403 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5404 }
5405
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005406 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005407 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005408 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005409 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005410 }
5411
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005412 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5413 return mLockdownEnabled
5414 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5415 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005416 }
5417
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005418 private NetworkAgentInfo getLegacyLockdownNai() {
5419 if (!mLockdownEnabled) {
5420 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005421 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005422 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005423 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5424 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005425
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005426 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005427 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5428 // a local variable. There is no need to make a copy because its contents cannot change.
5429 final Network[] underlying = nai.declaredUnderlyingNetworks;
5430 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005431 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005432 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005433
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005434 // The legacy lockdown VPN always uses the default network.
5435 // If the VPN's underlying network is no longer the current default network, it means that
5436 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005437 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5438 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005439 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005440 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005441 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005442 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005443
5444 return nai;
5445 };
5446
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005447 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5448 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5449 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005450 private DetailedState getLegacyLockdownState(DetailedState origState) {
5451 if (origState != DetailedState.CONNECTED) {
5452 return origState;
5453 }
5454 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5455 ? DetailedState.CONNECTING
5456 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005457 }
5458
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005459 private void filterForLegacyLockdown(NetworkInfo ni) {
5460 if (!mLockdownEnabled || !ni.isConnected()) return;
5461 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5462 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5463 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5464 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5465 // network, this time with a state of CONNECTED.
5466 //
5467 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5468 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5469 // is not too far off the truth, since an always-on VPN, when not connected, is always
5470 // trying to reconnect.
5471 if (getLegacyLockdownNai() == null) {
5472 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5473 }
5474 }
5475
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005476 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005477 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005478 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005479 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005480 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5481 return;
5482 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005483 final long ident = Binder.clearCallingIdentity();
5484 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005485 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005486 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005487 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005488 } finally {
5489 Binder.restoreCallingIdentity(ident);
5490 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005491 }
Wink Savillecb117d32013-08-29 14:57:08 -07005492
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005493 @Override
5494 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005495 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005496 final long ident = Binder.clearCallingIdentity();
5497 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005498 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005499 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005500 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5501 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005502 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005503 } finally {
5504 Binder.restoreCallingIdentity(ident);
5505 }
5506 }
5507
James Mattis02220e22021-03-13 19:27:21 -08005508 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005509 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005510 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5511 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5512 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005513 }
5514
James Mattis02220e22021-03-13 19:27:21 -08005515 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005516 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005517 // If there was a network preference for this user, remove it.
5518 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5519 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005520 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5521 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5522 }
junyulaid91e7052020-08-28 13:44:33 +08005523 }
5524
James Mattis02220e22021-03-13 19:27:21 -08005525 private void onPackageChanged(@NonNull final String packageName) {
5526 // This is necessary in case a package is added or removed, but also when it's replaced to
5527 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5528 // as one in the preferences, then it should follow the same routing as that other package,
5529 // which means updating the rules is never to be needed in this case (whether it joins or
5530 // leaves a UID with a preference).
5531 if (isMappedInOemNetworkPreference(packageName)) {
5532 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5533 }
5534 }
5535
5536 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005537 @Override
5538 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005539 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005540 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005541 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005542
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005543 // User should be filled for below intents, check the existence.
5544 if (user == null) {
5545 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5546 return;
5547 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005548
Lorenzo Colitticd675292021-02-04 17:32:07 +09005549 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005550 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005551 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005552 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005553 } else {
junyulaid91e7052020-08-28 13:44:33 +08005554 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005555 }
5556 }
5557 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005558
James Mattis02220e22021-03-13 19:27:21 -08005559 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5560 @Override
5561 public void onReceive(Context context, Intent intent) {
5562 ensureRunningOnConnectivityServiceThread();
5563 switch (intent.getAction()) {
5564 case Intent.ACTION_PACKAGE_ADDED:
5565 case Intent.ACTION_PACKAGE_REMOVED:
5566 case Intent.ACTION_PACKAGE_REPLACED:
5567 onPackageChanged(intent.getData().getSchemeSpecificPart());
5568 break;
5569 default:
5570 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5571 }
5572 }
5573 };
5574
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005575 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005576 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005577
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005578 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005579 public final String name;
5580 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005581 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005582 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005583
lifraf3a3492021-03-10 13:58:14 +08005584 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5585 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005586 this.name = name;
5587 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005588 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005589 mDeathRecipient = deathRecipient;
5590
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005591 if (mDeathRecipient == null) {
5592 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005593 }
5594 }
5595
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005596 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005597 try {
5598 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5599 } catch (RemoteException e) {
5600 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005601 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005602 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005603 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005604
James Mattis4fce5d12020-11-12 15:53:42 -08005605 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5606 for (int i = 0; i < requests.size(); i++) {
5607 ensureNetworkRequestHasType(requests.get(i));
5608 }
5609 }
5610
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005611 private void ensureNetworkRequestHasType(NetworkRequest request) {
5612 if (request.type == NetworkRequest.Type.NONE) {
5613 throw new IllegalArgumentException(
5614 "All NetworkRequests in ConnectivityService must have a type");
5615 }
5616 }
5617
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005618 /**
5619 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005620 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005621 */
James Mattis258ea3c2020-11-15 15:04:40 -08005622 @VisibleForTesting
5623 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005624 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5625 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005626 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005627
James Mattisa076c532020-12-02 14:12:41 -08005628 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5629 void setSatisfier(
5630 @Nullable final NetworkAgentInfo satisfier,
5631 @Nullable final NetworkRequest activeRequest) {
5632 mSatisfier = satisfier;
5633 mActiveRequest = activeRequest;
5634 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005635
James Mattisd31bdfa2020-12-23 16:37:26 -08005636 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005637 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005638 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005639 private NetworkAgentInfo mSatisfier;
5640 NetworkAgentInfo getSatisfier() {
5641 return mSatisfier;
5642 }
5643
5644 // The request in mRequests assigned to a network agent. This is null if none of the
5645 // requests in mRequests can be satisfied. This member has the constraint of only being
5646 // accessible on the handler thread.
5647 @Nullable
5648 private NetworkRequest mActiveRequest;
5649 NetworkRequest getActiveRequest() {
5650 return mActiveRequest;
5651 }
5652
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005653 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005654 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005655 @Nullable
5656 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005657
5658 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005659 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005660 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005661 final int mPid;
5662 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005663 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005664 @Nullable
5665 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005666
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005667 // Counter keeping track of this NRI.
5668 final PerUidCounter mPerUidCounter;
5669
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005670 // Effective UID of this request. This is different from mUid when a privileged process
5671 // files a request on behalf of another UID. This UID is used to determine blocked status,
5672 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5673 // maximum limit of registered callbacks per UID.
5674 final int mAsUid;
5675
paulhue9913722021-05-26 15:19:20 +08005676 // Default network priority of this request.
5677 private final int mDefaultNetworkPriority;
5678
5679 int getDefaultNetworkPriority() {
5680 return mDefaultNetworkPriority;
5681 }
5682
James Mattis3ce3d3c2021-02-09 18:18:28 -08005683 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5684 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5685 // maintained for keying off of. This is only a concern when the original nri
5686 // mNetworkRequests changes which happens currently for apps that register callbacks to
5687 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5688 // that match the per-app default nri that currently tracks the calling app's uid so that
5689 // callbacks are fired at the appropriate time. When the callbacks fire,
5690 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5691 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5692 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5693 @NonNull
5694 private final NetworkRequest mNetworkRequestForCallback;
5695 NetworkRequest getNetworkRequestForCallback() {
5696 return mNetworkRequestForCallback;
5697 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005698
James Mattisd31bdfa2020-12-23 16:37:26 -08005699 /**
5700 * Get the list of UIDs this nri applies to.
5701 */
5702 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005703 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005704 // networkCapabilities.getUids() returns a defensive copy.
5705 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005706 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5707 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005708 }
5709
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005710 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5711 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005712 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
5713 DEFAULT_NETWORK_PRIORITY_NONE);
James Mattis45d81842021-01-10 14:24:24 -08005714 }
5715
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005716 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005717 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhue9913722021-05-26 15:19:20 +08005718 @Nullable String callingAttributionTag, final int defaultNetworkPriority) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005719 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005720 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005721 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005722 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005723 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005724 mBinder = null;
5725 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005726 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005727 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005728 mPerUidCounter = getRequestCounter(this);
5729 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005730 /**
5731 * Location sensitive data not included in pending intent. Only included in
5732 * {@link NetworkCallback}.
5733 */
5734 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005735 mCallingAttributionTag = callingAttributionTag;
paulhue9913722021-05-26 15:19:20 +08005736 mDefaultNetworkPriority = defaultNetworkPriority;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005737 }
5738
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005739 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005740 @Nullable final IBinder binder,
5741 @NetworkCallback.Flag int callbackFlags,
5742 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005743 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5744 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005745 }
5746
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005747 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005748 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005749 @Nullable final IBinder binder,
5750 @NetworkCallback.Flag int callbackFlags,
5751 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005752 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005753 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005754 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005755 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005756 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005757 mBinder = binder;
5758 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005759 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005760 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005761 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005762 mPerUidCounter = getRequestCounter(this);
5763 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005764 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005765 mCallingAttributionTag = callingAttributionTag;
paulhue9913722021-05-26 15:19:20 +08005766 mDefaultNetworkPriority = DEFAULT_NETWORK_PRIORITY_NONE;
James Mattisb1392002021-03-31 13:57:52 -07005767 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005768 }
5769
James Mattis3ce3d3c2021-02-09 18:18:28 -08005770 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5771 @NonNull final List<NetworkRequest> r) {
5772 super();
5773 ensureAllNetworkRequestsHaveType(r);
5774 mRequests = initializeRequests(r);
5775 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005776 final NetworkAgentInfo satisfier = nri.getSatisfier();
5777 if (null != satisfier) {
5778 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5779 // The active request is necessary to figure out what callbacks to send, in
5780 // particular then a network updates its capabilities.
5781 // As this code creates a new NRI with a new set of requests, figure out which of
5782 // the list of requests should be the active request. It is always the first
5783 // request of the list that can be satisfied by the satisfier since the order of
5784 // requests is a priority order.
5785 // Note even in the presence of a satisfier there may not be an active request,
5786 // when the satisfier is the no-service network.
5787 NetworkRequest activeRequest = null;
5788 for (final NetworkRequest candidate : r) {
5789 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5790 activeRequest = candidate;
5791 break;
5792 }
5793 }
5794 setSatisfier(satisfier, activeRequest);
5795 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005796 mMessenger = nri.mMessenger;
5797 mBinder = nri.mBinder;
5798 mPid = nri.mPid;
5799 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005800 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005801 mPendingIntent = nri.mPendingIntent;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005802 mPerUidCounter = getRequestCounter(this);
5803 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005804 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005805 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhue9913722021-05-26 15:19:20 +08005806 mDefaultNetworkPriority = DEFAULT_NETWORK_PRIORITY_NONE;
James Mattisb1392002021-03-31 13:57:52 -07005807 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005808 }
5809
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005810 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhue9913722021-05-26 15:19:20 +08005811 this(asUid, Collections.singletonList(r), DEFAULT_NETWORK_PRIORITY_NONE);
James Mattis45d81842021-01-10 14:24:24 -08005812 }
5813
paulhue9913722021-05-26 15:19:20 +08005814 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5815 final int defaultNetworkPriority) {
5816 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
5817 defaultNetworkPriority);
Cody Kesting73708bf2019-12-18 10:57:50 -08005818 }
5819
James Mattis2516da32021-01-31 17:06:19 -08005820 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5821 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5822 // false.
5823 boolean isBeingSatisfied() {
5824 return (null != mSatisfier && null != mActiveRequest);
5825 }
5826
James Mattis3d229892020-11-16 16:46:28 -08005827 boolean isMultilayerRequest() {
5828 return mRequests.size() > 1;
5829 }
5830
James Mattis45d81842021-01-10 14:24:24 -08005831 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5832 // Creating a defensive copy to prevent the sender from modifying the list being
5833 // reflected in the return value of this method.
5834 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08005835 return Collections.unmodifiableList(tempRequests);
5836 }
5837
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005838 void decrementRequestCount() {
5839 mPerUidCounter.decrementCount(mUid);
5840 }
5841
James Mattisb1392002021-03-31 13:57:52 -07005842 void linkDeathRecipient() {
5843 if (null != mBinder) {
5844 try {
5845 mBinder.linkToDeath(this, 0);
5846 } catch (RemoteException e) {
5847 binderDied();
5848 }
5849 }
5850 }
5851
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005852 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07005853 if (null != mBinder) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005854 mBinder.unlinkToDeath(this, 0);
5855 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005856 }
5857
James Mattis4fce5d12020-11-12 15:53:42 -08005858 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005859 public void binderDied() {
5860 log("ConnectivityService NetworkRequestInfo binderDied(" +
James Mattis4fce5d12020-11-12 15:53:42 -08005861 mRequests + ", " + mBinder + ")");
James Mattisa152f882020-11-20 16:08:10 -08005862 releaseNetworkRequests(mRequests);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005863 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005864
James Mattis4fce5d12020-11-12 15:53:42 -08005865 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005866 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005867 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5868 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08005869 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005870 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005871 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08005872 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08005873 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
Roshan Piuse1220262021-03-11 21:16:44 -08005874 + " callback flags: " + mCallbackFlags;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005875 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005876 }
5877
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09005878 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5879 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5880 if (badCapability != null) {
5881 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04005882 }
5883 }
5884
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005885 // This checks that the passed capabilities either do not request a
5886 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005887 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08005888 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09005889 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005890 throw new SecurityException("Insufficient permissions to request a specific SSID");
5891 }
paulhu1a407652019-03-22 16:35:06 +08005892
5893 if (nc.hasSignalStrength()
5894 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5895 throw new SecurityException(
5896 "Insufficient permissions to request a specific signal strength");
5897 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08005898 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07005899
junyulai2217bec2021-04-14 23:33:31 +08005900 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07005901 enforceNetworkFactoryPermission();
5902 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09005903 }
5904
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005905 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005906 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005907 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08005908 // mNetworkRequests may contain the same value multiple times in case of
5909 // multilayer requests. It won't matter in this case because the thresholds
5910 // will then be the same and be deduplicated as they enter the `thresholds` set.
5911 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08005912 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5913 for (final NetworkRequest req : nri.mRequests) {
5914 if (req.networkCapabilities.hasSignalStrength()
5915 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5916 thresholds.add(req.networkCapabilities.getSignalStrength());
5917 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005918 }
5919 }
5920 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005921 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005922 }
5923
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005924 private void updateSignalStrengthThresholds(
5925 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005926 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005927
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09005928 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005929 String detail;
5930 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5931 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5932 } else {
5933 detail = reason;
5934 }
5935 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005936 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09005937 }
5938
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005939 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005940 }
5941
Etan Cohen1b6d4182017-04-03 17:42:34 -07005942 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5943 if (nc == null) {
5944 return;
5945 }
5946 NetworkSpecifier ns = nc.getNetworkSpecifier();
5947 if (ns == null) {
5948 return;
5949 }
lucaslin22f9b9f2021-01-22 15:15:23 +08005950 if (ns instanceof MatchAllNetworkSpecifier) {
5951 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5952 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07005953 }
5954
lucasline117e2e2019-10-22 18:27:33 +08005955 private void ensureValid(NetworkCapabilities nc) {
5956 ensureValidNetworkSpecifier(nc);
5957 if (nc.isPrivateDnsBroken()) {
5958 throw new IllegalArgumentException("Can't request broken private DNS");
5959 }
5960 }
5961
Roshan Pius951c0032020-12-22 15:10:42 -08005962 private boolean isTargetSdkAtleast(int version, int callingUid,
5963 @NonNull String callingPackageName) {
5964 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08005965 final PackageManager pm =
5966 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08005967 try {
Roshan Pius951c0032020-12-22 15:10:42 -08005968 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08005969 if (callingVersion < version) return false;
5970 } catch (PackageManager.NameNotFoundException e) { }
5971 return true;
5972 }
5973
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005974 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005975 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
junyulaiad010792021-01-11 16:53:38 +08005976 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08005977 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08005978 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08005979 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08005980 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5981 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08005982 throw new SecurityException("Insufficient permissions to specify legacy type");
5983 }
markchienfac84a22020-03-18 21:16:15 +08005984 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09005985 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005986 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09005987 // Privileged callers can track the default network of another UID by passing in a UID.
5988 if (asUid != Process.INVALID_UID) {
5989 enforceSettingsPermission();
5990 } else {
5991 asUid = callingUid;
5992 }
junyulaiad010792021-01-11 16:53:38 +08005993 final NetworkRequest.Type reqType;
5994 try {
5995 reqType = NetworkRequest.Type.values()[reqTypeInt];
5996 } catch (ArrayIndexOutOfBoundsException e) {
5997 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5998 }
5999 switch (reqType) {
6000 case TRACK_DEFAULT:
6001 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006002 // is unused and will be replaced by ones appropriate for the UID (usually, the
6003 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006004 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006005 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006006 enforceAccessPermission();
6007 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006008 case TRACK_SYSTEM_DEFAULT:
6009 enforceSettingsPermission();
6010 networkCapabilities = new NetworkCapabilities(defaultNc);
6011 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006012 case BACKGROUND_REQUEST:
6013 enforceNetworkStackOrSettingsPermission();
6014 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006015 case REQUEST:
6016 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6017 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6018 callingAttributionTag);
6019 // TODO: this is incorrect. We mark the request as metered or not depending on
6020 // the state of the app when the request is filed, but we never change the
6021 // request if the app changes network state. http://b/29964605
6022 enforceMeteredApnPolicy(networkCapabilities);
6023 break;
junyulai1b1c8742021-03-12 20:05:08 +08006024 case LISTEN_FOR_BEST:
6025 enforceAccessPermission();
6026 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6027 break;
junyulaiad010792021-01-11 16:53:38 +08006028 default:
6029 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006030 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006031 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006032 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006033 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006034
junyulai1b1c8742021-03-12 20:05:08 +08006035 // Enforce FOREGROUND if the caller does not have permission to use background network.
6036 if (reqType == LISTEN_FOR_BEST) {
6037 restrictBackgroundRequestForCaller(networkCapabilities);
6038 }
6039
6040 // Set the UID range for this request to the single UID of the requester, unless the
6041 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006042 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6043 // are no visible methods to set the UIDs, an app could use reflection to try and get
6044 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006045 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006046 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6047 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006048
Etan Cohen85000162017-02-05 10:42:27 -08006049 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006050 throw new IllegalArgumentException("Bad timeout specified");
6051 }
lucasline117e2e2019-10-22 18:27:33 +08006052 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08006053
James Mattis3ce3d3c2021-02-09 18:18:28 -08006054 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006055 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006056 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006057 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006058 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006059 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006060
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006061 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6062 // copied from the default request above. (This is necessary to ensure, for example, that
6063 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6064 // changes don't alter request matching.
6065 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6066 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006067 throw new IllegalStateException(
6068 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006069 + networkCapabilities + " vs. " + defaultNc);
6070 }
6071
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006072 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006073 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006074 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006075 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006076 }
6077 return networkRequest;
6078 }
6079
James Mattis3ce3d3c2021-02-09 18:18:28 -08006080 /**
6081 * Return the nri to be used when registering a network request. Specifically, this is used with
6082 * requests registered to track the default request. If there is currently a per-app default
6083 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6084 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006085 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6086 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006087 * @param nr the network request for the nri.
6088 * @param msgr the messenger for the nri.
6089 * @param binder the binder for the nri.
6090 * @param callingAttributionTag the calling attribution tag for the nri.
6091 * @return the nri to register.
6092 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006093 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006094 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006095 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006096 @Nullable String callingAttributionTag) {
6097 final List<NetworkRequest> requests;
6098 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6099 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006100 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006101 } else {
6102 requests = Collections.singletonList(nr);
6103 }
Roshan Pius951c0032020-12-22 15:10:42 -08006104 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006105 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006106 }
6107
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006108 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6109 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006110 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006111 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006112 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006113 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006114 }
6115 }
6116
fenglu3f357402015-03-20 11:29:56 -07006117 @Override
fenglub00f4882015-04-21 17:12:05 -07006118 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006119 enforceAccessPermission();
6120 NetworkAgentInfo nai = null;
6121 if (network == null) {
6122 return false;
6123 }
6124 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006125 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006126 }
6127 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006128 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006129 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006130 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006131 Integer uidReqs = mBandwidthRequests.get(uid);
6132 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006133 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006134 }
6135 mBandwidthRequests.put(uid, ++uidReqs);
6136 }
fenglu3f357402015-03-20 11:29:56 -07006137 return true;
6138 }
6139 return false;
6140 }
6141
Felipe Leme0a5ae422016-06-20 16:36:29 -07006142 private boolean isSystem(int uid) {
6143 return uid < Process.FIRST_APPLICATION_UID;
6144 }
fenglu3f357402015-03-20 11:29:56 -07006145
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006146 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006147 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006148 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006149 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006150 return;
6151 }
Hugo Benichi39621362017-02-11 17:04:43 +09006152 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6153 // Policy already enforced.
6154 return;
6155 }
paulhuaf50d7d2020-12-24 19:47:34 +08006156 final long ident = Binder.clearCallingIdentity();
6157 try {
6158 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6159 // If UID is restricted, don't allow them to bring up metered APNs.
6160 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6161 }
6162 } finally {
6163 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006164 }
6165 }
6166
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006167 @Override
6168 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006169 PendingIntent operation, @NonNull String callingPackageName,
6170 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006171 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006172 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006173 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006174 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6175 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006176 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006177 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006178 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006179 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006180 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006181 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6182 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006183
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006184 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006185 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006186 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6187 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006188 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006189 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6190 nri));
6191 return networkRequest;
6192 }
6193
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006194 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6195 mHandler.sendMessageDelayed(
6196 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006197 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006198 }
6199
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006200 @Override
6201 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006202 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006203 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006204 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006205 }
6206
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006207 // In order to implement the compatibility measure for pre-M apps that call
6208 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6209 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6210 // This ensures it has permission to do so.
6211 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6212 if (nc == null) {
6213 return false;
6214 }
6215 int[] transportTypes = nc.getTransportTypes();
6216 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6217 return false;
6218 }
6219 try {
6220 mContext.enforceCallingOrSelfPermission(
6221 android.Manifest.permission.ACCESS_WIFI_STATE,
6222 "ConnectivityService");
6223 } catch (SecurityException e) {
6224 return false;
6225 }
6226 return true;
6227 }
6228
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006229 @Override
6230 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006231 Messenger messenger, IBinder binder,
6232 @NetworkCallback.Flag int callbackFlags,
6233 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006234 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006235 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6236 enforceAccessPermission();
6237 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006238
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006239 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006240 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006241 Binder.getCallingPid(), callingUid, callingPackageName);
6242 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006243 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6244 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6245 // onLost and onAvailable callbacks when networks move in and out of the background.
6246 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6247 // can't request networks.
6248 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006249 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006250
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006251 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006252 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006253 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006254 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006255 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006256 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006257
6258 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6259 return networkRequest;
6260 }
6261
6262 @Override
6263 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006264 PendingIntent operation, @NonNull String callingPackageName,
6265 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006266 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006267 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006268 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6269 enforceAccessPermission();
6270 }
lucasline117e2e2019-10-22 18:27:33 +08006271 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006272 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006273 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006274 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006275 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006276
6277 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006278 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006279 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6280 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006281 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006282
6283 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006284 }
6285
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006286 /** Returns the next Network provider ID. */
6287 public final int nextNetworkProviderId() {
6288 return mNextNetworkProviderId.getAndIncrement();
6289 }
6290
James Mattisa152f882020-11-20 16:08:10 -08006291 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
James Mattis4fce5d12020-11-12 15:53:42 -08006292 for (int i = 0; i < networkRequests.size(); i++) {
6293 releaseNetworkRequest(networkRequests.get(i));
6294 }
6295 }
6296
Erik Kline0c04b742016-07-07 16:50:58 +09006297 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006298 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006299 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006300 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006301 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006302 }
6303
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006304 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6305 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006306 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6307 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6308 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006309 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006310 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006311 return;
6312 }
6313
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006314 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6315 mNetworkProviderInfos.put(npi.messenger, npi);
6316 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006317 }
6318
6319 @Override
6320 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006321 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006322 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006323 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006324 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006325 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6326 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006327 }
6328
6329 @Override
6330 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006331 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006332 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006333 }
6334
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006335 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006336 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006337 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6338 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006339 Objects.requireNonNull(score);
6340 Objects.requireNonNull(caps);
6341 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006342 final NetworkOffer offer = new NetworkOffer(
Chalard Jean30689b82021-03-22 22:44:02 +09006343 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006344 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6345 }
6346
6347 @Override
6348 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6349 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6350 }
6351
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006352 private void handleUnregisterNetworkProvider(Messenger messenger) {
6353 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6354 if (npi == null) {
6355 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006356 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006357 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006358 // Unregister all the offers from this provider
6359 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6360 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006361 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006362 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6363 toRemove.add(noi);
6364 }
6365 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006366 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006367 handleUnregisterNetworkOffer(noi);
6368 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006369 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006370 }
6371
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006372 @Override
James Mattisf7027322020-12-13 16:28:14 -08006373 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006374 if (request.hasTransport(TRANSPORT_TEST)) {
6375 enforceNetworkFactoryOrTestNetworksPermission();
6376 } else {
6377 enforceNetworkFactoryPermission();
6378 }
James Mattisf7027322020-12-13 16:28:14 -08006379 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6380 if (nri != null) {
6381 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6382 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6383 mHandler.post(() -> handleReleaseNetworkRequest(
6384 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6385 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006386 }
6387
Paul Jensen1f567382015-02-13 14:18:39 -05006388 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6389 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006390 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006391 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006392 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006393 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006394 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006395
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006396 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006397 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006398 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006399
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006400 // UID ranges for users that are currently blocked by VPNs.
6401 // This array is accessed and iterated on multiple threads without holding locks, so its
6402 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6403 // (on the handler thread).
6404 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6405
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006406 // Must only be accessed on the handler thread
6407 @NonNull
6408 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6409
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006410 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006411 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006412
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006413 // Current OEM network preferences. This object must only be written to on the handler thread.
6414 // Since it is immutable and always non-null, other threads may read it if they only care
6415 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006416 @NonNull
6417 private OemNetworkPreferences mOemNetworkPreferences =
6418 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006419 // Current per-profile network preferences. This object follows the same threading rules as
6420 // the OEM network preferences above.
6421 @NonNull
6422 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
James Mattis45d81842021-01-10 14:24:24 -08006423
paulhu51f77dc2021-06-07 02:34:20 +00006424 // A set of UIDs that should use mobile data preferentially if available. This object follows
6425 // the same threading rules as the OEM network preferences above.
6426 @NonNull
6427 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6428
James Mattiscb1e0362021-04-06 17:07:42 -07006429 // OemNetworkPreferences activity String log entries.
6430 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6431 @NonNull
6432 private final LocalLog mOemNetworkPreferencesLogs =
6433 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6434
James Mattis02220e22021-03-13 19:27:21 -08006435 /**
6436 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6437 * @param packageName the package name to check existence of a mapping for.
6438 * @return true if a mapping exists, false otherwise
6439 */
6440 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6441 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6442 }
6443
James Mattise3ef1912020-12-20 11:09:58 -08006444 // The always-on request for an Internet-capable network that apps without a specific default
6445 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006446 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006447 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006448 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006449 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006450 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006451 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006452 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006453
James Mattisd31bdfa2020-12-23 16:37:26 -08006454 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6455 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6456 }
6457
6458 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006459 * Return the default network request currently tracking the given uid.
6460 * @param uid the uid to check.
6461 * @return the NetworkRequestInfo tracking the given uid.
6462 */
6463 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006464 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006465 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6466 if (nri == mDefaultRequest) {
6467 continue;
6468 }
6469 // Checking the first request is sufficient as only multilayer requests will have more
6470 // than one request and for multilayer, all requests will track the same uids.
6471 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6472 return nri;
6473 }
6474 }
6475 return mDefaultRequest;
6476 }
6477
6478 /**
6479 * Get a copy of the network requests of the default request that is currently tracking the
6480 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006481 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6482 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006483 * @param requestorUid the uid to check the default for.
6484 * @param requestorPackageName the requestor's package name.
6485 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6486 */
6487 @NonNull
6488 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006489 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006490 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006491 getDefaultRequestTrackingUid(asUid).mRequests,
6492 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006493 }
6494
6495 /**
6496 * Copy the given nri's NetworkRequest collection.
6497 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006498 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6499 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006500 * @param requestorUid the uid to set on the copied collection.
6501 * @param requestorPackageName the package name to set on the copied collection.
6502 * @return the copied NetworkRequest collection.
6503 */
6504 @NonNull
6505 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006506 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6507 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006508 final List<NetworkRequest> requests = new ArrayList<>();
6509 for (final NetworkRequest nr : requestsToCopy) {
6510 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006511 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006512 nr.legacyType, nextNetworkRequestId(), nr.type));
6513 }
6514 return requests;
6515 }
6516
6517 @NonNull
6518 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006519 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6520 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006521 // These capabilities are for a TRACK_DEFAULT callback, so:
6522 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6523 // mDefaultRequest and a per-UID default request.
6524 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006525 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006526 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006527 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6528 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006529 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006530 restrictRequestUidsForCallerAndSetRequestorInfo(
6531 netCap, requestorUid, requestorPackageName);
6532 return netCap;
6533 }
6534
6535 /**
6536 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6537 * @param nr the network request to check for equality against.
6538 * @return the nri if one exists, null otherwise.
6539 */
6540 @Nullable
6541 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6542 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6543 if (nri.getNetworkRequestForCallback().equals(nr)) {
6544 return nri;
6545 }
6546 }
6547 return null;
6548 }
6549
6550 /**
6551 * Check if an nri is currently being managed by per-app default networking.
6552 * @param nri the nri to check.
6553 * @return true if this nri is currently being managed by per-app default networking.
6554 */
6555 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6556 // nri.mRequests.get(0) is only different from the original request filed in
6557 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6558 // functionality therefore if these two don't match, it means this particular nri is
6559 // currently being managed by a per-app default.
6560 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6561 }
6562
6563 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006564 * Determine if an nri is a managed default request that disallows default networking.
6565 * @param nri the request to evaluate
6566 * @return true if device-default networking is disallowed
6567 */
6568 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6569 // Check if this nri is a managed default that supports the default network at its
6570 // lowest priority request.
6571 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6572 final NetworkCapabilities lowestPriorityNetCap =
6573 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6574 return isPerAppDefaultRequest(nri)
6575 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6576 lowestPriorityNetCap));
6577 }
6578
Erik Kline05f2b402015-04-30 12:58:40 +09006579 // Request used to optionally keep mobile data active even when higher
6580 // priority networks like Wi-Fi are active.
6581 private final NetworkRequest mDefaultMobileDataRequest;
6582
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006583 // Request used to optionally keep wifi data active even when higher
6584 // priority networks like ethernet are active.
6585 private final NetworkRequest mDefaultWifiRequest;
6586
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006587 // Request used to optionally keep vehicle internal network always active
6588 private final NetworkRequest mDefaultVehicleRequest;
6589
James Mattisd31bdfa2020-12-23 16:37:26 -08006590 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6591 // network with no service. This NAI should never be matched against, nor should any public API
6592 // ever return the associated network. For this reason, this NAI is not in the list of available
6593 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6594 // default requests that don't support using the device default network which will ultimately
6595 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6596 @VisibleForTesting
6597 final NetworkAgentInfo mNoServiceNetwork;
6598
Chalard Jean5b409c72021-02-04 13:12:59 +09006599 // The NetworkAgentInfo currently satisfying the default request, if any.
6600 private NetworkAgentInfo getDefaultNetwork() {
6601 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006602 }
6603
James Mattis2516da32021-01-31 17:06:19 -08006604 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6605 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6606 // Currently, all network requests will have the same uids therefore checking the first
6607 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006608 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006609 if (null == uids) {
6610 continue;
6611 }
6612 for (final UidRange range : uids) {
6613 if (range.contains(uid)) {
6614 return nri.getSatisfier();
6615 }
6616 }
6617 }
6618 return getDefaultNetwork();
6619 }
6620
Varun Ananddf569952019-02-06 10:13:38 -08006621 @Nullable
6622 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6623 return nai != null ? nai.network : null;
6624 }
6625
6626 private void ensureRunningOnConnectivityServiceThread() {
6627 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6628 throw new IllegalStateException(
6629 "Not running on ConnectivityService thread: "
6630 + Thread.currentThread().getName());
6631 }
6632 }
6633
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006634 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006635 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6636 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006637 }
6638
Chalard Jean29d06db2018-05-02 21:14:54 +09006639 /**
6640 * Register a new agent with ConnectivityService to handle a network.
6641 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006642 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006643 * @param networkInfo the initial info associated with this network. It can be updated later :
6644 * see {@link #updateNetworkInfo}.
6645 * @param linkProperties the initial link properties of this network. They can be updated
6646 * later : see {@link #updateLinkProperties}.
6647 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006648 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006649 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006650 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006651 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006652 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006653 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006654 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006655 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006656 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006657 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6658 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006659 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6660 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6661 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006662 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006663 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006664 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6665 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006666 } else {
6667 enforceNetworkFactoryPermission();
6668 }
6669
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006670 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006671 final long token = Binder.clearCallingIdentity();
6672 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006673 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006674 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006675 } finally {
6676 Binder.restoreCallingIdentity(token);
6677 }
6678 }
6679
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006680 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006681 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006682 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6683 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006684 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006685 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6686 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6687 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6688 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006689 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006690 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006691
Rubin Xuffd77d82017-09-05 18:40:49 +01006692 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006693
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006694 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006695 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006696 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006697 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09006698 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6699 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006700
6701 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006702 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006703 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006704 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6705
Chalard Jeanf2da1772018-04-26 16:16:10 +09006706 final String extraInfo = networkInfo.getExtraInfo();
6707 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006708 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006709 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006710 mDeps.getNetworkStack().makeNetworkMonitor(
6711 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006712 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6713 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006714 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006715 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006716 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006717 }
6718
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006719 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6720 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006721 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006722 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006723 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006724 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006725 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006726
6727 try {
6728 networkMonitor.start();
6729 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006730 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006731 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006732 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006733 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006734 updateNetworkInfo(nai, networkInfo);
6735 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006736 }
6737
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006738 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6739 @NonNull public final NetworkOffer offer;
6740
6741 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6742 this.offer = offer;
6743 }
6744
6745 @Override
6746 public void binderDied() {
6747 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6748 }
6749 }
6750
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006751 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6752 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6753 if (npi.providerId == providerId) return true;
6754 }
6755 return false;
6756 }
6757
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006758 /**
6759 * Register or update a network offer.
6760 * @param newOffer The new offer. If the callback member is the same as an existing
6761 * offer, it is an update of that offer.
6762 */
6763 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6764 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006765 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006766 // This may actually happen if a provider updates its score or registers and then
6767 // immediately unregisters. The offer would still be in the handler queue, but the
6768 // provider would have been removed.
6769 if (DBG) log("Received offer from an unregistered provider");
6770 return;
6771 }
6772
6773 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6774 if (null != existingOffer) {
6775 handleUnregisterNetworkOffer(existingOffer);
6776 newOffer.migrateFrom(existingOffer.offer);
6777 }
6778 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6779 try {
Chalard Jean30689b82021-03-22 22:44:02 +09006780 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006781 } catch (RemoteException e) {
6782 noi.binderDied();
6783 return;
6784 }
6785 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09006786 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006787 }
6788
6789 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6790 ensureRunningOnConnectivityServiceThread();
6791 mNetworkOffers.remove(noi);
Chalard Jean30689b82021-03-22 22:44:02 +09006792 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006793 }
6794
6795 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6796 @NonNull final INetworkOfferCallback callback) {
6797 ensureRunningOnConnectivityServiceThread();
6798 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09006799 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006800 }
6801 return null;
6802 }
6803
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006804 /**
6805 * Called when receiving LinkProperties directly from a NetworkAgent.
6806 * Stores into |nai| any data coming from the agent that might also be written to the network's
6807 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6808 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09006809 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006810 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006811 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6812 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09006813 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08006814 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006815 }
6816
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006817 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006818 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006819 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006820
Lorenzo Colittid523d142020-04-01 20:16:30 +09006821 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6822 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6823 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09006824 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09006825
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006826 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00006827
6828 // update filtering rules, need to happen after the interface update so netd knows about the
6829 // new interface (the interface name -> index map becomes initialized)
6830 updateVpnFiltering(newLp, oldLp, networkAgent);
6831
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006832 updateMtu(newLp, oldLp);
6833 // TODO - figure out what to do for clat
6834// for (LinkProperties lp : newLp.getStackedLinks()) {
6835// updateMtu(lp, null);
6836// }
Chalard Jean5b409c72021-02-04 13:12:59 +09006837 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08006838 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6839 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09006840
Erik Klineb9888902016-04-05 13:30:49 +09006841 updateRoutes(newLp, oldLp, netId);
6842 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05006843 // Make sure LinkProperties represents the latest private DNS status.
6844 // This does not need to be done before updateDnses because the
6845 // LinkProperties are not the source of the private DNS configuration.
6846 // updateDnses will fetch the private DNS configuration from DnsManager.
6847 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09006848
Chalard Jean5b409c72021-02-04 13:12:59 +09006849 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05006850 handleApplyDefaultProxy(newLp.getHttpProxy());
6851 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006852 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05006853 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02006854
6855 updateWakeOnLan(newLp);
6856
Hai Shalome58bdc62021-01-11 18:45:34 -08006857 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6858 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6859 // does, it needs to be merged here.
6860 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6861 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09006862
Robert Greenwalte525a0a2014-09-30 16:50:07 -07006863 // TODO - move this check to cover the whole function
6864 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09006865 synchronized (networkAgent) {
6866 networkAgent.linkProperties = newLp;
6867 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09006868 // Start or stop DNS64 detection and 464xlat according to network state.
6869 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08006870 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09006871 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6872 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08006873 if (networkAgent.everConnected) {
6874 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6875 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07006876 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006877
6878 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04006879 }
6880
Hai Shalome58bdc62021-01-11 18:45:34 -08006881 /**
6882 * @param naData captive portal data from NetworkAgent
6883 * @param apiData captive portal data from capport API
6884 */
6885 @Nullable
6886 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6887 CaptivePortalData apiData) {
6888 if (naData == null || apiData == null) {
6889 return naData == null ? apiData : naData;
6890 }
6891 final CaptivePortalData.Builder captivePortalBuilder =
6892 new CaptivePortalData.Builder(naData);
6893
6894 if (apiData.isCaptive()) {
6895 captivePortalBuilder.setCaptive(true);
6896 }
6897 if (apiData.isSessionExtendable()) {
6898 captivePortalBuilder.setSessionExtendable(true);
6899 }
6900 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6901 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6902 // otherwise data would be inconsistent. Prefer the capport API info if present,
6903 // as it can generally be refreshed more often.
6904 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6905 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6906 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6907 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6908 // No source has time / bytes remaining information: surface the newest refresh time
6909 // for other fields
6910 captivePortalBuilder.setRefreshTime(
6911 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6912 }
6913
Hai Shalom7c6ab402021-02-04 19:34:06 -08006914 // Prioritize the user portal URL from the network agent if the source is authenticated.
6915 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6916 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6917 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6918 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08006919 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08006920 // Prioritize the venue information URL from the network agent if the source is
6921 // authenticated.
6922 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6923 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6924 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6925 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08006926 }
6927 return captivePortalBuilder.build();
6928 }
6929
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006930 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09006931 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09006932 // marks on unsupported interfaces is harmless.
6933 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6934 return;
6935 }
Joel Scherpelza235a812017-05-22 13:47:41 +09006936
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006937 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6938 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6939
6940 // TODO (b/183076074): remove legacy fallback after migrating overlays
6941 final int legacyMark = mContext.getResources().getInteger(mContext.getResources()
6942 .getIdentifier("config_networkWakeupPacketMark", "integer", "android"));
6943 final int legacyMask = mContext.getResources().getInteger(mContext.getResources()
6944 .getIdentifier("config_networkWakeupPacketMask", "integer", "android"));
6945 mark = mark == 0 ? legacyMark : mark;
6946 mask = mask == 0 ? legacyMask : mask;
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006947
6948 // Mask/mark of zero will not detect anything interesting.
6949 // Don't install rules unless both values are nonzero.
6950 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09006951 return;
6952 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006953
6954 final String prefix = "iface:" + iface;
6955 try {
6956 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08006957 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006958 } else {
Luke Huang46289a22018-09-27 19:33:11 +08006959 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006960 }
6961 } catch (Exception e) {
6962 loge("Exception modifying wakeup packet monitoring: " + e);
6963 }
6964
Joel Scherpelza235a812017-05-22 13:47:41 +09006965 }
6966
Chalard Jean9589e722019-11-19 19:03:53 +09006967 private void updateInterfaces(final @Nullable LinkProperties newLp,
6968 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09006969 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09006970 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01006971 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6972 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09006973 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09006974 for (final String iface : interfaceDiff.added) {
6975 try {
6976 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08006977 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09006978 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08006979 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6980 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09006981 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08006982 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09006983 }
Paul Jensenbff73492014-04-28 10:33:11 -04006984 }
6985 }
Chalard Jean9589e722019-11-19 19:03:53 +09006986 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04006987 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006988 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09006989 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08006990 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04006991 } catch (Exception e) {
6992 loge("Exception removing interface: " + e);
6993 }
6994 }
6995 }
6996
Tyler Weare4314862019-12-05 14:55:30 -08006997 // TODO: move to frameworks/libs/net.
6998 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6999 final String nextHop;
7000
7001 switch (route.getType()) {
7002 case RouteInfo.RTN_UNICAST:
7003 if (route.hasGateway()) {
7004 nextHop = route.getGateway().getHostAddress();
7005 } else {
7006 nextHop = INetd.NEXTHOP_NONE;
7007 }
7008 break;
7009 case RouteInfo.RTN_UNREACHABLE:
7010 nextHop = INetd.NEXTHOP_UNREACHABLE;
7011 break;
7012 case RouteInfo.RTN_THROW:
7013 nextHop = INetd.NEXTHOP_THROW;
7014 break;
7015 default:
7016 nextHop = INetd.NEXTHOP_NONE;
7017 break;
7018 }
7019
7020 final RouteInfoParcel rip = new RouteInfoParcel();
7021 rip.ifName = route.getInterface();
7022 rip.destination = route.getDestination().toString();
7023 rip.nextHop = nextHop;
7024 rip.mtu = route.getMtu();
7025
7026 return rip;
7027 }
7028
Paul Jensene0fd4a82014-08-06 15:51:33 -04007029 /**
7030 * Have netd update routes from oldLp to newLp.
7031 * @return true if routes changed between oldLp and newLp
7032 */
7033 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007034 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007035 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7036 new CompareOrUpdateResult<>(
7037 oldLp != null ? oldLp.getAllRoutes() : null,
7038 newLp != null ? newLp.getAllRoutes() : null,
7039 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007040
7041 // add routes before removing old in case it helps with continuous connectivity
7042
Chalard Jean9dd11612018-06-04 16:52:49 +09007043 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007044 for (RouteInfo route : routeDiff.added) {
7045 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007046 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007047 try {
Tyler Weare4314862019-12-05 14:55:30 -08007048 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007049 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007050 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007051 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007052 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007053 }
7054 }
7055 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007056 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007057 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007058 try {
Tyler Weare4314862019-12-05 14:55:30 -08007059 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007060 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007061 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007062 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007063 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007064 }
7065 }
7066
7067 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007068 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007069 try {
Tyler Weare4314862019-12-05 14:55:30 -08007070 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007071 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007072 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007073 }
7074 }
Tyler Weare4314862019-12-05 14:55:30 -08007075
7076 for (RouteInfo route : routeDiff.updated) {
7077 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7078 try {
7079 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7080 } catch (Exception e) {
7081 loge("Exception in networkUpdateRouteParcel: " + e);
7082 }
7083 }
7084 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7085 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007086 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007087
Erik Klineb9888902016-04-05 13:30:49 +09007088 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7089 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7090 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007091 }
Erik Klineb9888902016-04-05 13:30:49 +09007092
Erik Kline31b4a9e2018-01-11 21:07:29 +09007093 if (DBG) {
7094 final Collection<InetAddress> dnses = newLp.getDnsServers();
7095 log("Setting DNS servers for network " + netId + " to " + dnses);
7096 }
Erik Klineb9888902016-04-05 13:30:49 +09007097 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007098 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007099 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007100 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007101 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007102 }
Erik Kline54e35c02017-04-07 15:29:29 +09007103 }
7104
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007105 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7106 NetworkAgentInfo nai) {
7107 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7108 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7109 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7110 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7111
7112 if (!wasFiltering && !needsFiltering) {
7113 // Nothing to do.
7114 return;
7115 }
7116
7117 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7118 // Nothing changed.
7119 return;
7120 }
7121
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007122 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007123 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007124 // TODO: this create a window of opportunity for apps to receive traffic between the time
7125 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007126 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007127 // old rules are being removed.
7128 if (wasFiltering) {
7129 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7130 }
7131 if (needsFiltering) {
7132 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7133 }
7134 }
7135
Valentin Iftime9fa35092019-09-24 13:32:13 +02007136 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007137 if (mWolSupportedInterfaces == null) {
7138 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007139 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007140 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007141 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7142 }
7143
Luke Huangb913c812018-08-24 20:33:16 +08007144 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007145 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007146 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007147 }
7148 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007149 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007150 }
Luke Huangb913c812018-08-24 20:33:16 +08007151 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007152 }
7153
Chalard Jean62edfd82019-12-02 18:39:29 +09007154 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7155 @NonNull final NetworkCapabilities newNc) {
7156 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7157 final int newPermission = getNetworkPermission(newNc);
7158 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7159 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007160 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007161 } catch (RemoteException | ServiceSpecificException e) {
7162 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007163 }
7164 }
7165 }
7166
Paul Jensen53f08952015-06-16 14:27:36 -04007167 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007168 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7169 * Stores into |nai| any data coming from the agent that might also be written to the network's
7170 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7171 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007172 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007173 */
7174 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007175 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7176 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7177 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7178 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007179 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7180 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7181 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7182 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7183 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007184 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007185 }
7186
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007187 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007188 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007189 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007190 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007191 underlyingNetworks = underlyingNetworksOrDefault(
7192 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007193 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007194 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7195 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007196 // metered if any underlying is metered, or originally declared metered by the agent.
7197 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007198 boolean roaming = false; // roaming if any underlying is roaming
7199 boolean congested = false; // congested if any underlying is congested
7200 boolean suspended = true; // suspended if all underlying are suspended
7201
7202 boolean hadUnderlyingNetworks = false;
7203 if (null != underlyingNetworks) {
7204 for (Network underlyingNetwork : underlyingNetworks) {
7205 final NetworkAgentInfo underlying =
7206 getNetworkAgentInfoForNetwork(underlyingNetwork);
7207 if (underlying == null) continue;
7208
7209 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7210 hadUnderlyingNetworks = true;
7211 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007212 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007213 }
7214
7215 // Merge capabilities of this underlying network. For bandwidth, assume the
7216 // worst case.
7217 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7218 underlyingCaps.getLinkDownstreamBandwidthKbps());
7219 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7220 underlyingCaps.getLinkUpstreamBandwidthKbps());
7221 // If this underlying network is metered, the VPN is metered (it may cost money
7222 // to send packets on this network).
7223 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7224 // If this underlying network is roaming, the VPN is roaming (the billing structure
7225 // is different than the usual, local one).
7226 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7227 // If this underlying network is congested, the VPN is congested (the current
7228 // condition of the network affects the performance of this network).
7229 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7230 // If this network is not suspended, the VPN is not suspended (the VPN
7231 // is able to transfer some data).
7232 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7233 }
7234 }
7235 if (!hadUnderlyingNetworks) {
7236 // No idea what the underlying networks are; assume reasonable defaults
7237 metered = true;
7238 roaming = false;
7239 congested = false;
7240 suspended = false;
7241 }
7242
lifrade6c2a2021-03-04 14:08:08 +08007243 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007244 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7245 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7246 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7247 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7248 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7249 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007250 }
7251
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007252 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007253 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7254 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7255 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007256 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007257 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007258 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007259 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007260 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7261 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007262 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007263 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007264 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007265 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007266 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7267 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007268 // does not cause any request (that is not a listen) currently matching that agent to
7269 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007270 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007271 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007272 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007273 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007274 }
7275
Paul Jensen53f08952015-06-16 14:27:36 -04007276 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007277 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007278 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007279 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007280 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007281 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007282 }
Paul Jensende49eb12015-06-25 15:30:08 -04007283 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007284 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007285 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007286 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007287 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007288 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007289 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007290 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007291 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007292 }
lucaslin2240ef62019-03-12 13:08:03 +08007293 if (nai.partialConnectivity) {
7294 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7295 } else {
7296 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7297 }
lucasline117e2e2019-10-22 18:27:33 +08007298 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007299
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007300 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007301 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7302 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007303 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007304 }
7305
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007306 if (nai.supportsUnderlyingNetworks()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007307 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7308 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007309 }
7310
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007311 return newNc;
7312 }
7313
Lorenzo Colitti44840702021-01-11 22:27:57 +09007314 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7315 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7316 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7317 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7318 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7319 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7320 if (prevSuspended != suspended) {
7321 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7322 // onResumed have been removed.
7323 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7324 : ConnectivityManager.CALLBACK_RESUMED);
7325 }
7326 if (prevSuspended != suspended || prevRoaming != roaming) {
7327 // updateNetworkInfo will mix in the suspended info from the capabilities and
7328 // take appropriate action for the network having possibly changed state.
7329 updateNetworkInfo(nai, nai.networkInfo);
7330 }
7331 }
7332
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007333 /**
7334 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7335 *
7336 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7337 * capabilities we manage and store in {@code nai}, such as validated status and captive
7338 * portal status)
7339 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7340 * potentially triggers rematches.
7341 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7342 * change.)
7343 *
7344 * @param oldScore score of the network before any of the changes that prompted us
7345 * to call this function.
7346 * @param nai the network having its capabilities updated.
7347 * @param nc the new network capabilities.
7348 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007349 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7350 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007351 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007352 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007353 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007354 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007355
Chalard Jeanb2a49912018-01-16 18:43:05 +09007356 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007357 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007358
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007359 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007360 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7361 // the change we're processing can't affect any requests, it can only affect the listens
7362 // on this network. We might have been called by rematchNetworkAndRequests when a
7363 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007364 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007365 } else {
7366 // If the requestable capabilities have changed or the score changed, we can't have been
7367 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007368 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007369 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007370 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007371 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007372
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007373 final boolean oldMetered = prevNc.isMetered();
7374 final boolean newMetered = newNc.isMetered();
7375 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007376
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007377 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007378 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7379 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007380 }
junyulaif2c67e42018-08-07 19:50:45 +08007381
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007382 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7383 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007384
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007385 // Report changes that are interesting for network statistics tracking.
7386 if (meteredChanged || roamingChanged) {
7387 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007388 }
7389
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007390 // This network might have been underlying another network. Propagate its capabilities.
7391 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007392
7393 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007394 mDnsManager.updateTransportsForNetwork(
7395 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007396 }
lucaslin53e8a262021-06-08 01:43:59 +08007397
7398 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007399 }
7400
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007401 /** Convenience method to update the capabilities for a given network. */
7402 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7403 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7404 }
7405
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007406 /**
7407 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7408 * network.
7409 *
7410 * Ingress interface filtering enforces that all apps under the given network can only receive
7411 * packets from the network's interface (and loopback). This is important for VPNs because
7412 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7413 * non-VPN interfaces.
7414 *
7415 * As a result, this method should return true iff
7416 * 1. the network is an app VPN (not legacy VPN)
7417 * 2. the VPN does not allow bypass
7418 * 3. the VPN is fully-routed
7419 * 4. the VPN interface is non-null
7420 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007421 * @see INetd#firewallAddUidInterfaceRules
7422 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007423 */
7424 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7425 LinkProperties lp) {
7426 if (nc == null || lp == null) return false;
7427 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007428 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007429 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007430 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007431 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7432 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007433 }
7434
Chiachang Wang28afaff2020-12-10 22:24:47 +08007435 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7436 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7437 int index = 0;
7438 for (UidRange range : ranges) {
7439 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7440 index++;
7441 }
7442 return stableRanges;
7443 }
7444
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007445 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7446 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7447 for (int i = 0; i < ranges.length; i++) {
7448 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7449 }
7450 return stableRanges;
7451 }
7452
Ken Chen5e65a852020-12-24 12:59:10 +08007453 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7454 int[] exemptUids) {
7455 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7456 try {
7457 mNetd.socketDestroy(ranges, exemptUids);
7458 } catch (Exception e) {
7459 loge("Exception in socket destroy: ", e);
7460 }
7461 }
7462 }
7463
7464 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7465 int[] exemptUids = new int[2];
7466 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7467 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7468 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7469 exemptUids[0] = VPN_UID;
7470 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7471 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7472
7473 maybeCloseSockets(nai, ranges, exemptUids);
7474 try {
7475 if (add) {
paulhue9913722021-05-26 15:19:20 +08007476 // TODO: Passing default network priority to netd.
7477 mNetd.networkAddUidRanges(nai.network.netId, ranges
7478 /* DEFAULT_NETWORK_PRIORITY_NONE */);
Ken Chen5e65a852020-12-24 12:59:10 +08007479 } else {
paulhue9913722021-05-26 15:19:20 +08007480 // TODO: Passing default network priority to netd.
7481 mNetd.networkRemoveUidRanges(nai.network.netId, ranges
7482 /* DEFAULT_NETWORK_PRIORITY_NONE */);
Ken Chen5e65a852020-12-24 12:59:10 +08007483 }
7484 } catch (Exception e) {
7485 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7486 " on netId " + nai.network.netId + ". " + e);
7487 }
7488 maybeCloseSockets(nai, ranges, exemptUids);
7489 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007490
lucaslin53e8a262021-06-08 01:43:59 +08007491 private boolean isProxySetOnAnyDefaultNetwork() {
7492 ensureRunningOnConnectivityServiceThread();
7493 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7494 final NetworkAgentInfo nai = nri.getSatisfier();
7495 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7496 return true;
7497 }
7498 }
7499 return false;
7500 }
7501
7502 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7503 NetworkCapabilities newNc) {
7504 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7505 // the proxy might be changed since the default network satisfied by the apps might also
7506 // changed.
7507 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7508 // that happens to prevent false alarms.
7509 if (nai.isVPN() && nai.everConnected && !NetworkCapabilities.hasSameUids(prevNc, newNc)
7510 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7511 mProxyTracker.sendProxyBroadcast();
7512 }
7513 }
7514
Chalard Jeanb2a49912018-01-16 18:43:05 +09007515 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7516 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007517 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7518 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007519 if (null == prevRanges) prevRanges = new ArraySet<>();
7520 if (null == newRanges) newRanges = new ArraySet<>();
7521 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7522
7523 prevRanges.removeAll(newRanges);
7524 newRanges.removeAll(prevRangesCopy);
7525
7526 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007527 // When updating the VPN uid routing rules, add the new range first then remove the old
7528 // range. If old range were removed first, there would be a window between the old
7529 // range being removed and the new range being added, during which UIDs contained
7530 // in both ranges are not subject to any VPN routing rules. Adding new range before
7531 // removing old range works because, unlike the filtering rules below, it's possible to
7532 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007533 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7534 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7535 // [1-5] & [1-2],[4-5] == [3]
7536 // Then we can do:
7537 // maybeCloseSockets([3])
7538 // mNetd.networkAddUidRanges([1-2],[4-5])
7539 // mNetd.networkRemoveUidRanges([1-5])
7540 // maybeCloseSockets([3])
7541 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7542 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007543 if (!newRanges.isEmpty()) {
Ken Chen5e65a852020-12-24 12:59:10 +08007544 updateUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007545 }
7546 if (!prevRanges.isEmpty()) {
Ken Chen5e65a852020-12-24 12:59:10 +08007547 updateUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007548 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007549 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7550 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7551 final String iface = nai.linkProperties.getInterfaceName();
7552 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007553 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007554 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7555 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7556 // were added first and then newRanges got removed later, there would be only one uid
7557 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7558 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7559 // Note that this is in contrast with the (more robust) update of VPN routing rules
7560 // above, where the addition of new ranges happens before the removal of old ranges.
7561 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7562 // to be removed will never overlap with the new range to be added.
7563 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007564 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007565 }
7566 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007567 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007568 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007569 } catch (Exception e) {
7570 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007571 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007572 }
7573 }
7574
Hugo Benichi9d35b752017-09-01 01:23:32 +00007575 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007576 ensureRunningOnConnectivityServiceThread();
7577
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007578 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007579 // Ignore updates for disconnected networks
7580 return;
7581 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007582 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007583 log("Update of LinkProperties for " + nai.toShortString()
7584 + "; created=" + nai.created
7585 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007586 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007587 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7588 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007589 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007590 }
7591
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007592 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7593 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007594 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007595 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007596 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007597 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7598 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7599 // such an API is ever implemented, there is no doubt the right request to send in
7600 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7601 // be sent as a separate extra.
7602 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007603 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007604 sendIntent(nri.mPendingIntent, intent);
7605 }
7606 // else not handled
7607 }
7608
7609 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7610 mPendingIntentWakeLock.acquire();
7611 try {
7612 if (DBG) log("Sending " + pendingIntent);
7613 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7614 } catch (PendingIntent.CanceledException e) {
7615 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7616 mPendingIntentWakeLock.release();
7617 releasePendingNetworkRequest(pendingIntent);
7618 }
7619 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7620 }
7621
7622 @Override
7623 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7624 String resultData, Bundle resultExtras) {
7625 if (DBG) log("Finished sending " + pendingIntent);
7626 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007627 // Release with a delay so the receiving client has an opportunity to put in its
7628 // own request.
7629 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007630 }
7631
James Mattis212df9e2020-12-03 19:57:41 -08007632 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7633 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7634 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007635 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007636 // Default request has no msgr. Also prevents callbacks from being invoked for
7637 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7638 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7639 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007640 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007641 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007642 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007643 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007644 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007645 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007646 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007647 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7648 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007649 }
Roshan Pius951c0032020-12-22 15:10:42 -08007650 final boolean includeLocationSensitiveInfo =
7651 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007652 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007653 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007654 final NetworkCapabilities nc =
7655 networkCapabilitiesRestrictedForCallerPermissions(
7656 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7657 putParcelable(
7658 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007659 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007660 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007661 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007662 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007663 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7664 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007665 // For this notification, arg1 contains the blocked status.
7666 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007667 break;
7668 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007669 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007670 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007671 break;
7672 }
7673 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007674 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007675 final NetworkCapabilities netCap =
7676 networkCapabilitiesRestrictedForCallerPermissions(
7677 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7678 putParcelable(
7679 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007680 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007681 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007682 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007683 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007684 break;
7685 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007686 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007687 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7688 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007689 break;
7690 }
junyulaif2c67e42018-08-07 19:50:45 +08007691 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007692 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007693 msg.arg1 = arg1;
7694 break;
7695 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007696 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007697 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007698 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007699 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007700 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007701 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007702 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007703 }
James Mattis45d81842021-01-10 14:24:24 -08007704 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007705 } catch (RemoteException e) {
7706 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007707 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007708 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007709 }
7710
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007711 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7712 bundle.putParcelable(t.getClass().getSimpleName(), t);
7713 }
7714
Paul Jensenaf94b982014-09-30 15:37:41 -04007715 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007716 if (nai.numRequestNetworkRequests() != 0) {
7717 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7718 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007719 // Ignore listening and track default requests.
7720 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007721 loge("Dead network still had at least " + nr);
7722 break;
7723 }
Paul Jensenaf94b982014-09-30 15:37:41 -04007724 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007725 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04007726 }
7727
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007728 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7729 if (oldNetwork == null) {
7730 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7731 return;
7732 }
Chalard Jean49707572019-12-10 21:07:02 +09007733 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007734
7735 // If we get here it means that the last linger timeout for this network expired. So there
7736 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08007737 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007738
Lorenzo Colitti2666be82016-09-09 18:48:56 +09007739 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007740 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007741 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007742 } else {
junyulai0ac374f2020-12-14 18:41:52 +08007743 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007744 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007745 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007746 }
7747
James Mattise3ef1912020-12-20 11:09:58 -08007748 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7749 boolean isDefaultChanged = false;
7750 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7751 final NetworkReassignment.RequestReassignment reassignment =
7752 changes.getReassignment(defaultRequestInfo);
7753 if (null == reassignment) {
7754 continue;
7755 }
7756 // reassignment only contains those instances where the satisfying network changed.
7757 isDefaultChanged = true;
7758 // Notify system services of the new default.
7759 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7760 }
Chiachang Wang087fd272018-09-28 22:42:48 +08007761
James Mattise3ef1912020-12-20 11:09:58 -08007762 if (isDefaultChanged) {
7763 // Hold a wakelock for a short time to help apps in migrating to a new default.
7764 scheduleReleaseNetworkTransitionWakelock();
7765 }
7766 }
7767
7768 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7769 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7770 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7771 if (DBG) {
7772 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7773 }
Chalard Jean8e382112019-12-03 20:45:30 +09007774
James Mattisd31bdfa2020-12-23 16:37:26 -08007775 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7776 if (newDefaultNetwork != null) {
7777 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04007778 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09007779
James Mattisd31bdfa2020-12-23 16:37:26 -08007780 // Set an app level managed default and return since further processing only applies to the
7781 // default network.
7782 if (mDefaultRequest != nri) {
7783 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7784 return;
7785 }
7786
7787 makeDefaultNetwork(newDefaultNetwork);
7788
James Mattise3ef1912020-12-20 11:09:58 -08007789 if (oldDefaultNetwork != null) {
7790 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7791 }
7792 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08007793 handleApplyDefaultProxy(null != newDefaultNetwork
7794 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7795 updateTcpBufferSizes(null != newDefaultNetwork
7796 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09007797 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04007798 }
7799
James Mattisd31bdfa2020-12-23 16:37:26 -08007800 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7801 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7802 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7803 try {
7804 if (VDBG) {
7805 log("Setting default network for " + nri
7806 + " using UIDs " + nri.getUids()
7807 + " with old network " + (oldDefaultNetwork != null
7808 ? oldDefaultNetwork.network().getNetId() : "null")
7809 + " and new network " + (newDefaultNetwork != null
7810 ? newDefaultNetwork.network().getNetId() : "null"));
7811 }
7812 if (nri.getUids().isEmpty()) {
7813 throw new IllegalStateException("makeDefaultForApps called without specifying"
7814 + " any applications to set as the default." + nri);
7815 }
7816 if (null != newDefaultNetwork) {
paulhue9913722021-05-26 15:19:20 +08007817 // TODO: Passing default network priority to netd.
James Mattisd31bdfa2020-12-23 16:37:26 -08007818 mNetd.networkAddUidRanges(
7819 newDefaultNetwork.network.getNetId(),
paulhue9913722021-05-26 15:19:20 +08007820 toUidRangeStableParcels(nri.getUids())
7821 /* nri.getDefaultNetworkPriority() */);
James Mattisd31bdfa2020-12-23 16:37:26 -08007822 }
7823 if (null != oldDefaultNetwork) {
paulhue9913722021-05-26 15:19:20 +08007824 // TODO: Passing default network priority to netd.
James Mattisd31bdfa2020-12-23 16:37:26 -08007825 mNetd.networkRemoveUidRanges(
7826 oldDefaultNetwork.network.getNetId(),
paulhue9913722021-05-26 15:19:20 +08007827 toUidRangeStableParcels(nri.getUids())
7828 /* nri.getDefaultNetworkPriority() */);
James Mattisd31bdfa2020-12-23 16:37:26 -08007829 }
7830 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09007831 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08007832 }
7833 }
7834
7835 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7836 try {
7837 if (null != newDefaultNetwork) {
7838 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7839 } else {
7840 mNetd.networkClearDefault();
7841 }
7842 } catch (RemoteException | ServiceSpecificException e) {
7843 loge("Exception setting default network :" + e);
7844 }
7845 }
7846
Chalard Jean05cbe972019-12-09 11:50:38 +09007847 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007848 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09007849 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09007850 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09007851 processNewlySatisfiedListenRequests(nai);
7852 }
7853
7854 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08007855 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7856 if (nri.isMultilayerRequest()) {
7857 continue;
7858 }
7859 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007860 if (!nr.isListen()) continue;
7861 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08007862 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007863 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7864 }
7865 }
Chalard Jeancd397a22019-11-22 22:33:33 +09007866 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007867
Chalard Jeancd397a22019-11-22 22:33:33 +09007868 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08007869 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7870 if (nri.isMultilayerRequest()) {
7871 continue;
7872 }
7873 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007874 if (!nr.isListen()) continue;
7875 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7876 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09007877 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09007878 }
7879 }
7880 }
7881
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007882 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007883 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007884 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08007885 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09007886 @Nullable public final NetworkRequest mOldNetworkRequest;
7887 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007888 @Nullable public final NetworkAgentInfo mOldNetwork;
7889 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08007890 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09007891 @Nullable final NetworkRequest oldNetworkRequest,
7892 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007893 @Nullable final NetworkAgentInfo oldNetwork,
7894 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08007895 mNetworkRequestInfo = networkRequestInfo;
7896 mOldNetworkRequest = oldNetworkRequest;
7897 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007898 mOldNetwork = oldNetwork;
7899 mNewNetwork = newNetwork;
7900 }
Chalard Jean49707572019-12-10 21:07:02 +09007901
7902 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09007903 final NetworkRequest requestToShow = null != mNewNetworkRequest
7904 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7905 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08007906 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7907 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09007908 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007909 }
7910
Chalard Jean46a62372019-12-10 21:25:24 +09007911 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007912
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007913 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09007914 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007915 }
7916
7917 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09007918 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09007919 // The code is never supposed to add two reassignments of the same request. Make
7920 // sure this stays true, but without imposing this expensive check on all
7921 // reassignments on all user devices.
7922 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08007923 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09007924 throw new IllegalStateException("Trying to reassign ["
7925 + reassignment + "] but already have ["
7926 + existing + "]");
7927 }
7928 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09007929 }
Chalard Jean46a62372019-12-10 21:25:24 +09007930 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09007931 }
7932
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007933 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09007934 // the passed request.
7935 @Nullable
7936 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007937 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08007938 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09007939 }
7940 return null;
7941 }
Chalard Jean49707572019-12-10 21:07:02 +09007942
7943 public String toString() {
7944 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7945 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09007946 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09007947 for (final RequestReassignment rr : getRequestReassignments()) {
7948 sj.add(rr.toString());
7949 }
7950 return sj.toString();
7951 }
7952
7953 public String debugString() {
7954 final StringBuilder sb = new StringBuilder();
7955 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09007956 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09007957 for (final RequestReassignment rr : getRequestReassignments()) {
7958 sb.append("\n ").append(rr);
7959 }
7960 return sb.append("\n").toString();
7961 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09007962 }
7963
Chalard Jean24344d72019-12-04 13:32:31 +09007964 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09007965 @Nullable final NetworkRequest previousRequest,
7966 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09007967 @Nullable final NetworkAgentInfo previousSatisfier,
7968 @Nullable final NetworkAgentInfo newSatisfier,
7969 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08007970 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09007971 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09007972 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09007973 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007974 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09007975 }
James Mattisa076c532020-12-02 14:12:41 -08007976 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean550b5212021-03-05 23:07:53 +09007977 previousSatisfier.lingerRequest(previousRequest.requestId, now);
Chalard Jean24344d72019-12-04 13:32:31 +09007978 } else {
7979 if (VDBG || DDBG) log(" accepting network in place of null");
7980 }
junyulai0ac374f2020-12-14 18:41:52 +08007981
7982 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7983 // and immediately satisfies a request then remove the timer. This will happen for
7984 // all networks except in the case of an underlying network for a VCN.
7985 if (newSatisfier.isNascent()) {
7986 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08007987 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08007988 }
7989
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007990 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08007991 newSatisfier.unlingerRequest(newRequest.requestId);
7992 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007993 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08007994 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09007995 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09007996 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09007997 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007998 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08007999 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008000 }
James Mattisa076c532020-12-02 14:12:41 -08008001 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008002 }
James Mattisa076c532020-12-02 14:12:41 -08008003 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008004 }
8005
James Mattisa076c532020-12-02 14:12:41 -08008006 /**
8007 * This function is triggered when something can affect what network should satisfy what
8008 * request, and it computes the network reassignment from the passed collection of requests to
8009 * network match to the one that the system should now have. That data is encoded in an
8010 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8011 * satisfier.
8012 *
8013 * After the reassignment is computed, it is applied to the state objects.
8014 *
8015 * @param networkRequests the nri objects to evaluate for possible network reassignment
8016 * @return NetworkReassignment listing of proposed network assignment changes
8017 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008018 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008019 private NetworkReassignment computeNetworkReassignment(
8020 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008021 final NetworkReassignment changes = new NetworkReassignment();
8022
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008023 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008024 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008025 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008026 if (!nai.everConnected) {
8027 continue;
8028 }
Chalard Jean857a1712019-12-10 21:08:07 +09008029 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008030 }
Chalard Jean857a1712019-12-10 21:08:07 +09008031
James Mattisa076c532020-12-02 14:12:41 -08008032 for (final NetworkRequestInfo nri : networkRequests) {
8033 // Non-multilayer listen requests can be ignored.
8034 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8035 continue;
8036 }
8037 NetworkAgentInfo bestNetwork = null;
8038 NetworkRequest bestRequest = null;
8039 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008040 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008041 // Stop evaluating as the highest possible priority request is satisfied.
8042 if (null != bestNetwork) {
8043 bestRequest = req;
8044 break;
8045 }
8046 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008047 if (null == bestNetwork && isDefaultBlocked(nri)) {
8048 // Remove default networking if disallowed for managed default requests.
8049 bestNetwork = mNoServiceNetwork;
8050 }
8051 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008052 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008053 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008054 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008055 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008056 }
8057 return changes;
8058 }
8059
James Mattisa076c532020-12-02 14:12:41 -08008060 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8061 return new HashSet<>(mNetworkRequests.values());
8062 }
8063
Paul Jensenc88b39b2015-06-16 14:27:36 -04008064 /**
James Mattisa076c532020-12-02 14:12:41 -08008065 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008066 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008067 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008068 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008069 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8070 }
8071
8072 /**
8073 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8074 * being disconnected.
8075 */
8076 private void rematchNetworksAndRequests(
8077 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8078 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008079 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008080 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008081 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008082 if (VDBG || DDBG) {
8083 log(changes.debugString());
8084 } else if (DBG) {
8085 log(changes.toString()); // Shorter form, only one line of log
8086 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008087 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008088 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008089 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008090
Chalard Jeand7f762d2019-12-10 19:01:29 +09008091 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008092 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008093 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008094
8095 // Since most of the time there are only 0 or 1 background networks, it would probably
8096 // be more efficient to just use an ArrayList here. TODO : measure performance
8097 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8098 for (final NetworkAgentInfo nai : nais) {
8099 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8100 }
8101
Chalard Jeand7f762d2019-12-10 19:01:29 +09008102 // First, update the lists of satisfied requests in the network agents. This is necessary
8103 // because some code later depends on this state to be correct, most prominently computing
8104 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008105 for (final NetworkReassignment.RequestReassignment event :
8106 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008107 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8108 event.mOldNetworkRequest, event.mNewNetworkRequest,
8109 event.mOldNetwork, event.mNewNetwork,
8110 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008111 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008112
James Mattise3ef1912020-12-20 11:09:58 -08008113 // Process default network changes if applicable.
8114 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008115
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008116 // Notify requested networks are available after the default net is switched, but
8117 // before LegacyTypeTracker sends legacy broadcasts
8118 for (final NetworkReassignment.RequestReassignment event :
8119 changes.getRequestReassignments()) {
8120 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008121 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008122 } else {
James Mattisa076c532020-12-02 14:12:41 -08008123 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008124 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008125 }
8126 }
8127
junyulai0ac374f2020-12-14 18:41:52 +08008128 // Update the inactivity state before processing listen callbacks, because the background
8129 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008130 // just yet though, because they have to be sent after the listens are processed to keep
8131 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008132 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008133 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008134 // Rematching may have altered the inactivity state of some networks, so update all
8135 // inactivity timers. updateInactivityState reads the state from the network agent
8136 // and does nothing if the state has not changed : the source of truth is controlled
8137 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8138 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008139 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008140 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008141 }
8142 }
8143
Chalard Jeanb10ab412019-12-11 14:12:30 +09008144 for (final NetworkAgentInfo nai : nais) {
8145 if (!nai.everConnected) continue;
8146 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008147 // Process listen requests and update capabilities if the background state has
8148 // changed for this network. For consistency with previous behavior, send onLost
8149 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008150 processNewlyLostListenRequests(nai);
8151 if (oldBackground != nai.isBackgroundNetwork()) {
8152 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008153 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008154 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008155 }
8156
junyulai0ac374f2020-12-14 18:41:52 +08008157 for (final NetworkAgentInfo nai : inactiveNetworks) {
8158 // For nascent networks, if connecting with no foreground request, skip broadcasting
8159 // LOSING for backward compatibility. This is typical when mobile data connected while
8160 // wifi connected with mobile data always-on enabled.
8161 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008162 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008163 }
8164
James Mattise3ef1912020-12-20 11:09:58 -08008165 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008166
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008167 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008168 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008169 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008170 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008171 // This network has active linger timers and no requests, but is not
8172 // lingering. Linger it.
8173 //
8174 // One way (the only way?) this can happen if this network is unvalidated
8175 // and became unneeded due to another network improving its score to the
8176 // point where this network will no longer be able to satisfy any requests
8177 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008178 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008179 notifyNetworkLosing(nai, now);
8180 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008181 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008182 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008183 teardownUnneededNetwork(nai);
8184 }
8185 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008186 }
8187 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008188
Chalard Jean62edfd82019-12-02 18:39:29 +09008189 /**
8190 * Apply a change in background state resulting from rematching networks with requests.
8191 *
8192 * During rematch, a network may change background states by starting to satisfy or stopping
8193 * to satisfy a foreground request. Listens don't count for this. When a network changes
8194 * background states, its capabilities need to be updated and callbacks fired for the
8195 * capability change.
8196 *
8197 * @param nai The network that changed background states
8198 */
8199 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8200 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8201 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8202 updateNetworkPermissions(nai, newNc);
8203 nai.getAndSetNetworkCapabilities(newNc);
8204 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8205 }
8206
Chalard Jeanf0344532019-11-19 19:23:38 +09008207 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008208 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008209 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008210 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8211 changes.getReassignment(mDefaultRequest);
8212 final NetworkAgentInfo oldDefaultNetwork =
8213 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8214 final NetworkAgentInfo newDefaultNetwork =
8215 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008216
Chalard Jean5b409c72021-02-04 13:12:59 +09008217 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008218 // Maintain the illusion : since the legacy API only understands one network at a time,
8219 // if the default network changed, apps should see a disconnected broadcast for the
8220 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008221 if (oldDefaultNetwork != null) {
8222 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8223 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008224 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008225 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008226 // The new default network can be newly null if and only if the old default
8227 // network doesn't satisfy the default request any more because it lost a
8228 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008229 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008230 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008231 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008232 }
8233 }
8234
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008235 // Now that all the callbacks have been sent, send the legacy network broadcasts
8236 // as needed. This is necessary so that legacy requests correctly bind dns
8237 // requests to this network. The legacy users are listening for this broadcast
8238 // and will generally do a dns request so they can ensureRouteToHost and if
8239 // they do that before the callbacks happen they'll use the default network.
8240 //
8241 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8242 // callbacks, but if apps can receive the broadcast before the callback, they still might
8243 // have an inconsistent view of networking.
8244 //
8245 // This *does* introduce a race where if the user uses the new api
8246 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8247 // they may get old info. Reverse this after the old startUsing api is removed.
8248 // This is on top of the multiple intent sequencing referenced in the todo above.
8249 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008250 if (nai.everConnected) {
8251 addNetworkToLegacyTypeTracker(nai);
8252 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008253 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008254 }
8255
Chalard Jean0354d8c2021-01-12 10:58:56 +09008256 private void issueNetworkNeeds() {
8257 ensureRunningOnConnectivityServiceThread();
8258 for (final NetworkOfferInfo noi : mNetworkOffers) {
8259 issueNetworkNeeds(noi);
8260 }
8261 }
8262
8263 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8264 ensureRunningOnConnectivityServiceThread();
8265 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8266 informOffer(nri, noi.offer, mNetworkRanker);
8267 }
8268 }
8269
8270 /**
8271 * Inform a NetworkOffer about any new situation of a request.
8272 *
8273 * This function handles updates to offers. A number of events may happen that require
8274 * updating the registrant for this offer about the situation :
8275 * • The offer itself was updated. This may lead the offer to no longer being able
8276 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8277 * or conversely being strengthened enough to beat the satisfier (and therefore
8278 * start being needed)
8279 * • The network satisfying a request changed (including cases where the request
8280 * starts or stops being satisfied). The new network may be a stronger or weaker
8281 * match than the old one, possibly affecting whether the offer is needed.
8282 * • The network satisfying a request updated their score. This may lead the offer
8283 * to no longer be able to beat it if the current satisfier got better, or
8284 * conversely start being a good choice if the current satisfier got weaker.
8285 *
8286 * @param nri The request
8287 * @param offer The offer. This may be an updated offer.
8288 */
8289 private static void informOffer(@NonNull NetworkRequestInfo nri,
8290 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8291 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8292 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008293
8294 // Multi-layer requests have a currently active request, the one being satisfied.
8295 // Since the system will try to bring up a better network than is currently satisfying
8296 // the request, NetworkProviders need to be told the offers matching the requests *above*
8297 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8298 // not needed, and the offer is needed for the active request iff the offer can beat
8299 // the satisfier.
8300 // For non-multilayer requests, the logic above gracefully degenerates to only the
8301 // last case.
8302 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8303 // providers that the offer is needed for this request, until the active request is found.
8304 // In a second phase, deal with the currently active request. In a third phase, inform
8305 // the providers that offer is unneeded for the remaining requests.
8306
8307 // First phase : inform providers of all requests above the active request.
8308 int i;
8309 for (i = 0; nri.mRequests.size() > i; ++i) {
8310 final NetworkRequest request = nri.mRequests.get(i);
8311 if (activeRequest == request) break; // Found the active request : go to phase 2
8312 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8313 // Since this request is higher-priority than the one currently satisfied, if the
8314 // offer can satisfy it, the provider should try and bring up the network for sure ;
8315 // no need to even ask the ranker – an offer that can satisfy is always better than
8316 // no network. Hence tell the provider so unless it already knew.
8317 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8318 offer.onNetworkNeeded(request);
8319 }
8320 }
8321
8322 // Second phase : deal with the active request (if any)
8323 if (null != activeRequest && activeRequest.isRequest()) {
8324 final boolean oldNeeded = offer.neededFor(activeRequest);
8325 // An offer is needed if it is currently served by this provider or if this offer
8326 // can beat the current satisfier.
8327 final boolean currentlyServing = satisfier != null
8328 && satisfier.factorySerialNumber == offer.providerId;
8329 final boolean newNeeded = (currentlyServing
8330 || (activeRequest.canBeSatisfiedBy(offer.caps)
Chalard Jeane4aeac62021-03-29 17:03:59 +09008331 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
Chalard Jean0354d8c2021-01-12 10:58:56 +09008332 if (newNeeded != oldNeeded) {
8333 if (newNeeded) {
8334 offer.onNetworkNeeded(activeRequest);
8335 } else {
8336 // The offer used to be able to beat the satisfier. Now it can't.
8337 offer.onNetworkUnneeded(activeRequest);
8338 }
8339 }
8340 }
8341
8342 // Third phase : inform the providers that the offer isn't needed for any request
8343 // below the active one.
8344 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8345 final NetworkRequest request = nri.mRequests.get(i);
8346 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8347 // Since this request is lower-priority than the one currently satisfied, if the
8348 // offer can satisfy it, the provider should not try and bring up the network.
8349 // Hence tell the provider so unless it already knew.
8350 if (offer.neededFor(request)) {
8351 offer.onNetworkUnneeded(request);
8352 }
8353 }
8354 }
8355
Chalard Jean61c79252019-11-07 23:07:32 +09008356 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8357 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8358 NetworkRequest nr = nai.requestAt(i);
8359 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8360 // legacy type tracker filters out repeat adds
8361 mLegacyTypeTracker.add(nr.legacyType, nai);
8362 }
8363 }
8364
8365 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008366 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008367 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8368 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8369 if (nai.isVPN()) {
8370 mLegacyTypeTracker.add(TYPE_VPN, nai);
8371 }
8372 }
8373
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008374 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008375 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008376 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008377 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008378 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008379 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008380
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008381 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008382 // Don't repeat publish.
8383 if (newInetCondition == mDefaultInetConditionPublished) return;
8384
8385 mDefaultInetConditionPublished = newInetCondition;
8386 sendInetConditionBroadcast(nai.networkInfo);
8387 }
8388
Chalard Jeand61375d2020-01-14 22:46:36 +09008389 @NonNull
8390 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8391 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008392 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008393 final boolean suspended =
8394 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8395 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8396 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8397 // state. This is because the network could have been suspended before connecting,
8398 // or it could be disconnecting while being suspended, and in both these cases
8399 // the state should not be overridden. Note that the only detailed state that
8400 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8401 // worry about multiple different substates of CONNECTED.
8402 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8403 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008404 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8405 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8406 // network agent is created, then goes to suspended, then goes out of suspended without
8407 // ever setting connected. Check if network agent is ever connected to update the state.
8408 newInfo.setDetailedState(nai.everConnected
8409 ? NetworkInfo.DetailedState.CONNECTED
8410 : NetworkInfo.DetailedState.CONNECTING,
8411 info.getReason(),
8412 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008413 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008414 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008415 return newInfo;
8416 }
8417
8418 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8419 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8420
Erik Kline99f301b2017-02-15 19:59:17 +09008421 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008422 NetworkInfo oldInfo = null;
8423 synchronized (networkAgent) {
8424 oldInfo = networkAgent.networkInfo;
8425 networkAgent.networkInfo = newInfo;
8426 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008427
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008428 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008429 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8430 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008431 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008432
Robin Leea8c0b6e2016-05-01 23:00:00 +01008433 if (!networkAgent.created
8434 && (state == NetworkInfo.State.CONNECTED
8435 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008436
8437 // A network that has just connected has zero requests and is thus a foreground network.
8438 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8439
Luke Huangfdd11f82019-04-09 18:41:49 +08008440 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008441 if (networkAgent.supportsUnderlyingNetworks()) {
8442 // Initialize the network's capabilities to their starting values according to the
8443 // underlying networks. This ensures that the capabilities are correct before
8444 // anything happens to the network.
8445 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008446 }
Paul Jensen74940202014-08-04 12:21:19 -04008447 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008448 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008449 }
8450
8451 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8452 networkAgent.everConnected = true;
8453
lucaslin45e639b2019-04-03 17:09:28 +08008454 // NetworkCapabilities need to be set before sending the private DNS config to
8455 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008456 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8457
Erik Kline9a62f012018-03-21 07:18:33 -07008458 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008459 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8460 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008461
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008462 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8463 // command must be sent after updating LinkProperties to maximize chances of
8464 // NetworkMonitor seeing the correct LinkProperties when starting.
8465 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008466 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008467 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008468 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008469 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008470 new LinkProperties(networkAgent.linkProperties,
8471 true /* parcelSensitiveFields */),
8472 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008473 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008474
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008475 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8476 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8477 // capabilities, so it only needs to be done once on initial connect, not every time the
8478 // network's capabilities change. Note that we do this before rematching the network,
8479 // so we could decide to tear it down immediately afterwards. That's fine though - on
8480 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8481 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008482 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008483
junyulai0ac374f2020-12-14 18:41:52 +08008484 // Before first rematching networks, put an inactivity timer without any request, this
8485 // allows {@code updateInactivityState} to update the state accordingly and prevent
8486 // tearing down for any {@code unneeded} evaluation in this period.
8487 // Note that the timer will not be rescheduled since the expiry time is
8488 // fixed after connection regardless of the network satisfying other requests or not.
8489 // But it will be removed as soon as the network satisfies a request for the first time.
8490 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8491 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008492 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008493
Paul Jensen05e85ee2014-09-11 11:00:39 -04008494 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008495 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008496
8497 // This has to happen after matching the requests, because callbacks are just requests.
8498 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008499 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008500 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008501 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008502 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008503 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008504 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008505 if (networkAgent.isVPN()) {
8506 // As the active or bound network changes for apps, broadcast the default proxy, as
8507 // apps may need to update their proxy data. This is called after disconnecting from
8508 // VPN to make sure we do not broadcast the old proxy data.
8509 // TODO(b/122649188): send the broadcast only to VPN users.
8510 mProxyTracker.sendProxyBroadcast();
8511 }
Yintang Gu5014b522019-06-18 14:24:32 +08008512 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8513 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008514 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008515 }
8516 }
8517
Chalard Jean28018572020-12-21 18:36:52 +09008518 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008519 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8520 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008521 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008522 }
8523
Erik Kline99f301b2017-02-15 19:59:17 +09008524 // Notify only this one new request of the current state. Transfer all the
8525 // current state by calling NetworkCapabilities and LinkProperties callbacks
8526 // so that callers can be guaranteed to have as close to atomicity in state
8527 // transfer as can be supported by this current API.
8528 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008529 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008530 if (nri.mPendingIntent != null) {
8531 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8532 // Attempt no subsequent state pushes where intents are involved.
8533 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008534 }
Erik Kline99f301b2017-02-15 19:59:17 +09008535
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008536 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008537 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008538 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8539 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8540 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008541 }
8542
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008543 // Notify the requests on this NAI that the network is now lingered.
8544 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008545 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008546 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8547 }
8548
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008549 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8550 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8551 return vpnBlocked
8552 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8553 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8554 }
8555
8556 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8557 if (blockedReasons == BLOCKED_REASON_NONE) {
8558 mUidBlockedReasons.delete(uid);
8559 } else {
8560 mUidBlockedReasons.put(uid, blockedReasons);
8561 }
8562 }
8563
junyulaif2c67e42018-08-07 19:50:45 +08008564 /**
8565 * Notify of the blocked state apps with a registered callback matching a given NAI.
8566 *
8567 * Unlike other callbacks, blocked status is different between each individual uid. So for
8568 * any given nai, all requests need to be considered according to the uid who filed it.
8569 *
8570 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008571 * @param oldMetered True if the previous network capabilities were metered.
8572 * @param newMetered True if the current network capabilities are metered.
8573 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8574 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008575 */
8576 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008577 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8578 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008579
8580 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8581 NetworkRequest nr = nai.requestAt(i);
8582 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008583
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008584 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8585 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8586 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008587 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008588 : oldVpnBlocked;
8589
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008590 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8591 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8592 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008593 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008594 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008595 }
8596 }
8597 }
8598
8599 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008600 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008601 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008602 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008603 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008604 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008605 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008606 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008607 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008608
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008609 final int oldBlockedState = getBlockedState(
8610 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8611 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8612 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008613 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008614 }
junyulaif2c67e42018-08-07 19:50:45 +08008615 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8616 NetworkRequest nr = nai.requestAt(i);
8617 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008618 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008619 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8620 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008621 }
8622 }
8623 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008624 }
8625
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008626 @VisibleForTesting
8627 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008628 // The NetworkInfo we actually send out has no bearing on the real
8629 // state of affairs. For example, if the default connection is mobile,
8630 // and a request for HIPRI has just gone away, we need to pretend that
8631 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8632 // the state to DISCONNECTED, even though the network is of type MOBILE
8633 // and is still connected.
8634 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8635 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008636 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008637 if (state != DetailedState.DISCONNECTED) {
8638 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008639 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008640 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008641 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008642 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8643 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8644 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8645 if (info.isFailover()) {
8646 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8647 nai.networkInfo.setFailover(false);
8648 }
8649 if (info.getReason() != null) {
8650 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8651 }
8652 if (info.getExtraInfo() != null) {
8653 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8654 }
8655 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008656 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008657 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008658 if (newDefaultAgent != null) {
8659 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8660 newDefaultAgent.networkInfo);
8661 } else {
8662 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8663 }
8664 }
8665 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8666 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008667 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008668 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008669 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008670 }
8671 }
8672 }
8673
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008674 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008675 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008676 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008677 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008678 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008679 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8680 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008681 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8682 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008683 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008684 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008685 } else {
8686 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8687 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008688 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008689 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008690
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008691 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8692 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8693 }
8694
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008695 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008696 * Returns the list of all interfaces that could be used by network traffic that does not
8697 * explicitly specify a network. This includes the default network, but also all VPNs that are
8698 * currently connected.
8699 *
8700 * Must be called on the handler thread.
8701 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008702 @NonNull
8703 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008704 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008705 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008706 final Set<Integer> activeNetIds = new ArraySet<>();
8707 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8708 if (nri.isBeingSatisfied()) {
8709 activeNetIds.add(nri.getSatisfier().network().netId);
8710 }
8711 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008712 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008713 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008714 defaultNetworks.add(nai.network);
8715 }
8716 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008717 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008718 }
8719
8720 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09008721 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8722 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008723 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08008724 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008725 ensureRunningOnConnectivityServiceThread();
8726 String activeIface = null;
8727 LinkProperties activeLinkProperties = getActiveLinkProperties();
8728 if (activeLinkProperties != null) {
8729 activeIface = activeLinkProperties.getInterfaceName();
8730 }
Benedict Wong9308cd32019-06-12 17:46:31 +00008731
junyulai2050bed2021-01-23 09:46:34 +08008732 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008733 try {
junyulaide41fc22021-01-22 22:46:01 +08008734 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08008735 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08008736 snapshots.add(snapshot);
8737 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008738 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8739 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008740 } catch (Exception ignored) {
8741 }
8742 }
8743
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07008744 @Override
Udam Sainicd645462016-01-04 12:16:14 -08008745 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08008746 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008747 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008748 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008749
8750 if (!TextUtils.isEmpty(settingUrl)) {
8751 return settingUrl;
8752 }
8753
8754 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08008755 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008756 if (!TextUtils.isEmpty(settingUrl)) {
8757 return settingUrl;
8758 }
8759
8760 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08008761 }
8762
8763 @Override
junyulai070f9ff2019-01-16 20:23:34 +08008764 public void startNattKeepalive(Network network, int intervalSeconds,
8765 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008766 enforceKeepalivePermission();
8767 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08008768 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08008769 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08008770 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008771 }
8772
8773 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08008774 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08008775 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08008776 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07008777 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08008778 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07008779 mKeepaliveTracker.startNattKeepalive(
8780 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8781 intervalSeconds, cb,
8782 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8783 } finally {
8784 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8785 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08008786 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8787 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07008788 }
8789 }
junyulaid05a1922019-01-15 11:32:44 +08008790 }
8791
8792 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08008793 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08008794 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07008795 try {
8796 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08008797 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07008798 mKeepaliveTracker.startTcpKeepalive(
8799 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8800 } finally {
8801 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8802 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08008803 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8804 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07008805 }
8806 }
junyulai0835a1e2019-01-08 20:04:33 +08008807 }
8808
8809 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008810 public void stopKeepalive(Network network, int slot) {
8811 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08008812 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008813 }
8814
8815 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07008816 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08008817 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07008818
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08008819 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08008820 final long token = Binder.clearCallingIdentity();
8821 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08008822 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
8823 UserHandle.getUserHandleForUid(uid))) {
8824 return;
8825 }
8826
Heemin Seogdb8489d2019-06-12 09:21:44 -07008827 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8828 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08008829
8830 // Turn airplane mode off
8831 setAirplaneMode(false);
8832
8833 // restore private DNS settings to default mode (opportunistic)
8834 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
8835 UserHandle.getUserHandleForUid(uid))) {
8836 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
8837 PRIVATE_DNS_MODE_OPPORTUNISTIC);
8838 }
8839
8840 Settings.Global.putString(mContext.getContentResolver(),
8841 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08008842 } finally {
8843 Binder.restoreCallingIdentity(token);
8844 }
Stuart Scottd5463642015-04-02 18:00:02 -07008845 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04008846
Ricky Wai7097cc92018-01-23 04:09:45 +00008847 @Override
8848 public byte[] getNetworkWatchlistConfigHash() {
8849 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8850 if (nwm == null) {
8851 loge("Unable to get NetworkWatchlistManager");
8852 return null;
8853 }
8854 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8855 return nwm.getWatchlistConfigHash();
8856 }
8857
Hugo Benichibe0c7652016-05-31 16:28:06 +09008858 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09008859 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08008860 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09008861 }
Hugo Benichif4210292017-04-21 15:07:12 +09008862
8863 private static boolean toBool(int encodedBoolean) {
8864 return encodedBoolean != 0; // Only 0 means false.
8865 }
8866
8867 private static int encodeBool(boolean b) {
8868 return b ? 1 : 0;
8869 }
mswest4632928412018-03-12 10:34:34 -07008870
8871 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08008872 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8873 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8874 @NonNull String[] args) {
8875 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8876 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07008877 }
8878
Chiachang Wang77ae8a02020-10-12 15:20:07 +08008879 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07008880 @Override
8881 public int onCommand(String cmd) {
8882 if (cmd == null) {
8883 return handleDefaultCommands(cmd);
8884 }
8885 final PrintWriter pw = getOutPrintWriter();
8886 try {
8887 switch (cmd) {
8888 case "airplane-mode":
8889 final String action = getNextArg();
8890 if ("enable".equals(action)) {
8891 setAirplaneMode(true);
8892 return 0;
8893 } else if ("disable".equals(action)) {
8894 setAirplaneMode(false);
8895 return 0;
8896 } else if (action == null) {
8897 final ContentResolver cr = mContext.getContentResolver();
8898 final int enabled = Settings.Global.getInt(cr,
8899 Settings.Global.AIRPLANE_MODE_ON);
8900 pw.println(enabled == 0 ? "disabled" : "enabled");
8901 return 0;
8902 } else {
8903 onHelp();
8904 return -1;
8905 }
8906 default:
8907 return handleDefaultCommands(cmd);
8908 }
8909 } catch (Exception e) {
8910 pw.println(e);
8911 }
8912 return -1;
8913 }
8914
8915 @Override
8916 public void onHelp() {
8917 PrintWriter pw = getOutPrintWriter();
8918 pw.println("Connectivity service commands:");
8919 pw.println(" help");
8920 pw.println(" Print this help text.");
8921 pw.println(" airplane-mode [enable|disable]");
8922 pw.println(" Turn airplane mode on or off.");
8923 pw.println(" airplane-mode");
8924 pw.println(" Get airplane mode.");
8925 }
8926 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008927
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09008928 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09008929 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8930 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8931 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08008932 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008933 }
8934
8935 /**
8936 * @param connectionInfo the connection to resolve.
8937 * @return {@code uid} if the connection is found and the app has permission to observe it
8938 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8939 * connection is not found.
8940 */
8941 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008942 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8943 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8944 }
8945
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09008946 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008947 connectionInfo.local, connectionInfo.remote);
8948
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09008949 if (uid == INVALID_UID) return uid; // Not found.
8950
8951 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8952 // VPN, if any, that applies to the UID that owns the connection.
8953 if (checkNetworkStackPermission()) return uid;
8954
8955 final NetworkAgentInfo vpn = getVpnForUid(uid);
8956 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008957 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07008958 return INVALID_UID;
8959 }
8960
8961 return uid;
8962 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00008963
Benedict Wong493e04b2018-11-09 14:45:34 -08008964 /**
8965 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8966 *
8967 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8968 */
8969 @Override
8970 public IBinder startOrGetTestNetworkService() {
8971 synchronized (mTNSLock) {
8972 TestNetworkService.enforceTestNetworkPermissions(mContext);
8973
8974 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08008975 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08008976 }
8977
8978 return mTNS;
8979 }
8980 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08008981
Cody Kesting73708bf2019-12-18 10:57:50 -08008982 /**
8983 * Handler used for managing all Connectivity Diagnostics related functions.
8984 *
8985 * @see android.net.ConnectivityDiagnosticsManager
8986 *
8987 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8988 */
8989 @VisibleForTesting
8990 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08008991 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8992
Cody Kesting73708bf2019-12-18 10:57:50 -08008993 /**
8994 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8995 * android.net.ConnectivityDiagnosticsManager}.
8996 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8997 * NetworkRequestInfo to be registered
8998 */
8999 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9000
9001 /**
9002 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9003 * android.net.ConnectivityDiagnosticsManager}.
9004 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9005 * arg1 = the uid of the caller
9006 */
9007 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9008
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009009 /**
9010 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9011 * after processing {@link #EVENT_NETWORK_TESTED} events.
9012 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9013 * NetworkMonitor.
9014 * data = PersistableBundle of extras passed from NetworkMonitor.
9015 *
9016 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9017 */
9018 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9019
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009020 /**
9021 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9022 * been detected on the network.
9023 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9024 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9025 * arg2 = NetID.
9026 * data = PersistableBundle of extras passed from NetworkMonitor.
9027 */
9028 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9029
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009030 /**
9031 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9032 * the platform. This event will invoke {@link
9033 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9034 * callbacks.
9035 * obj = Network that was reported on
9036 * arg1 = boolint for the quality reported
9037 */
9038 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9039
Cody Kesting73708bf2019-12-18 10:57:50 -08009040 private ConnectivityDiagnosticsHandler(Looper looper) {
9041 super(looper);
9042 }
9043
9044 @Override
9045 public void handleMessage(Message msg) {
9046 switch (msg.what) {
9047 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9048 handleRegisterConnectivityDiagnosticsCallback(
9049 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9050 break;
9051 }
9052 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9053 handleUnregisterConnectivityDiagnosticsCallback(
9054 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9055 break;
9056 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009057 case EVENT_NETWORK_TESTED: {
9058 final ConnectivityReportEvent reportEvent =
9059 (ConnectivityReportEvent) msg.obj;
9060
Aaron Huang959d3642021-01-21 15:47:41 +08009061 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009062 break;
9063 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009064 case EVENT_DATA_STALL_SUSPECTED: {
9065 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009066 final Pair<Long, PersistableBundle> arg =
9067 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009068 if (nai == null) break;
9069
Aaron Huang959d3642021-01-21 15:47:41 +08009070 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009071 break;
9072 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009073 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
9074 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
9075 break;
9076 }
9077 default: {
9078 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9079 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009080 }
9081 }
9082 }
9083
9084 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9085 @VisibleForTesting
9086 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9087 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9088 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009089 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009090
9091 @VisibleForTesting
9092 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009093 @NonNull IConnectivityDiagnosticsCallback cb,
9094 @NonNull NetworkRequestInfo nri,
9095 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009096 mCb = cb;
9097 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009098 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009099 }
9100
9101 @Override
9102 public void binderDied() {
9103 log("ConnectivityDiagnosticsCallback IBinder died.");
9104 unregisterConnectivityDiagnosticsCallback(mCb);
9105 }
9106 }
9107
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009108 /**
9109 * Class used for sending information from {@link
9110 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9111 */
9112 private static class NetworkTestedResults {
9113 private final int mNetId;
9114 private final int mTestResult;
9115 private final long mTimestampMillis;
9116 @Nullable private final String mRedirectUrl;
9117
9118 private NetworkTestedResults(
9119 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9120 mNetId = netId;
9121 mTestResult = testResult;
9122 mTimestampMillis = timestampMillis;
9123 mRedirectUrl = redirectUrl;
9124 }
9125 }
9126
9127 /**
9128 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9129 * ConnectivityDiagnosticsHandler}.
9130 */
9131 private static class ConnectivityReportEvent {
9132 private final long mTimestampMillis;
9133 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009134 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009135
Aaron Huang959d3642021-01-21 15:47:41 +08009136 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9137 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009138 mTimestampMillis = timestampMillis;
9139 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009140 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009141 }
9142 }
9143
Cody Kesting73708bf2019-12-18 10:57:50 -08009144 private void handleRegisterConnectivityDiagnosticsCallback(
9145 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9146 ensureRunningOnConnectivityServiceThread();
9147
9148 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009149 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009150 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9151
James Mattis64b8b0f2020-11-24 17:40:49 -08009152 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9153 // confusing for these networks to change when an NRI is satisfied in another layer.
9154 if (nri.isMultilayerRequest()) {
9155 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9156 + "network requests.");
9157 }
9158
Cody Kesting73708bf2019-12-18 10:57:50 -08009159 // This means that the client registered the same callback multiple times. Do
9160 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009161 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009162 if (VDBG) log("Diagnostics callback is already registered");
9163
9164 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9165 // incremented when the NetworkRequestInfo is created as part of
9166 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009167 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009168 return;
9169 }
9170
Cody Kesting31f1ff62020-03-05 10:46:02 -08009171 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009172
9173 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009174 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009175 } catch (RemoteException e) {
9176 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009177 return;
9178 }
9179
9180 // Once registered, provide ConnectivityReports for matching Networks
9181 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9182 synchronized (mNetworkForNetId) {
9183 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9184 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009185 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9186 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009187 matchingNetworks.add(nai);
9188 }
9189 }
9190 }
9191 for (final NetworkAgentInfo nai : matchingNetworks) {
9192 final ConnectivityReport report = nai.getConnectivityReport();
9193 if (report == null) {
9194 continue;
9195 }
9196 if (!checkConnectivityDiagnosticsPermissions(
9197 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9198 continue;
9199 }
9200
9201 try {
9202 cb.onConnectivityReportAvailable(report);
9203 } catch (RemoteException e) {
9204 // Exception while sending the ConnectivityReport. Move on to the next network.
9205 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009206 }
9207 }
9208
9209 private void handleUnregisterConnectivityDiagnosticsCallback(
9210 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9211 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009212 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009213
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009214 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9215 mConnectivityDiagnosticsCallbacks.remove(iCb);
9216 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009217 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9218 return;
9219 }
9220
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009221 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009222
Cody Kesting70fa2b22020-12-02 12:16:56 -08009223 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9224 // (if the Binder died)
9225 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9226 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009227 return;
9228 }
9229
Cody Kesting46cb1672020-03-04 13:35:20 -08009230 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9231 // incremented when the NetworkRequestInfo is created as part of
9232 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009233 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009234
Cody Kesting31f1ff62020-03-05 10:46:02 -08009235 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009236 }
9237
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009238 private void handleNetworkTestedWithExtras(
9239 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9240 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009241 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009242 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009243 final ConnectivityReport report =
9244 new ConnectivityReport(
9245 reportEvent.mNai.network,
9246 reportEvent.mTimestampMillis,
9247 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009248 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009249 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009250 nai.setConnectivityReport(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009251 final List<IConnectivityDiagnosticsCallback> results =
9252 getMatchingPermissionedCallbacks(nai);
9253 for (final IConnectivityDiagnosticsCallback cb : results) {
9254 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009255 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009256 } catch (RemoteException ex) {
9257 loge("Error invoking onConnectivityReport", ex);
9258 }
9259 }
9260 }
9261
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009262 private void handleDataStallSuspected(
9263 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9264 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009265 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009266 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009267 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009268 new DataStallReport(
9269 nai.network,
9270 timestampMillis,
9271 detectionMethod,
9272 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009273 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009274 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009275 final List<IConnectivityDiagnosticsCallback> results =
9276 getMatchingPermissionedCallbacks(nai);
9277 for (final IConnectivityDiagnosticsCallback cb : results) {
9278 try {
9279 cb.onDataStallSuspected(report);
9280 } catch (RemoteException ex) {
9281 loge("Error invoking onDataStallSuspected", ex);
9282 }
9283 }
9284 }
9285
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009286 private void handleNetworkConnectivityReported(
9287 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9288 final List<IConnectivityDiagnosticsCallback> results =
9289 getMatchingPermissionedCallbacks(nai);
9290 for (final IConnectivityDiagnosticsCallback cb : results) {
9291 try {
9292 cb.onNetworkConnectivityReported(nai.network, connectivity);
9293 } catch (RemoteException ex) {
9294 loge("Error invoking onNetworkConnectivityReported", ex);
9295 }
9296 }
9297 }
9298
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009299 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009300 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9301 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009302 sanitized.setUids(null);
9303 sanitized.setAdministratorUids(new int[0]);
9304 sanitized.setOwnerUid(Process.INVALID_UID);
9305 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009306 }
9307
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009308 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9309 @NonNull NetworkAgentInfo nai) {
9310 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009311 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009312 mConnectivityDiagnosticsCallbacks.entrySet()) {
9313 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9314 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
James Mattis64b8b0f2020-11-24 17:40:49 -08009315 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9316 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009317 if (checkConnectivityDiagnosticsPermissions(
9318 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009319 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009320 }
9321 }
9322 }
9323 return results;
9324 }
9325
Cody Kesting7474f672021-05-11 14:22:40 -07009326 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9327 @NonNull NetworkAgentInfo nai) {
9328 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9329 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9330 }
9331
Cody Kesting160ef392021-05-05 13:17:22 -07009332 private boolean hasLocationPermission(String packageName, int uid) {
9333 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9334 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9335 // call in a try-catch.
9336 try {
9337 if (!mLocationPermissionChecker.checkLocationPermission(
9338 packageName, null /* featureId */, uid, null /* message */)) {
9339 return false;
9340 }
9341 } catch (SecurityException e) {
9342 return false;
9343 }
9344
9345 return true;
9346 }
9347
9348 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9349 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
9350 if (virtual.supportsUnderlyingNetworks()
9351 && virtual.networkCapabilities.getOwnerUid() == uid
9352 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9353 return true;
9354 }
9355 }
9356
9357 return false;
9358 }
9359
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009360 @VisibleForTesting
9361 boolean checkConnectivityDiagnosticsPermissions(
9362 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9363 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9364 return true;
9365 }
9366
Cody Kesting160ef392021-05-05 13:17:22 -07009367 // Administrator UIDs also contains the Owner UID
9368 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9369 if (!CollectionUtils.contains(administratorUids, callbackUid)
9370 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009371 return false;
9372 }
9373
Cody Kesting7474f672021-05-11 14:22:40 -07009374 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9375 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009376 }
9377
Cody Kestingd199a9d2019-12-17 12:55:28 -08009378 @Override
9379 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009380 @NonNull IConnectivityDiagnosticsCallback callback,
9381 @NonNull NetworkRequest request,
9382 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009383 if (request.legacyType != TYPE_NONE) {
9384 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9385 + " Please use NetworkCapabilities instead.");
9386 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009387 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009388 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009389
9390 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9391 // and administrator uids to be safe.
9392 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009393 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009394
9395 final NetworkRequest requestWithId =
9396 new NetworkRequest(
9397 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9398
9399 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9400 //
9401 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9402 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9403 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009404 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009405 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009406 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009407
9408 mConnectivityDiagnosticsHandler.sendMessage(
9409 mConnectivityDiagnosticsHandler.obtainMessage(
9410 ConnectivityDiagnosticsHandler
9411 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9412 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009413 }
9414
9415 @Override
9416 public void unregisterConnectivityDiagnosticsCallback(
9417 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009418 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009419 mConnectivityDiagnosticsHandler.sendMessage(
9420 mConnectivityDiagnosticsHandler.obtainMessage(
9421 ConnectivityDiagnosticsHandler
9422 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009423 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009424 0,
9425 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009426 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009427
9428 @Override
9429 public void simulateDataStall(int detectionMethod, long timestampMillis,
9430 @NonNull Network network, @NonNull PersistableBundle extras) {
9431 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9432 android.Manifest.permission.NETWORK_STACK);
9433 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9434 if (!nc.hasTransport(TRANSPORT_TEST)) {
9435 throw new SecurityException("Data Stall simluation is only possible for test networks");
9436 }
9437
9438 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009439 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009440 throw new SecurityException("Data Stall simulation is only possible for network "
9441 + "creators");
9442 }
9443
Cody Kesting652e3ec2020-05-21 12:08:21 -07009444 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9445 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9446 // Data Stall information as a DataStallReportParcelable and passing to
9447 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9448 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009449 final DataStallReportParcelable p = new DataStallReportParcelable();
9450 p.timestampMillis = timestampMillis;
9451 p.detectionMethod = detectionMethod;
9452
9453 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9454 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9455 }
9456 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9457 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9458 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9459 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9460 }
9461
Serik Beketayevec8ad212020-12-07 22:43:07 -08009462 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009463 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009464
lucaslin66f44212021-02-23 01:12:55 +08009465 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9466 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009467 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009468 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009469 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009470 }
lucaslin37a16d92021-01-21 19:48:09 +08009471
9472 @Override
9473 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009474 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009475 nai.clatd.interfaceLinkStateChanged(iface, up);
9476 }
9477 }
9478
9479 @Override
9480 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009481 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009482 nai.clatd.interfaceRemoved(iface);
9483 }
lucaslin66f44212021-02-23 01:12:55 +08009484 }
9485 }
9486
lucaslin1a8b4c62021-01-21 02:02:55 +08009487 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9488
9489 /**
9490 * Class used for updating network activity tracking with netd and notify network activity
9491 * changes.
9492 */
9493 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009494 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009495 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009496 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009497 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9498 new RemoteCallbackList<>();
9499 // Indicate the current system default network activity is active or not.
9500 @GuardedBy("mActiveIdleTimers")
9501 private boolean mNetworkActive;
9502 @GuardedBy("mActiveIdleTimers")
9503 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9504 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009505
lucaslin1193a5d2021-01-21 02:04:15 +08009506 private class IdleTimerParams {
9507 public final int timeout;
9508 public final int transportType;
9509
9510 IdleTimerParams(int timeout, int transport) {
9511 this.timeout = timeout;
9512 this.transportType = transport;
9513 }
9514 }
9515
9516 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009517 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009518 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009519 mNetd = netd;
9520 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009521 }
9522
lucaslin66f44212021-02-23 01:12:55 +08009523 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9524 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9525 synchronized (mActiveIdleTimers) {
9526 mNetworkActive = active;
9527 // If there are no idle timers, it means that system is not monitoring
9528 // activity, so the system default network for those default network
9529 // unspecified apps is always considered active.
9530 //
9531 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9532 // any network activity change event. Whenever this event is received,
9533 // the mActiveIdleTimers should be always not empty. The legacy behavior
9534 // is no-op. Remove to refer to mNetworkActive only.
9535 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9536 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9537 }
9538 }
9539 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009540
lucaslin1193a5d2021-01-21 02:04:15 +08009541 // The network activity should only be updated from ConnectivityService handler thread
9542 // when mActiveIdleTimers lock is held.
9543 @GuardedBy("mActiveIdleTimers")
9544 private void reportNetworkActive() {
9545 final int length = mNetworkActivityListeners.beginBroadcast();
9546 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9547 try {
9548 for (int i = 0; i < length; i++) {
9549 try {
9550 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9551 } catch (RemoteException | RuntimeException e) {
9552 loge("Fail to send network activie to listener " + e);
9553 }
9554 }
9555 } finally {
9556 mNetworkActivityListeners.finishBroadcast();
9557 }
9558 }
9559
9560 @GuardedBy("mActiveIdleTimers")
9561 public void handleReportNetworkActivity() {
9562 synchronized (mActiveIdleTimers) {
9563 reportNetworkActive();
9564 }
9565 }
9566
lucaslin1a8b4c62021-01-21 02:02:55 +08009567 // This is deprecated and only to support legacy use cases.
9568 private int transportTypeToLegacyType(int type) {
9569 switch (type) {
9570 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009571 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009572 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009573 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009574 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009575 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009576 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009577 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009578 default:
9579 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9580 }
9581 return ConnectivityManager.TYPE_NONE;
9582 }
9583
9584 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9585 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9586 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9587 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9588 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9589 final long ident = Binder.clearCallingIdentity();
9590 try {
9591 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9592 RECEIVE_DATA_ACTIVITY_CHANGE,
9593 null /* resultReceiver */,
9594 null /* scheduler */,
9595 0 /* initialCode */,
9596 null /* initialData */,
9597 null /* initialExtra */);
9598 } finally {
9599 Binder.restoreCallingIdentity(ident);
9600 }
9601 }
9602
9603 /**
9604 * Setup data activity tracking for the given network.
9605 *
9606 * Every {@code setupDataActivityTracking} should be paired with a
9607 * {@link #removeDataActivityTracking} for cleanup.
9608 */
9609 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9610 final String iface = networkAgent.linkProperties.getInterfaceName();
9611
9612 final int timeout;
9613 final int type;
9614
9615 if (networkAgent.networkCapabilities.hasTransport(
9616 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9617 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009618 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009619 10);
9620 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9621 } else if (networkAgent.networkCapabilities.hasTransport(
9622 NetworkCapabilities.TRANSPORT_WIFI)) {
9623 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009624 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009625 15);
9626 type = NetworkCapabilities.TRANSPORT_WIFI;
9627 } else {
9628 return; // do not track any other networks
9629 }
9630
lucaslinb961efc2021-01-21 02:03:17 +08009631 updateRadioPowerState(true /* isActive */, type);
9632
lucaslin1a8b4c62021-01-21 02:02:55 +08009633 if (timeout > 0 && iface != null) {
9634 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009635 synchronized (mActiveIdleTimers) {
9636 // Networks start up.
9637 mNetworkActive = true;
9638 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9639 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9640 reportNetworkActive();
9641 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009642 } catch (Exception e) {
9643 // You shall not crash!
9644 loge("Exception in setupDataActivityTracking " + e);
9645 }
9646 }
9647 }
9648
9649 /**
9650 * Remove data activity tracking when network disconnects.
9651 */
9652 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9653 final String iface = networkAgent.linkProperties.getInterfaceName();
9654 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9655
lucaslinb961efc2021-01-21 02:03:17 +08009656 if (iface == null) return;
9657
9658 final int type;
9659 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9660 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9661 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9662 type = NetworkCapabilities.TRANSPORT_WIFI;
9663 } else {
9664 return; // do not track any other networks
9665 }
9666
9667 try {
9668 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +08009669 synchronized (mActiveIdleTimers) {
9670 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9671 // The call fails silently if no idle timer setup for this interface
9672 mNetd.idletimerRemoveInterface(iface, params.timeout,
9673 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +08009674 }
lucaslinb961efc2021-01-21 02:03:17 +08009675 } catch (Exception e) {
9676 // You shall not crash!
9677 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +08009678 }
9679 }
9680
9681 /**
9682 * Update data activity tracking when network state is updated.
9683 */
9684 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9685 NetworkAgentInfo oldNetwork) {
9686 if (newNetwork != null) {
9687 setupDataActivityTracking(newNetwork);
9688 }
9689 if (oldNetwork != null) {
9690 removeDataActivityTracking(oldNetwork);
9691 }
9692 }
lucaslinb961efc2021-01-21 02:03:17 +08009693
9694 private void updateRadioPowerState(boolean isActive, int transportType) {
9695 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9696 switch (transportType) {
9697 case NetworkCapabilities.TRANSPORT_CELLULAR:
9698 bs.reportMobileRadioPowerState(isActive, NO_UID);
9699 break;
9700 case NetworkCapabilities.TRANSPORT_WIFI:
9701 bs.reportWifiRadioPowerState(isActive, NO_UID);
9702 break;
9703 default:
9704 logw("Untracked transport type:" + transportType);
9705 }
9706 }
lucaslin1193a5d2021-01-21 02:04:15 +08009707
9708 public boolean isDefaultNetworkActive() {
9709 synchronized (mActiveIdleTimers) {
9710 // If there are no idle timers, it means that system is not monitoring activity,
9711 // so the default network is always considered active.
9712 //
9713 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9714 // tracking is disabled (negative idle timer value configured), or no active default
9715 // network. In the latter case, this reports active but it should report inactive.
9716 return mNetworkActive || mActiveIdleTimers.isEmpty();
9717 }
9718 }
9719
9720 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9721 mNetworkActivityListeners.register(l);
9722 }
9723
9724 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9725 mNetworkActivityListeners.unregister(l);
9726 }
lucaslin012f7a12021-01-21 02:04:35 +08009727
9728 public void dump(IndentingPrintWriter pw) {
9729 synchronized (mActiveIdleTimers) {
9730 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9731 pw.println("Idle timers:");
9732 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9733 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9734 final IdleTimerParams params = ent.getValue();
9735 pw.print(" timeout="); pw.print(params.timeout);
9736 pw.print(" type="); pw.println(params.transportType);
9737 }
9738 }
9739 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009740 }
James Mattis47db0582021-01-01 14:13:35 -08009741
Daniel Brightf9e945b2020-06-15 16:10:01 -07009742 /**
9743 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9744 *
9745 * @param socketInfo the socket information
9746 * @param callback the callback to register
9747 */
9748 @Override
9749 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9750 @NonNull final IQosCallback callback) {
9751 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9752 if (nai == null || nai.networkCapabilities == null) {
9753 try {
9754 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9755 } catch (final RemoteException ex) {
9756 loge("registerQosCallbackInternal: RemoteException", ex);
9757 }
9758 return;
9759 }
9760 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9761 }
9762
9763 /**
9764 * Register a {@link IQosCallback} with base {@link QosFilter}.
9765 *
9766 * @param filter the filter to register
9767 * @param callback the callback to register
9768 * @param nai the agent information related to the filter's network
9769 */
9770 @VisibleForTesting
9771 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9772 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9773 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9774 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9775
9776 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9777 enforceConnectivityRestrictedNetworksPermission();
9778 }
9779 mQosCallbackTracker.registerCallback(callback, filter, nai);
9780 }
9781
9782 /**
9783 * Unregisters the given callback.
9784 *
9785 * @param callback the callback to unregister
9786 */
9787 @Override
9788 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009789 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -07009790 mQosCallbackTracker.unregisterCallback(callback);
9791 }
James Mattis47db0582021-01-01 14:13:35 -08009792
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009793 // Network preference per-profile and OEM network preferences can't be set at the same
9794 // time, because it is unclear what should happen if both preferences are active for
9795 // one given UID. To make it possible, the stack would have to clarify what would happen
9796 // in case both are active at the same time. The implementation may have to be adjusted
9797 // to implement the resulting rules. For example, a priority could be defined between them,
9798 // where the OEM preference would be considered less or more important than the enterprise
9799 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9800 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9801 // are set at the right level. Other solutions are possible, e.g. merging of the
9802 // preferences for the relevant UIDs.
9803 private static void throwConcurrentPreferenceException() {
9804 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9805 + "set OemNetworkPreference at the same time");
James Mattis45d81842021-01-10 14:24:24 -08009806 }
9807
9808 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +09009809 * Request that a user profile is put by default on a network matching a given preference.
9810 *
9811 * See the documentation for the individual preferences for a description of the supported
9812 * behaviors.
9813 *
9814 * @param profile the profile concerned.
9815 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9816 * constants.
9817 * @param listener an optional listener to listen for completion of the operation.
9818 */
9819 @Override
9820 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9821 @ConnectivityManager.ProfileNetworkPreference final int preference,
9822 @Nullable final IOnCompleteListener listener) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009823 Objects.requireNonNull(profile);
9824 PermissionUtils.enforceNetworkStackPermission(mContext);
9825 if (DBG) {
9826 log("setProfileNetworkPreference " + profile + " to " + preference);
9827 }
9828 if (profile.getIdentifier() < 0) {
9829 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9830 + "UserHandle.CURRENT not supported)");
9831 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +09009832 final UserManager um = mContext.getSystemService(UserManager.class);
9833 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009834 throw new IllegalArgumentException("Profile must be a managed profile");
9835 }
9836 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9837 // handler thread. However it is an immutable object, so reading the reference is
9838 // safe - it's just possible the value is slightly outdated. For the final check,
9839 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9840 // lot easier to understand, so opportunistically check it.
paulhu51f77dc2021-06-07 02:34:20 +00009841 // TODO: Have a priority for each preference.
9842 if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009843 throwConcurrentPreferenceException();
9844 }
9845 final NetworkCapabilities nc;
9846 switch (preference) {
9847 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9848 nc = null;
9849 break;
9850 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9851 final UidRange uids = UidRange.createForUser(profile);
9852 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9853 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9854 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9855 break;
9856 default:
9857 throw new IllegalArgumentException(
9858 "Invalid preference in setProfileNetworkPreference");
9859 }
9860 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9861 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9862 }
9863
9864 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9865 @Nullable final NetworkCapabilities nc) {
9866 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9867 ensureRequestableCapabilities(nc);
9868 }
9869
9870 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9871 @NonNull final ProfileNetworkPreferences prefs) {
9872 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9873 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9874 // The NRI for a user should be comprised of two layers:
9875 // - The request for the capabilities
9876 // - The request for the default network, for fallback. Create an image of it to
9877 // have the correct UIDs in it (also a request can only be part of one NRI, because
9878 // of lookups in 1:1 associations like mNetworkRequests).
9879 // Note that denying a fallback can be implemented simply by not adding the second
9880 // request.
9881 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9882 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
James Mattisa117e282021-04-20 17:26:30 -07009883 nrs.add(createDefaultInternetRequestForTransport(
9884 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009885 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +08009886 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
9887 DEFAULT_NETWORK_PRIORITY_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009888 result.add(nri);
9889 }
9890 return result;
9891 }
9892
9893 private void handleSetProfileNetworkPreference(
9894 @NonNull final ProfileNetworkPreferences.Preference preference,
9895 @Nullable final IOnCompleteListener listener) {
9896 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9897 // particular because it's not clear what preference should win in case both apply
9898 // to the same app.
9899 // The binder call has already checked this, but as mOemNetworkPreferences is only
9900 // touched on the handler thread, it's theoretically not impossible that it has changed
9901 // since.
paulhu51f77dc2021-06-07 02:34:20 +00009902 // TODO: Have a priority for each preference.
9903 if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Chalard Jean0f57a492021-03-09 21:09:20 +09009904 // This may happen on a device with an OEM preference set when a user is removed.
9905 // In this case, it's safe to ignore. In particular this happens in the tests.
9906 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009907 return;
9908 }
9909
9910 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9911
9912 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
James Mattis20a4a8b2021-03-28 17:41:09 -07009913 mSystemNetworkRequestCounter.transact(
9914 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9915 () -> {
9916 final ArraySet<NetworkRequestInfo> nris =
9917 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9918 replaceDefaultNetworkRequestsForPreference(nris);
9919 });
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009920 // Finally, rematch.
9921 rematchAllNetworksAndRequests();
9922
9923 if (null != listener) {
9924 try {
9925 listener.onComplete();
9926 } catch (RemoteException e) {
9927 loge("Listener for setProfileNetworkPreference has died");
9928 }
9929 }
9930 }
9931
paulhu51f77dc2021-06-07 02:34:20 +00009932 @VisibleForTesting
9933 @NonNull
9934 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
9935 @NonNull final Set<Integer> uids) {
9936 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
9937 if (uids.size() == 0) {
9938 // Should not create NetworkRequestInfo if no preferences. Without uid range in
9939 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
9940 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
9941 return nris;
9942 }
9943
9944 final List<NetworkRequest> requests = new ArrayList<>();
9945 // The NRI should be comprised of two layers:
9946 // - The request for the mobile network preferred.
9947 // - The request for the default network, for fallback.
9948 requests.add(createDefaultInternetRequestForTransport(
9949 TRANSPORT_CELLULAR, NetworkRequest.Type.LISTEN));
9950 requests.add(createDefaultInternetRequestForTransport(
9951 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9952 final Set<UidRange> ranges = new ArraySet<>();
9953 for (final int uid : uids) {
9954 ranges.add(new UidRange(uid, uid));
9955 }
9956 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +08009957 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
9958 DEFAULT_NETWORK_PRIORITY_MOBILE_DATA_PREFERRED));
paulhu51f77dc2021-06-07 02:34:20 +00009959 return nris;
9960 }
9961
9962 private void handleMobileDataPreferredUidsChanged() {
9963 // Ignore update preference because it's not clear what preference should win in case both
9964 // apply to the same app.
9965 // TODO: Have a priority for each preference.
9966 if (!mOemNetworkPreferences.isEmpty() || !mProfileNetworkPreferences.isEmpty()) {
9967 loge("Ignore mobile data preference change because other preferences are not empty");
9968 return;
9969 }
9970
9971 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
9972 mSystemNetworkRequestCounter.transact(
9973 mDeps.getCallingUid(), 1 /* numOfNewRequests */,
9974 () -> {
9975 final ArraySet<NetworkRequestInfo> nris =
9976 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids);
9977 replaceDefaultNetworkRequestsForPreference(nris);
9978 });
9979 // Finally, rematch.
9980 rematchAllNetworksAndRequests();
9981 }
9982
James Mattis45d81842021-01-10 14:24:24 -08009983 private void enforceAutomotiveDevice() {
9984 final boolean isAutomotiveDevice =
9985 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9986 if (!isAutomotiveDevice) {
9987 throw new UnsupportedOperationException(
9988 "setOemNetworkPreference() is only available on automotive devices.");
9989 }
9990 }
9991
9992 /**
9993 * Used by automotive devices to set the network preferences used to direct traffic at an
9994 * application level as per the given OemNetworkPreferences. An example use-case would be an
9995 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9996 * vehicle via a particular network.
9997 *
9998 * Calling this will overwrite the existing preference.
9999 *
James Mattisda32cfe2021-01-26 16:23:52 -080010000 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010001 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010002 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010003 */
James Mattis47db0582021-01-01 14:13:35 -080010004 @Override
James Mattis45d81842021-01-10 14:24:24 -080010005 public void setOemNetworkPreference(
10006 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010007 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010008
James Mattisfa270db2021-05-31 17:11:10 -070010009 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10010 // Only bypass the permission/device checks if this is a valid test request.
10011 if (isValidTestOemNetworkPreference(preference)) {
10012 enforceManageTestNetworksPermission();
10013 } else {
10014 enforceAutomotiveDevice();
10015 enforceOemNetworkPreferencesPermission();
10016 validateOemNetworkPreferences(preference);
10017 }
James Mattis45d81842021-01-10 14:24:24 -080010018
paulhu51f77dc2021-06-07 02:34:20 +000010019 // TODO: Have a priority for each preference.
10020 if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010021 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
10022 // handler thread. However it is an immutable object, so reading the reference is
10023 // safe - it's just possible the value is slightly outdated. For the final check,
10024 // see #handleSetOemPreference. But if this can be caught here it is a
10025 // lot easier to understand, so opportunistically check it.
10026 throwConcurrentPreferenceException();
10027 }
10028
James Mattis45d81842021-01-10 14:24:24 -080010029 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10030 new Pair<>(preference, listener)));
10031 }
10032
James Mattisfa270db2021-05-31 17:11:10 -070010033 /**
10034 * Check the validity of an OEM network preference to be used for testing purposes.
10035 * @param preference the preference to validate
10036 * @return true if this is a valid OEM network preference test request.
10037 */
10038 private boolean isValidTestOemNetworkPreference(
10039 @NonNull final OemNetworkPreferences preference) {
10040 // Allow for clearing of an existing OemNetworkPreference used for testing.
10041 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10042 // changes after this check is complete. This is an unlikely scenario as calling of this API
10043 // is controlled by the OEM therefore the added complexity is not worth adding given those
10044 // circumstances. That said, it is an edge case to be aware of hence this comment.
10045 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10046 && isTestOemNetworkPreference(mOemNetworkPreferences);
10047 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10048 }
10049
10050 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10051 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10052 return prefMap.size() == 1
10053 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10054 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10055 }
10056
James Mattis45d81842021-01-10 14:24:24 -080010057 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10058 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10059 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010060 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10061 throw new IllegalArgumentException(
10062 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10063 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010064 }
10065 }
10066 }
10067
10068 private void handleSetOemNetworkPreference(
10069 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010070 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010071 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10072 if (DBG) {
10073 log("set OEM network preferences :" + preference.toString());
10074 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010075 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
10076 // particular because it's not clear what preference should win in case both apply
10077 // to the same app.
10078 // The binder call has already checked this, but as mOemNetworkPreferences is only
10079 // touched on the handler thread, it's theoretically not impossible that it has changed
10080 // since.
paulhu51f77dc2021-06-07 02:34:20 +000010081 // TODO: Have a priority for each preference.
10082 if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010083 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
10084 return;
10085 }
10086
James Mattiscb1e0362021-04-06 17:07:42 -070010087 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
James Mattis20a4a8b2021-03-28 17:41:09 -070010088 final int uniquePreferenceCount = new ArraySet<>(
10089 preference.getNetworkPreferences().values()).size();
10090 mSystemNetworkRequestCounter.transact(
10091 mDeps.getCallingUid(), uniquePreferenceCount,
10092 () -> {
10093 final ArraySet<NetworkRequestInfo> nris =
10094 new OemNetworkRequestFactory()
10095 .createNrisFromOemNetworkPreferences(preference);
10096 replaceDefaultNetworkRequestsForPreference(nris);
10097 });
James Mattis45d81842021-01-10 14:24:24 -080010098 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010099
10100 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010101 try {
10102 listener.onComplete();
10103 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010104 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010105 }
James Mattis45d81842021-01-10 14:24:24 -080010106 }
10107 }
10108
Chalard Jean17215832021-03-01 14:06:28 +090010109 private void replaceDefaultNetworkRequestsForPreference(
James Mattis3ce3d3c2021-02-09 18:18:28 -080010110 @NonNull final Set<NetworkRequestInfo> nris) {
James Mattisc12c1f12021-02-20 14:40:51 -080010111 // Pass in a defensive copy as this collection will be updated on remove.
10112 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010113 addPerAppDefaultNetworkRequests(nris);
James Mattis45d81842021-01-10 14:24:24 -080010114 }
10115
James Mattis3ce3d3c2021-02-09 18:18:28 -080010116 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10117 ensureRunningOnConnectivityServiceThread();
10118 mDefaultNetworkRequests.addAll(nris);
10119 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10120 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010121 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
James Mattis20a4a8b2021-03-28 17:41:09 -070010122 mSystemNetworkRequestCounter.transact(
10123 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
10124 () -> {
10125 nrisToRegister.addAll(
10126 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10127 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10128 handleRegisterNetworkRequests(nrisToRegister);
10129 });
James Mattis3ce3d3c2021-02-09 18:18:28 -080010130 }
10131
10132 /**
10133 * All current requests that are tracking the default network need to be assessed as to whether
10134 * or not the current set of per-application default requests will be changing their default
10135 * network. If so, those requests will need to be updated so that they will send callbacks for
10136 * default network changes at the appropriate time. Additionally, those requests tracking the
10137 * default that were previously updated by this flow will need to be reassessed.
10138 * @return the nris which will need to be updated.
10139 */
10140 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10141 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10142 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10143 // same nri in the map's values for each of its NetworkRequest objects.
10144 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010145 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010146 // Include this nri if it is currently being tracked.
10147 if (isPerAppTrackedNri(nri)) {
10148 defaultCallbackRequests.add(nri);
10149 continue;
10150 }
10151 // We only track callbacks for requests tracking the default.
10152 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10153 continue;
10154 }
10155 // Include this nri if it will be tracked by the new per-app default requests.
10156 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010157 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010158 if (isNriGoingToBeTracked) {
10159 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010160 }
10161 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010162 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010163 }
10164
James Mattis3ce3d3c2021-02-09 18:18:28 -080010165 /**
10166 * Create nris for those network requests that are currently tracking the default network that
10167 * are being controlled by a per-application default.
10168 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10169 * foundation when creating the nri. Important items include the calling uid's original
10170 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10171 * requests are assumed to have already been validated as needing to be updated.
10172 * @return the Set of nris to use when registering network requests.
10173 */
10174 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10175 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10176 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10177 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10178 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010179 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010180
10181 // If this nri is not being tracked, the change it back to an untracked nri.
10182 if (trackingNri == mDefaultRequest) {
10183 callbackRequestsToRegister.add(new NetworkRequestInfo(
10184 callbackRequest,
10185 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10186 continue;
10187 }
10188
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010189 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010190 callbackRequestsToRegister.add(new NetworkRequestInfo(
10191 callbackRequest,
10192 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010193 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010194 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010195 }
10196 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010197 }
10198
Chalard Jean17215832021-03-01 14:06:28 +090010199 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10200 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010201 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010202 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010203 }
10204 }
10205
James Mattis45d81842021-01-10 14:24:24 -080010206 /**
10207 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10208 */
10209 @VisibleForTesting
10210 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010211 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010212 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010213 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010214 final SparseArray<Set<Integer>> uids =
10215 createUidsFromOemNetworkPreferences(preference);
10216 for (int i = 0; i < uids.size(); i++) {
10217 final int key = uids.keyAt(i);
10218 final Set<Integer> value = uids.valueAt(i);
10219 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10220 // No need to add an nri without any requests.
10221 if (0 == nri.mRequests.size()) {
10222 continue;
10223 }
10224 nris.add(nri);
10225 }
10226
10227 return nris;
10228 }
10229
10230 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10231 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010232 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010233 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010234 final List<UserHandle> users =
10235 mContext.getSystemService(UserManager.class).getUserHandles(true);
10236 if (null == users || users.size() == 0) {
10237 if (VDBG || DDBG) {
10238 log("No users currently available for setting the OEM network preference.");
10239 }
James Mattisb6b6a432021-06-01 22:30:36 -070010240 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010241 }
James Mattis45d81842021-01-10 14:24:24 -080010242 for (final Map.Entry<String, Integer> entry :
10243 preference.getNetworkPreferences().entrySet()) {
10244 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010245 // Add the rules for all users as this policy is device wide.
10246 for (final UserHandle user : users) {
10247 try {
10248 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10249 if (!prefToUids.contains(pref)) {
10250 prefToUids.put(pref, new ArraySet<>());
10251 }
10252 prefToUids.get(pref).add(uid);
10253 } catch (PackageManager.NameNotFoundException e) {
10254 // Although this may seem like an error scenario, it is ok that uninstalled
10255 // packages are sent on a network preference as the system will watch for
10256 // package installations associated with this network preference and update
10257 // accordingly. This is done to minimize race conditions on app install.
10258 continue;
James Mattis45d81842021-01-10 14:24:24 -080010259 }
James Mattis45d81842021-01-10 14:24:24 -080010260 }
10261 }
James Mattisb6b6a432021-06-01 22:30:36 -070010262 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010263 }
10264
10265 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10266 @OemNetworkPreferences.OemNetworkPreference final int preference,
10267 @NonNull final Set<Integer> uids) {
10268 final List<NetworkRequest> requests = new ArrayList<>();
10269 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10270 switch (preference) {
10271 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10272 requests.add(createUnmeteredNetworkRequest());
10273 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010274 requests.add(createDefaultInternetRequestForTransport(
10275 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010276 break;
10277 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10278 requests.add(createUnmeteredNetworkRequest());
10279 requests.add(createOemPaidNetworkRequest());
10280 break;
10281 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10282 requests.add(createOemPaidNetworkRequest());
10283 break;
10284 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10285 requests.add(createOemPrivateNetworkRequest());
10286 break;
James Mattisfa270db2021-05-31 17:11:10 -070010287 case OEM_NETWORK_PREFERENCE_TEST:
10288 requests.add(createUnmeteredNetworkRequest());
10289 requests.add(createTestNetworkRequest());
10290 requests.add(createDefaultRequest());
10291 break;
10292 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10293 requests.add(createTestNetworkRequest());
10294 break;
James Mattis45d81842021-01-10 14:24:24 -080010295 default:
10296 // This should never happen.
10297 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10298 + " called with invalid preference of " + preference);
10299 }
10300
James Mattisfa270db2021-05-31 17:11:10 -070010301 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010302 for (final int uid : uids) {
10303 ranges.add(new UidRange(uid, uid));
10304 }
10305 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010306 return new NetworkRequestInfo(
10307 Process.myUid(), requests, DEFAULT_NETWORK_PRIORITY_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010308 }
10309
10310 private NetworkRequest createUnmeteredNetworkRequest() {
10311 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10312 .addCapability(NET_CAPABILITY_NOT_METERED)
10313 .addCapability(NET_CAPABILITY_VALIDATED);
10314 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10315 }
10316
10317 private NetworkRequest createOemPaidNetworkRequest() {
10318 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10319 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10320 .addCapability(NET_CAPABILITY_OEM_PAID)
10321 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10322 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10323 }
10324
10325 private NetworkRequest createOemPrivateNetworkRequest() {
10326 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10327 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10328 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10329 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10330 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10331 }
10332
10333 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010334 final NetworkCapabilities netcap = new NetworkCapabilities();
10335 netcap.addCapability(NET_CAPABILITY_INTERNET);
10336 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10337 return netcap;
10338 }
10339
10340 private NetworkRequest createTestNetworkRequest() {
10341 final NetworkCapabilities netcap = new NetworkCapabilities();
10342 netcap.clearAll();
10343 netcap.addTransportType(TRANSPORT_TEST);
10344 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010345 }
James Mattis47db0582021-01-01 14:13:35 -080010346 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010347}