blob: 6c3a169b852bc43d0dcb9fe1b9da0324dd760418 [file] [log] [blame]
The Android Open Source Project9066cfe2009-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;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
lucasline252a742019-03-12 13:08:03 +080028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090029import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040030import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090032import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
34import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
lucasline252a742019-03-12 13:08:03 +080038import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090039import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060040import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080041import static android.net.NetworkPolicyManager.RULE_NONE;
42import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090043import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070044import static android.os.Process.INVALID_UID;
45import static android.system.OsConstants.IPPROTO_TCP;
46import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060047
Hugo Benichia0385682017-03-22 17:07:57 +090048import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060049
Chalard Jeanff46a252019-04-10 23:07:55 +090050import android.annotation.NonNull;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080051import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080052import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090053import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070054import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070055import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ContentResolver;
57import android.content.Context;
58import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070059import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070060import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070061import android.database.ContentObserver;
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +090062import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070063import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.ConnectivityManager;
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +090065import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.IConnectivityManager;
Luke Huang65914772019-03-16 00:31:46 +080067import android.net.IDnsResolver;
dalyk7301aa42018-03-05 12:42:22 -050068import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080069import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050070import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070071import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090072import android.net.INetworkMonitor;
73import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070074import android.net.INetworkPolicyListener;
75import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070076import android.net.INetworkStatsService;
junyulai7c469172019-01-16 20:23:34 +080077import android.net.ISocketKeepaliveCallback;
markchien6ea34542019-02-27 14:56:11 +080078import android.net.ITetheringEventCallback;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090079import android.net.InetAddresses;
80import android.net.IpPrefix;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080081import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070082import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010083import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080084import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070085import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070086import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070087import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070088import android.net.NetworkConfig;
Chalard Jean08577fc2018-05-02 21:14:54 +090089import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070091import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070092import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090093import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070094import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070095import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070096import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090097import android.net.NetworkStack;
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +090098import android.net.NetworkStackClient;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070099import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700100import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +0000101import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900102import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -0400103import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -0700104import android.net.RouteInfo;
junyulaie4135282019-01-03 18:50:15 +0800105import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400106import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -0400107import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600108import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900109import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900110import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700111import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900112import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900113import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900114import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800116import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700117import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700119import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700120import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700121import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.os.Looper;
123import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700124import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700125import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900126import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700127import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700128import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700129import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800130import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900131import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900132import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700133import android.os.ShellCallback;
134import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900135import android.os.SystemClock;
Anil Admale41992c2019-04-08 12:36:02 -0700136import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700137import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400138import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700140import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700141import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700142import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700143import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900144import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700145import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600146import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900147import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800148import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700149import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500150import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700151import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Wink Savilleab9321d2013-06-29 21:10:57 -0700154import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400155import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400156import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700157import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANd4a9de202019-01-30 22:01:20 +0900158import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700159import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700160import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800161import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700162import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900163import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700164import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600165import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700166import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900167import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900168import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700169import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700170import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400171import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900172import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500173import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900174import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900175import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100176import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700177import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900178import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700179import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600180import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900181import com.android.server.connectivity.NetworkNotificationManager;
182import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700183import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900184import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800185import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700186import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100187import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500188import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700189import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700190import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900191import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700192import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600193
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700194import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700195
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700196import org.xmlpull.v1.XmlPullParser;
197import org.xmlpull.v1.XmlPullParserException;
198
199import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700201import java.io.FileNotFoundException;
202import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700203import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700205import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700206import java.net.InetAddress;
207import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700208import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700209import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700210import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900211import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800212import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700213import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700214import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700215import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700216import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700217import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900218import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600219import java.util.SortedSet;
220import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222/**
223 * @hide
224 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800225public class ConnectivityService extends IConnectivityManager.Stub
226 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900227 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
Chalard Jean4133a122018-06-04 13:33:12 +0900229 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900230 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900231 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900232 private static final String NETWORK_ARG = "networks";
233 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900234
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900235 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900236 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
237 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900239 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700240
Remi NGUYEN VAN9ca4c622019-04-09 02:04:54 -0700241 /**
242 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
243 * by OEMs for configuration purposes, as this value is overridden by
244 * Settings.Global.CAPTIVE_PORTAL_HTTP_URL.
245 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
246 * (preferably via runtime resource overlays).
247 */
248 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
249 "http://connectivitycheck.gstatic.com/generate_204";
250
Jeff Sharkey899223b2012-08-04 15:24:58 -0700251 // TODO: create better separation between radio types and network types
252
Robert Greenwalt42acef32009-08-12 16:08:25 -0700253 // how long to wait before switching back to a radio's default network
254 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
255 // system property that can override the above value
256 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
257 "android.telephony.apn-restore";
258
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900259 // How long to wait before putting up a "This network doesn't have an Internet connection,
260 // connect anyway?" dialog after the user selects a network that doesn't validate.
261 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
262
lucaslind2e045e02019-01-24 15:55:30 +0800263 // How long to dismiss network notification.
264 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
265
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900266 // Default to 30s linger time-out. Modifiable only for testing.
267 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
268 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
269 @VisibleForTesting
270 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
271
Jeremy Joslin79294842014-12-03 17:15:28 -0800272 // How long to delay to removal of a pending intent based request.
273 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
274 private final int mReleasePendingIntentDelayMs;
275
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900276 private MockableSystemProperties mSystemProperties;
277
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800278 private Tethering mTethering;
279
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700280 private final PermissionMonitor mPermissionMonitor;
281
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700282 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700283
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900284 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700285 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900286 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700287
Hugo Benichi69744342017-11-27 10:57:16 +0900288 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
289 // a direct call to LockdownVpnTracker.isEnabled().
290 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700291 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900292 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700293 private LockdownVpnTracker mLockdownTracker;
294
junyulai05986c62018-08-07 19:50:45 +0800295 /**
296 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
297 * handler thread, they don't need a lock.
298 */
299 private SparseIntArray mUidRules = new SparseIntArray();
300 /** Flag indicating if background data is restricted. */
301 private boolean mRestrictBackground;
302
Erik Klineda4bfa82015-04-30 12:58:40 +0900303 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700304 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700305 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306
Luke Huang4e25ec62018-09-27 16:58:23 +0800307 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800308 @VisibleForTesting
Luke Huang65914772019-03-16 00:31:46 +0800309 protected IDnsResolver mDnsResolver;
310 @VisibleForTesting
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800311 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800312 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700313 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900314 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700315
Benedict Wong99a48412018-11-09 14:45:34 -0800316 /**
317 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
318 * instances.
319 */
320 @GuardedBy("mTNSLock")
321 private TestNetworkService mTNS;
322
323 private final Object mTNSLock = new Object();
324
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700325 private String mCurrentTcpBufferSizes;
326
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900327 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900328 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
329 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900330
Paul Jensenb10e37f2014-11-25 12:33:08 -0500331 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400332 // Tear down networks that have no chance (e.g. even if validated) of becoming
333 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500334 // all networks have been rematched against all NetworkRequests.
335 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400336 // Don't reap networks. This should be passed when some networks have not yet been
337 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500338 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900339 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500340
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900341 private enum UnneededFor {
342 LINGER, // Determine whether this network is unneeded and should be lingered.
343 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
344 }
345
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700346 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700347 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700348 * from one net to another. Clear happens when we get a new
349 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
350 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700351 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700352 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700353
Robert Greenwalt434203a2010-10-11 16:00:27 -0700354 /**
355 * used internally to reload global proxy settings
356 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700357 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700358
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700359 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400360 * PAC manager has received new port.
361 */
362 private static final int EVENT_PROXY_HAS_CHANGED = 16;
363
Robert Greenwalte049c232014-04-11 15:53:27 -0700364 /**
365 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700366 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700367 */
368 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
369
Robert Greenwalt7b816022014-04-18 15:25:25 -0700370 /**
371 * used internally when registering NetworkAgents
372 * obj = Messenger
373 */
374 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
375
Robert Greenwalt9258c642014-03-26 16:47:06 -0700376 /**
377 * used to add a network request
378 * includes a NetworkRequestInfo
379 */
380 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
381
382 /**
383 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900384 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700385 * cancel it.
386 * includes a NetworkRequestInfo
387 */
388 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
389
390 /**
391 * used to add a network listener - no request
392 * includes a NetworkRequestInfo
393 */
394 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
395
396 /**
397 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400398 * arg1 = UID of caller
399 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700400 */
401 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
402
Robert Greenwalta67be032014-05-16 15:49:14 -0700403 /**
404 * used internally when registering NetworkFactories
405 * obj = Messenger
406 */
407 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
408
Robert Greenwalt27711812014-06-25 16:45:57 -0700409 /**
410 * used internally to expire a wakelock when transitioning
411 * from one net to another. Expire happens when we fail to find
412 * a new network (typically after 1 minute) -
413 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
414 * a replacement network.
415 */
416 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
417
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700418 /**
419 * Used internally to indicate the system is ready.
420 */
421 private static final int EVENT_SYSTEM_READY = 25;
422
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800423 /**
424 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400425 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800426 */
427 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
428
429 /**
430 * used to remove a pending intent and its associated network request.
431 * arg1 = UID of caller
432 * obj = PendingIntent
433 */
434 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
435
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900436 /**
437 * used to specify whether a network should be used even if unvalidated.
438 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
439 * arg2 = whether to remember this choice in the future (1 or 0)
440 * obj = network
441 */
442 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
443
444 /**
445 * used to ask the user to confirm a connection to an unvalidated network.
446 * obj = network
447 */
448 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700449
Erik Klineda4bfa82015-04-30 12:58:40 +0900450 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700451 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900452 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700453 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900454
Paul Jensen694f2b82015-06-17 14:15:39 -0400455 /**
456 * used to add a network listener with a pending intent
457 * obj = NetworkRequestInfo
458 */
459 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
460
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900461 /**
462 * used to specify whether a network should not be penalized when it becomes unvalidated.
463 */
464 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
465
466 /**
467 * used to trigger revalidation of a network.
468 */
469 private static final int EVENT_REVALIDATE_NETWORK = 36;
470
Erik Klinea24d4592018-01-11 21:07:29 +0900471 // Handle changes in Private DNS settings.
472 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
473
dalyk7301aa42018-03-05 12:42:22 -0500474 // Handle private DNS validation status updates.
475 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
476
junyulai05986c62018-08-07 19:50:45 +0800477 /**
478 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
479 */
480 private static final int EVENT_UID_RULES_CHANGED = 39;
481
482 /**
483 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
484 */
485 private static final int EVENT_DATA_SAVER_CHANGED = 40;
486
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900487 /**
488 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
489 * been tested.
490 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
491 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
492 * arg2 = NetID.
493 */
494 public static final int EVENT_NETWORK_TESTED = 41;
495
496 /**
497 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
498 * config was resolved.
499 * obj = PrivateDnsConfig
500 * arg2 = netid
501 */
502 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
503
504 /**
505 * Request ConnectivityService display provisioning notification.
506 * arg1 = Whether to make the notification visible.
507 * arg2 = NetID.
508 * obj = Intent to be launched when notification selected by user, null if !arg1.
509 */
510 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
511
512 /**
lucaslind2e045e02019-01-24 15:55:30 +0800513 * This event can handle dismissing notification by given network id.
514 */
515 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
516
517 /**
lucasline252a742019-03-12 13:08:03 +0800518 * Used to specify whether a network should be used even if connectivity is partial.
519 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
520 * false)
521 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
522 * obj = network
523 */
524 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
525
526 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900527 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
528 * should be shown.
529 */
530 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
531
532 /**
533 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
534 * should be hidden.
535 */
536 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
537
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900538 private static String eventName(int what) {
539 return sMagicDecoderRing.get(what, Integer.toString(what));
540 }
541
Luke Huang65914772019-03-16 00:31:46 +0800542 private static IDnsResolver getDnsResolver() {
543 return IDnsResolver.Stub
544 .asInterface(ServiceManager.getService("dnsresolver"));
545 }
546
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900547 /** Handler thread used for both of the handlers below. */
548 @VisibleForTesting
549 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700550 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700551 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700552 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700553 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900554 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700555
Mike Lockwood0f79b542009-08-14 14:18:49 -0400556 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800557 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400558
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700559 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700560 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800561 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700562
Chalard Jean52c2aa72018-06-07 16:44:04 +0900563 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
564 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000565 @VisibleForTesting
566 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400567
Erik Klineda4bfa82015-04-30 12:58:40 +0900568 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700569
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400570 private UserManager mUserManager;
571
Chalard Jean4133a122018-06-04 13:33:12 +0900572 private NetworkConfig[] mNetConfigs;
573 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700574
Robert Greenwalt50393202011-06-21 17:26:14 -0700575 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900576 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700577
Chalard Jean4133a122018-06-04 13:33:12 +0900578 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400579
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900580 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900581 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900582 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900583
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700584 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800585 private static final int MIN_NET_ID = 100; // some reserved marks
586 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700587 private int mNextNetId = MIN_NET_ID;
588
Robert Greenwalt34524f02014-05-18 16:22:10 -0700589 // sequence number of NetworkRequests
590 private int mNextNetworkRequestId = 1;
591
Erik Kline7523eb32015-07-09 18:24:03 +0900592 // NetworkRequest activity String log entries.
593 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
594 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
595
Hugo Benichic2ae2872016-07-11 11:05:12 +0900596 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900597 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900598 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
599
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900600 private static final int MAX_WAKELOCK_LOGS = 20;
601 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900602 private int mTotalWakelockAcquisitions = 0;
603 private int mTotalWakelockReleases = 0;
604 private long mTotalWakelockDurationMs = 0;
605 private long mMaxWakelockDurationMs = 0;
606 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900607
Hugo Benichif9fdf872016-07-28 17:53:06 +0900608 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900609
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700610 @GuardedBy("mBandwidthRequests")
611 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
612
Erik Kline065ab6e2016-10-02 18:02:14 +0900613 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900614 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900615
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900616 @VisibleForTesting
617 final MultipathPolicyTracker mMultipathPolicyTracker;
618
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 /**
620 * Implements support for the legacy "one network per network type" model.
621 *
622 * We used to have a static array of NetworkStateTrackers, one for each
623 * network type, but that doesn't work any more now that we can have,
624 * for example, more that one wifi network. This class stores all the
625 * NetworkAgentInfo objects that support a given type, but the legacy
626 * API will only see the first one.
627 *
628 * It serves two main purposes:
629 *
630 * 1. Provide information about "the network for a given type" (since this
631 * API only supports one).
632 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
633 * the first network for a given type changes, or if the default network
634 * changes.
635 */
Chalard Jeanff46a252019-04-10 23:07:55 +0900636 @VisibleForTesting
637 static class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900638
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900639 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900640 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900641
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700642 /**
643 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
644 * Each list holds references to all NetworkAgentInfos that are used to
645 * satisfy requests for that network type.
646 *
647 * This array is built out at startup such that an unsupported network
648 * doesn't get an ArrayList instance, making this a tristate:
649 * unsupported, supported but not active and active.
650 *
651 * The actual lists are populated when we scan the network types that
652 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900653 *
654 * Threading model:
655 * - addSupportedType() is only called in the constructor
656 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
657 * They are therefore not thread-safe with respect to each other.
658 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
659 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
660 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700661 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900662 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jeanff46a252019-04-10 23:07:55 +0900663 @NonNull
664 private final ConnectivityService mService;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700665
Chalard Jeanff46a252019-04-10 23:07:55 +0900666 LegacyTypeTracker(@NonNull ConnectivityService service) {
667 mService = service;
668 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700669 }
670
671 public void addSupportedType(int type) {
672 if (mTypeLists[type] != null) {
673 throw new IllegalStateException(
674 "legacy list for type " + type + "already initialized");
675 }
Chalard Jean4133a122018-06-04 13:33:12 +0900676 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700677 }
678
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700679 public boolean isTypeSupported(int type) {
680 return isNetworkTypeValid(type) && mTypeLists[type] != null;
681 }
682
683 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900684 synchronized (mTypeLists) {
685 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
686 return mTypeLists[type].get(0);
687 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700688 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900689 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
691
Robert Greenwalt8d482522015-06-24 13:23:42 -0700692 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900693 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900694 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700695 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900696 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900697 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900698 }
699 }
700
701 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700702 public void add(int type, NetworkAgentInfo nai) {
703 if (!isTypeSupported(type)) {
704 return; // Invalid network type.
705 }
706 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
707
708 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
709 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700710 return;
711 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900712 synchronized (mTypeLists) {
713 list.add(nai);
714 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900715
716 // Send a broadcast if this is the first network of its type or if it's the default.
Chalard Jeanff46a252019-04-10 23:07:55 +0900717 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900718 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700719 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
Chalard Jeanff46a252019-04-10 23:07:55 +0900720 mService.sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700721 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700722 }
723
Lorenzo Colittia793a672014-07-31 23:20:17 +0900724 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900725 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900726 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
727 if (list == null || list.isEmpty()) {
728 return;
729 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900730 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900731
Hugo Benichi78caa2582016-06-21 09:48:07 +0900732 synchronized (mTypeLists) {
733 if (!list.remove(nai)) {
734 return;
735 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900736 }
737
Robert Greenwalt8d482522015-06-24 13:23:42 -0700738 final DetailedState state = DetailedState.DISCONNECTED;
739
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900740 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700741 maybeLogBroadcast(nai, state, type, wasDefault);
Chalard Jeanff46a252019-04-10 23:07:55 +0900742 mService.sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900743 }
744
745 if (!list.isEmpty() && wasFirstNetwork) {
746 if (DBG) log("Other network available for type " + type +
747 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900748 final NetworkAgentInfo replacement = list.get(0);
Chalard Jeanff46a252019-04-10 23:07:55 +0900749 maybeLogBroadcast(replacement, state, type, mService.isDefaultNetwork(replacement));
750 mService.sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900751 }
752 }
753
754 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900755 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
756 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700757 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900758 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700759 }
760 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700761
Robert Greenwalt8d482522015-06-24 13:23:42 -0700762 // send out another legacy broadcast - currently only used for suspend/unsuspend
763 // toggle
764 public void update(NetworkAgentInfo nai) {
Chalard Jeanff46a252019-04-10 23:07:55 +0900765 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700766 final DetailedState state = nai.networkInfo.getDetailedState();
767 for (int type = 0; type < mTypeLists.length; type++) {
768 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700769 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900770 final boolean isFirst = contains && (nai == list.get(0));
771 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700772 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jeanff46a252019-04-10 23:07:55 +0900773 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700774 }
775 }
776 }
777
Lorenzo Colittia793a672014-07-31 23:20:17 +0900778 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900779 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900780 String state = (nai.networkInfo != null) ?
781 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
782 "???/???";
783 return name + " " + state;
784 }
785
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700786 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900787 pw.println("mLegacyTypeTracker:");
788 pw.increaseIndent();
789 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700790 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900791 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700792 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900793 pw.println();
794 pw.println("Current state:");
795 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900796 synchronized (mTypeLists) {
797 for (int type = 0; type < mTypeLists.length; type++) {
798 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
799 for (NetworkAgentInfo nai : mTypeLists[type]) {
800 pw.println(type + " " + naiToString(nai));
801 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900802 }
803 }
804 pw.decreaseIndent();
805 pw.decreaseIndent();
806 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700807 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700808 }
Chalard Jeanff46a252019-04-10 23:07:55 +0900809 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700810
Vishnu Nair5c010902017-10-26 10:08:50 -0700811 /**
812 * Helper class which parses out priority arguments and dumps sections according to their
813 * priority. If priority arguments are omitted, function calls the legacy dump command.
814 */
815 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
816 @Override
817 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
818 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
819 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
820 }
821
822 @Override
823 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
824 doDump(fd, pw, args, asProto);
825 }
826
827 @Override
828 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
829 doDump(fd, pw, args, asProto);
830 }
831 };
832
Jeff Sharkey899223b2012-08-04 15:24:58 -0700833 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700834 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Luke Huang65914772019-03-16 00:31:46 +0800835 this(context, netManager, statsService, policyManager,
836 getDnsResolver(), new IpConnectivityLog());
Hugo Benichif9fdf872016-07-28 17:53:06 +0900837 }
838
839 @VisibleForTesting
840 protected ConnectivityService(Context context, INetworkManagementService netManager,
841 INetworkStatsService statsService, INetworkPolicyManager policyManager,
Luke Huang65914772019-03-16 00:31:46 +0800842 IDnsResolver dnsresolver, IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800843 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800844
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900845 mSystemProperties = getSystemProperties();
846
Hugo Benichif9fdf872016-07-28 17:53:06 +0900847 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900848 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900849 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900850 mNetworkRequests.put(mDefaultRequest, defaultNRI);
851 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900852
Chalard Jeandda156a2018-01-10 21:19:32 +0900853 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900854 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700855
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700856 // The default WiFi request is a background request so that apps using WiFi are
857 // migrated to a better network (typically ethernet) when one comes up, instead
858 // of staying on WiFi forever.
859 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
860 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
861
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900862 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900863 mHandlerThread.start();
864 mHandler = new InternalHandler(mHandlerThread.getLooper());
865 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700866
Jeremy Joslin79294842014-12-03 17:15:28 -0800867 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
868 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
869
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900870 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900871
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700872 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800873 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800874 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700875 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900876 mPolicyManagerInternal = checkNotNull(
877 LocalServices.getService(NetworkPolicyManagerInternal.class),
878 "missing NetworkPolicyManagerInternal");
Luke Huang65914772019-03-16 00:31:46 +0800879 mDnsResolver = checkNotNull(dnsresolver, "missing IDnsResolver");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000880 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900881
Luke Huang674660f2018-09-27 19:33:11 +0800882 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700883 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700884 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700885
junyulai05986c62018-08-07 19:50:45 +0800886 // To ensure uid rules are synchronized with Network Policy, register for
887 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
888 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700889 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900890 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700891 } catch (RemoteException e) {
892 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700893 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700894 }
895
896 final PowerManager powerManager = (PowerManager) context.getSystemService(
897 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700898 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
899 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
900 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800901 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700902
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700903 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700904
Wink Saville51f456f2013-04-23 14:26:51 -0700905 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900906 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700907 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700908 String[] naStrings = context.getResources().getStringArray(
909 com.android.internal.R.array.networkAttributes);
910 for (String naString : naStrings) {
911 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700912 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700913 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700914 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800915 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700916 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700917 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700918 }
Wink Saville51f456f2013-04-23 14:26:51 -0700919 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
920 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
921 n.type);
922 continue;
923 }
Wink Saville975c8482011-04-07 14:23:45 -0700924 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800925 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700926 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700927 continue;
928 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700929 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700930
Wink Saville975c8482011-04-07 14:23:45 -0700931 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700932 mNetworksDefined++;
933 } catch(Exception e) {
934 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700935 }
936 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700937
938 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
939 if (mNetConfigs[TYPE_VPN] == null) {
940 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
941 // don't need to add TYPE_VPN to mNetConfigs.
942 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
943 mNetworksDefined++; // used only in the log() statement below.
944 }
945
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900946 // Do the same for Ethernet, since it's often not specified in the configs, although many
947 // devices can use it via USB host adapters.
948 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
949 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
950 mNetworksDefined++;
951 }
952
Wink Saville5e56bc52013-07-29 15:00:57 -0700953 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700954
Robert Greenwalt50393202011-06-21 17:26:14 -0700955 mProtectedNetworks = new ArrayList<Integer>();
956 int[] protectedNetworks = context.getResources().getIntArray(
957 com.android.internal.R.array.config_protectedNetworks);
958 for (int p : protectedNetworks) {
959 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
960 mProtectedNetworks.add(p);
961 } else {
962 if (DBG) loge("Ignoring protectedNetwork " + p);
963 }
964 }
965
Erik Kline47222fc2017-04-30 19:36:15 +0900966 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800967
Chenbo Feng436fe582019-02-25 22:55:58 -0800968 mPermissionMonitor = new PermissionMonitor(mContext, mNMS, mNetd);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700969
Varun Anand4fa80e82019-02-06 10:13:38 -0800970 // Set up the listener for user state for creating user VPNs.
971 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700972 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100973 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700974 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700975 intentFilter.addAction(Intent.ACTION_USER_ADDED);
976 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000977 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700978 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800979 mIntentReceiver,
980 UserHandle.ALL,
981 intentFilter,
982 null /* broadcastPermission */,
983 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000984 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
985 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900986
junyulai2454b692018-11-01 17:16:31 +0800987 // Listen to package add and removal events for all users.
988 intentFilter = new IntentFilter();
989 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800990 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800991 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
992 intentFilter.addDataScheme("package");
993 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800994 mIntentReceiver,
995 UserHandle.ALL,
996 intentFilter,
997 null /* broadcastPermission */,
998 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800999
Chia-chi Yeh008ff392011-05-23 15:08:29 -07001000 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001001 mNMS.registerObserver(mTethering);
1002 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -07001003 } catch (RemoteException e) {
1004 loge("Error registering observer :" + e);
1005 }
1006
Erik Klineda4bfa82015-04-30 12:58:40 +09001007 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1008 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -08001009
Chalard Jean4133a122018-06-04 13:33:12 +09001010 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
1011 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -04001012
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04001013 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001014
junyulai0c666972019-03-04 22:45:36 +08001015 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +09001016 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
1017 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +09001018
1019 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1020 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1021 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1022 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1023 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1024 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1025 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09001026
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001027 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +09001028 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001029 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +09001030
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001031 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1032
Luke Huang65914772019-03-16 00:31:46 +08001033 mDnsManager = new DnsManager(mContext, mDnsResolver, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001034 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001036
Mike Yuf9729752018-08-17 15:22:05 +08001037 @VisibleForTesting
1038 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001039 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001040 final TetheringDependencies deps = new TetheringDependencies() {
1041 @Override
1042 public boolean isTetheringSupported() {
1043 return ConnectivityService.this.isTetheringSupported();
1044 }
Erik Kline72302902018-06-14 17:36:40 +09001045 @Override
1046 public NetworkRequest getDefaultNetworkRequest() {
1047 return mDefaultRequest;
1048 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001049 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001050 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001051 IoThread.get().getLooper(), new MockableSystemProperties(),
1052 deps);
1053 }
1054
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001055 @VisibleForTesting
1056 protected ProxyTracker makeProxyTracker() {
1057 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1058 }
1059
Chalard Jean26400492018-04-18 20:18:38 +09001060 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1061 final NetworkCapabilities netCap = new NetworkCapabilities();
1062 netCap.addCapability(NET_CAPABILITY_INTERNET);
1063 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1064 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1065 netCap.setSingleUid(uid);
1066 return netCap;
1067 }
1068
Chalard Jeandda156a2018-01-10 21:19:32 +09001069 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001070 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001071 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001072 netCap.addCapability(NET_CAPABILITY_INTERNET);
1073 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001074 if (transportType > -1) {
1075 netCap.addTransportType(transportType);
1076 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001077 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001078 }
1079
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001080 // Used only for testing.
1081 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001082 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001083 // changing ContentResolver to make registerContentObserver non-final).
1084 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1085 // by subclassing SettingsObserver.
1086 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001087 void updateAlwaysOnNetworks() {
1088 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001089 }
1090
Erik Kline736353a2018-03-21 07:18:33 -07001091 // See FakeSettingsProvider comment above.
1092 @VisibleForTesting
1093 void updatePrivateDnsSettings() {
1094 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1095 }
1096
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001097 private void handleAlwaysOnNetworkRequest(
1098 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001099 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001100 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1101 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001102 if (enable == isEnabled) {
1103 return; // Nothing to do.
1104 }
1105
1106 if (enable) {
1107 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001108 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001109 } else {
Etan Cohenae574a82019-01-08 12:09:18 -08001110 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1111 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001112 }
1113 }
1114
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001115 private void handleConfigureAlwaysOnNetworks() {
1116 handleAlwaysOnNetworkRequest(
1117 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1118 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1119 false);
1120 }
1121
Erik Klineda4bfa82015-04-30 12:58:40 +09001122 private void registerSettingsCallbacks() {
1123 // Watch for global HTTP proxy changes.
1124 mSettingsObserver.observe(
1125 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1126 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1127
1128 // Watch for whether or not to keep mobile data always on.
1129 mSettingsObserver.observe(
1130 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001131 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1132
1133 // Watch for whether or not to keep wifi always on.
1134 mSettingsObserver.observe(
1135 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1136 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001137 }
1138
Erik Klinea24d4592018-01-11 21:07:29 +09001139 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001140 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1141 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001142 }
1143 }
1144
Robert Greenwalt34524f02014-05-18 16:22:10 -07001145 private synchronized int nextNetworkRequestId() {
1146 return mNextNetworkRequestId++;
1147 }
1148
Paul Jensen67b0b072015-06-10 11:22:17 -04001149 @VisibleForTesting
1150 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001151 synchronized (mNetworkForNetId) {
1152 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1153 int netId = mNextNetId;
1154 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1155 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001156 if (!mNetIdInUse.get(netId)) {
1157 mNetIdInUse.put(netId, true);
1158 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001159 }
1160 }
1161 }
1162 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001163 }
1164
Chalard Jeanc0982912018-06-07 16:11:34 +09001165 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1168 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 state = nai.getNetworkState();
1171 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 final NetworkInfo info = new NetworkInfo(networkType, 0,
1174 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1176 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001177 final NetworkCapabilities capabilities = new NetworkCapabilities();
1178 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1179 !info.isRoaming());
1180 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001181 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001183 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 return state;
1185 } else {
1186 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001188 }
1189
junyulai4a192e22018-06-13 15:00:37 +08001190 @VisibleForTesting
1191 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001192 if (network == null) {
1193 return null;
1194 }
Erik Kline736353a2018-03-21 07:18:33 -07001195 return getNetworkAgentInfoForNetId(network.netId);
1196 }
1197
1198 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001199 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001200 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001202 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001204 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001205 synchronized (mVpns) {
1206 if (!mLockdownEnabled) {
1207 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001208 Vpn vpn = mVpns.get(user);
1209 if (vpn != null && vpn.appliesToUid(uid)) {
1210 return vpn.getUnderlyingNetworks();
1211 }
1212 }
1213 }
1214 return null;
1215 }
1216
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001217 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001218 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001219
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001220 final Network[] networks = getVpnUnderlyingNetworks(uid);
1221 if (networks != null) {
1222 // getUnderlyingNetworks() returns:
1223 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1224 // empty array => the VPN explicitly said "no default network".
1225 // non-empty array => the VPN specified one or more default networks; we use the
1226 // first one.
1227 if (networks.length > 0) {
1228 nai = getNetworkAgentInfoForNetwork(networks[0]);
1229 } else {
1230 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001231 }
1232 }
1233
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001234 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001235 return nai.getNetworkState();
1236 } else {
1237 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001239 }
1240
1241 /**
1242 * Check if UID should be blocked from using the network with the given LinkProperties.
1243 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001244 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1245 boolean ignoreBlocked) {
1246 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001247 if (ignoreBlocked) {
1248 return false;
1249 }
Robin Lee17e61832016-05-09 13:46:28 +01001250 synchronized (mVpns) {
1251 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001252 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001253 return true;
1254 }
1255 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001256 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001257 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001258 }
1259
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001260 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001261 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1262 return;
1263 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001264 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001265 synchronized (mBlockedAppUids) {
1266 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001267 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001268 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001269 blocked = false;
1270 } else {
1271 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001272 }
1273 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001274 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1275 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1276 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001277 }
1278
junyulai05986c62018-08-07 19:50:45 +08001279 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1280 boolean blocked) {
1281 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1282 return;
1283 }
1284 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1285 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1286 nri.mUid, nri.request.requestId, net.netId));
1287 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1288 }
1289
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001290 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001291 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1292 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001293 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001294 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001295 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001296 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1297
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001298 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001299 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001300 }
Hugo Benichi69744342017-11-27 10:57:16 +09001301 synchronized (mVpns) {
1302 if (mLockdownTracker != null) {
1303 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1304 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001305 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001306 }
1307
1308 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 * Return NetworkInfo for the active (i.e., connected) network interface.
1310 * It is assumed that at most one network is active at a time. If more
1311 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001312 * @return the info for the active network, or {@code null} if none is
1313 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001315 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001317 enforceAccessPermission();
1318 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001319 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001320 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001321 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1322 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324
Paul Jensen31a94f42015-02-13 14:18:39 -05001325 @Override
1326 public Network getActiveNetwork() {
1327 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001328 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001329 }
1330
1331 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001332 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001333 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001334 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001335 }
1336
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001337 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001338 final int user = UserHandle.getUserId(uid);
1339 int vpnNetId = NETID_UNSET;
1340 synchronized (mVpns) {
1341 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001342 // TODO : now that capabilities contain the UID, the appliesToUid test should
1343 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001344 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1345 }
1346 NetworkAgentInfo nai;
1347 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001348 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001349 if (nai != null) {
1350 final NetworkCapabilities requiredCaps =
1351 createDefaultNetworkCapabilitiesForUid(uid);
1352 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1353 return nai.network;
1354 }
1355 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001356 }
1357 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001358 if (nai != null
1359 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1360 nai = null;
1361 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001362 return nai != null ? nai.network : null;
1363 }
1364
Lorenzo Colitti18660282016-07-04 12:55:44 +09001365 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001366 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1367 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001368 final int uid = Binder.getCallingUid();
1369 NetworkState state = getUnfilteredActiveNetworkState(uid);
1370 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001371 }
1372
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001373 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001374 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001376 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001377 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001378 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 }
1380
1381 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 public NetworkInfo getNetworkInfo(int networkType) {
1383 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001385 if (getVpnUnderlyingNetworks(uid) != null) {
1386 // A VPN is active, so we may need to return one of its underlying networks. This
1387 // information is not available in LegacyTypeTracker, so we have to get it from
1388 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001389 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001390 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001391 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001392 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001393 }
1394 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001395 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001396 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 }
1398
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001399 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001400 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001401 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001402 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001403 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001404 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001405 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001406 return state.networkInfo;
1407 } else {
1408 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001409 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001410 }
1411
1412 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 public NetworkInfo[] getAllNetworkInfo() {
1414 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001415 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001416 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1417 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001418 NetworkInfo info = getNetworkInfo(networkType);
1419 if (info != null) {
1420 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001423 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001426 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001427 public Network getNetworkForType(int networkType) {
1428 enforceAccessPermission();
1429 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001430 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001431 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001432 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001433 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001434 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001435 }
1436
1437 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001438 public Network[] getAllNetworks() {
1439 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001440 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001441 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001442 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001443 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001444 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001445 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001446 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001447 }
1448
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001449 @Override
1450 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1451 // The basic principle is: if an app's traffic could possibly go over a
1452 // network, without the app doing anything multinetwork-specific,
1453 // (hence, by "default"), then include that network's capabilities in
1454 // the array.
1455 //
1456 // In the normal case, app traffic only goes over the system's default
1457 // network connection, so that's the only network returned.
1458 //
1459 // With a VPN in force, some app traffic may go into the VPN, and thus
1460 // over whatever underlying networks the VPN specifies, while other app
1461 // traffic may go over the system default network (e.g.: a split-tunnel
1462 // VPN, or an app disallowed by the VPN), so the set of networks
1463 // returned includes the VPN's underlying networks and the system
1464 // default.
1465 enforceAccessPermission();
1466
Chalard Jean4133a122018-06-04 13:33:12 +09001467 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001468
1469 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001470 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001471 if (nc != null) {
1472 result.put(nai.network, nc);
1473 }
1474
Hugo Benichi69744342017-11-27 10:57:16 +09001475 synchronized (mVpns) {
1476 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001477 Vpn vpn = mVpns.get(userId);
1478 if (vpn != null) {
1479 Network[] networks = vpn.getUnderlyingNetworks();
1480 if (networks != null) {
1481 for (Network network : networks) {
1482 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001483 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001484 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001485 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001486 }
1487 }
1488 }
1489 }
1490 }
1491 }
1492
1493 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1494 out = result.values().toArray(out);
1495 return out;
1496 }
1497
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001498 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001499 public boolean isNetworkSupported(int networkType) {
1500 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001501 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001502 }
1503
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001504 /**
1505 * Return LinkProperties for the active (i.e., connected) default
1506 * network interface. It is assumed that at most one default network
1507 * is active at a time. If more than one is active, it is indeterminate
1508 * which will be returned.
1509 * @return the ip properties for the active network, or {@code null} if
1510 * none is active
1511 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001512 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001513 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001514 enforceAccessPermission();
1515 final int uid = Binder.getCallingUid();
1516 NetworkState state = getUnfilteredActiveNetworkState(uid);
1517 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001518 }
1519
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001520 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001521 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001522 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001523 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1524 if (nai != null) {
1525 synchronized (nai) {
1526 return new LinkProperties(nai.linkProperties);
1527 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001528 }
1529 return null;
1530 }
1531
Robert Greenwalt12e67352014-05-13 21:41:06 -07001532 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001533 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001534 public LinkProperties getLinkProperties(Network network) {
1535 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001536 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1537 }
1538
1539 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1540 if (nai == null) {
1541 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001542 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001543 synchronized (nai) {
1544 return new LinkProperties(nai.linkProperties);
1545 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001546 }
1547
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001548 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001549 if (nai != null) {
1550 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001551 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001552 return networkCapabilitiesRestrictedForCallerPermissions(
1553 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001554 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001555 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001556 }
1557 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001558 return null;
1559 }
1560
1561 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001562 public NetworkCapabilities getNetworkCapabilities(Network network) {
1563 enforceAccessPermission();
1564 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1565 }
1566
Chalard Jeanb03a6222018-04-11 21:09:10 +09001567 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001568 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001569 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001570 if (!checkSettingsPermission(callerPid, callerUid)) {
1571 newNc.setUids(null);
1572 newNc.setSSID(null);
1573 }
Etan Cohen836ad572018-12-30 17:59:59 -08001574 if (newNc.getNetworkSpecifier() != null) {
1575 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1576 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001577 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001578 }
1579
Chalard Jeanb552c462018-02-21 18:43:54 +09001580 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1581 if (!checkSettingsPermission()) {
1582 nc.setSingleUid(Binder.getCallingUid());
1583 }
1584 }
1585
Chalard Jean26aa91a2018-03-20 19:13:57 +09001586 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1587 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1588 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1589 }
1590 }
1591
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001592 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001593 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001594 // Require internal since we're handing out IMSI details
1595 enforceConnectivityInternalPermission();
1596
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001597 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001598 for (Network network : getAllNetworks()) {
1599 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1600 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001601 // TODO (b/73321673) : NetworkState contains a copy of the
1602 // NetworkCapabilities, which may contain UIDs of apps to which the
1603 // network applies. Should the UIDs be cleared so as not to leak or
1604 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001605 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001606 }
1607 }
1608 return result.toArray(new NetworkState[result.size()]);
1609 }
1610
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001611 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001612 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001613 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001614 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1615 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1616 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001617 }
1618
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001619 @Override
1620 public boolean isActiveNetworkMetered() {
1621 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001622
Varun Anandc51b06d2019-02-25 17:22:02 -08001623 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001624 if (caps != null) {
1625 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1626 } else {
1627 // Always return the most conservative value
1628 return true;
1629 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001630 }
1631
Jeff Sharkey216c1812012-08-05 14:29:23 -07001632 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1633 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001634 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001635 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001636 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001637 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001638 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001639
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001640 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001641 * Ensures that the system cannot call a particular method.
1642 */
1643 private boolean disallowedBecauseSystemCaller() {
1644 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale41992c2019-04-08 12:36:02 -07001645 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
1646 // for devices launched with Q and above. However, existing devices upgrading to Q and
1647 // above must continued to be supported for few more releases.
1648 if (isSystem(Binder.getCallingUid()) && SystemProperties.getInt(
1649 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001650 log("This method exists only for app backwards compatibility"
1651 + " and must not be called by system services.");
1652 return true;
1653 }
1654 return false;
1655 }
1656
1657 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 * Ensure that a network route exists to deliver traffic to the specified
1659 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001660 * @param networkType the type of the network over which traffic to the
1661 * specified host is to be routed
1662 * @param hostAddress the IP address of the host to which the route is
1663 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 * @return {@code true} on success, {@code false} on failure
1665 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001666 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001667 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001668 if (disallowedBecauseSystemCaller()) {
1669 return false;
1670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001672 if (mProtectedNetworks.contains(networkType)) {
1673 enforceConnectivityInternalPermission();
1674 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001675
Chad Brubakerc0234532014-02-14 13:24:29 -08001676 InetAddress addr;
1677 try {
1678 addr = InetAddress.getByAddress(hostAddress);
1679 } catch (UnknownHostException e) {
1680 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1681 return false;
1682 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001685 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 return false;
1687 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001688
1689 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1690 if (nai == null) {
1691 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1692 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1693 } else {
1694 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1695 }
1696 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001697 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001698
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001699 DetailedState netState;
1700 synchronized (nai) {
1701 netState = nai.networkInfo.getDetailedState();
1702 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001703
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001704 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001705 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001706 log("requestRouteToHostAddress on down network "
1707 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001708 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001709 }
1710 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001712
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001713 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001714 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001715 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001716 LinkProperties lp;
1717 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001718 synchronized (nai) {
1719 lp = nai.linkProperties;
1720 netId = nai.network.netId;
1721 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001722 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001723 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1724 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001725 } finally {
1726 Binder.restoreCallingIdentity(token);
1727 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001728 }
1729
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001730 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001731 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001732 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001733 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001734 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001735 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001736 if (bestRoute.getGateway().equals(addr)) {
1737 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001738 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001739 } else {
1740 // if we will connect to this through another route, add a direct route
1741 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001742 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001743 }
1744 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001745 if (DBG) log("Adding legacy route " + bestRoute +
1746 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001747 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001748 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001749 } catch (Exception e) {
1750 // never crash - catch them all
1751 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001752 return false;
1753 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001754 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
1756
dalyk7301aa42018-03-05 12:42:22 -05001757 @VisibleForTesting
1758 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1759 @Override
1760 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1761 String hostname, boolean validated) {
1762 try {
1763 mHandler.sendMessage(mHandler.obtainMessage(
1764 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1765 new PrivateDnsValidationUpdate(netId,
1766 InetAddress.parseNumericAddress(ipAddress),
1767 hostname, validated)));
1768 } catch (IllegalArgumentException e) {
1769 loge("Error parsing ip address in validation event");
1770 }
1771 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001772
1773 @Override
1774 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1775 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1776 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1777 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1778 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1779 // event callback for certain nai. e.g. cellular. Register here to pass to
1780 // NetworkMonitor instead.
1781 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1782 // registerNetworkAgent to have NetworkMonitor created with system process as design
1783 // expectation. Also, NetdEventListenerService only allow one callback from each
1784 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1785 // NetworkMonitor registrants.
1786 if (nai != null && nai.satisfies(mDefaultRequest)) {
Chalard Jean971d9c92019-04-08 20:28:44 +09001787 Binder.withCleanCallingIdentity(() ->
1788 nai.networkMonitor().notifyDnsResponse(returnCode));
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001789 }
1790 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001791
1792 @Override
1793 public void onNat64PrefixEvent(int netId, boolean added,
1794 String prefixString, int prefixLength) {
1795 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1796 }
dalyk7301aa42018-03-05 12:42:22 -05001797 };
1798
1799 @VisibleForTesting
1800 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001801 final IIpConnectivityMetrics ipConnectivityMetrics =
1802 IIpConnectivityMetrics.Stub.asInterface(
1803 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1804 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001805 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001806 return;
dalyk7301aa42018-03-05 12:42:22 -05001807 }
1808
1809 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001810 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001811 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1812 mNetdEventCallback);
1813 } catch (Exception e) {
1814 loge("Error registering netd callback: " + e);
1815 }
1816 }
1817
Jeff Sharkey75d31892018-01-18 22:01:59 +09001818 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001819 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001820 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001821 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001822 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001823 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001824 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001825 // caller is NPMS, since we only register with them
1826 if (LOGD_BLOCKED_NETWORKINFO) {
1827 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1828 }
1829 mHandler.sendMessage(mHandler.obtainMessage(
1830 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1831
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001832 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001833 if (restrictBackground) {
1834 log("onRestrictBackgroundChanged(true): disabling tethering");
1835 mTethering.untetherAll();
1836 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001837 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001838 };
1839
junyulai05986c62018-08-07 19:50:45 +08001840 void handleUidRulesChanged(int uid, int newRules) {
1841 // skip update when we've already applied rules
1842 final int oldRules = mUidRules.get(uid, RULE_NONE);
1843 if (oldRules == newRules) return;
1844
1845 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1846
1847 if (newRules == RULE_NONE) {
1848 mUidRules.delete(uid);
1849 } else {
1850 mUidRules.put(uid, newRules);
1851 }
1852 }
1853
1854 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1855 if (mRestrictBackground == restrictBackground) return;
1856
1857 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1858 final boolean curMetered = nai.networkCapabilities.isMetered();
1859 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1860 restrictBackground);
1861 }
1862
1863 mRestrictBackground = restrictBackground;
1864 }
1865
1866 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1867 boolean isBackgroundRestricted) {
1868 synchronized (mVpns) {
1869 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1870 // Because the return value of this function depends on the list of UIDs the
1871 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1872 // list all state depending on the return value of this function has to be recomputed.
1873 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1874 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001875 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001876 return true;
1877 }
1878 }
1879
1880 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1881 isNetworkMetered, isBackgroundRestricted);
1882 }
1883
Robin Lee3b3dd942015-05-12 18:14:58 +01001884 /**
1885 * Require that the caller is either in the same user or has appropriate permission to interact
1886 * across users.
1887 *
1888 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1889 */
1890 private void enforceCrossUserPermission(int userId) {
1891 if (userId == UserHandle.getCallingUserId()) {
1892 // Not a cross-user call.
1893 return;
1894 }
1895 mContext.enforceCallingOrSelfPermission(
1896 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1897 "ConnectivityService");
1898 }
1899
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001900 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001901 for (String permission : permissions) {
1902 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001903 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001904 }
1905 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001906 return false;
1907 }
1908
paulhu3d67f532019-03-22 16:35:06 +08001909 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
1910 for (String permission : permissions) {
1911 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
1912 return true;
1913 }
1914 }
1915 return false;
1916 }
1917
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001918 private void enforceAnyPermissionOf(String... permissions) {
1919 if (!checkAnyPermissionOf(permissions)) {
1920 throw new SecurityException("Requires one of the following permissions: "
1921 + String.join(", ", permissions) + ".");
1922 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001923 }
1924
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001925 private void enforceInternetPermission() {
1926 mContext.enforceCallingOrSelfPermission(
1927 android.Manifest.permission.INTERNET,
1928 "ConnectivityService");
1929 }
1930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001932 mContext.enforceCallingOrSelfPermission(
1933 android.Manifest.permission.ACCESS_NETWORK_STATE,
1934 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
1936
1937 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001938 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
1940
Charles He36738632017-05-15 17:07:18 +01001941 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001942 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001943 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001944 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001945 }
1946
Chalard Jeanb552c462018-02-21 18:43:54 +09001947 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001948 return checkAnyPermissionOf(
1949 android.Manifest.permission.NETWORK_SETTINGS,
1950 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001951 }
1952
1953 private boolean checkSettingsPermission(int pid, int uid) {
1954 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001955 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1956 || PERMISSION_GRANTED == mContext.checkPermission(
1957 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001958 }
1959
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001960 private void enforceTetherAccessPermission() {
1961 mContext.enforceCallingOrSelfPermission(
1962 android.Manifest.permission.ACCESS_NETWORK_STATE,
1963 "ConnectivityService");
1964 }
1965
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001966 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001967 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001968 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001969 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001970 }
1971
Pavel Grafova462bcb2019-01-25 08:50:06 +00001972 private void enforceControlAlwaysOnVpnPermission() {
1973 mContext.enforceCallingOrSelfPermission(
1974 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1975 "ConnectivityService");
1976 }
1977
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001978 private void enforceNetworkStackSettingsOrSetup() {
1979 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001980 android.Manifest.permission.NETWORK_SETTINGS,
1981 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001982 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001983 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001984 }
1985
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001986 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001987 return checkAnyPermissionOf(
1988 android.Manifest.permission.NETWORK_STACK,
1989 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001990 }
1991
paulhu3d67f532019-03-22 16:35:06 +08001992 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
1993 return checkAnyPermissionOf(pid, uid,
1994 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
1995 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
1996 }
1997
Hugo Benichi514da602016-07-19 15:59:27 +09001998 private void enforceConnectivityRestrictedNetworksPermission() {
1999 try {
2000 mContext.enforceCallingOrSelfPermission(
2001 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2002 "ConnectivityService");
2003 return;
2004 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2005 enforceConnectivityInternalPermission();
2006 }
2007
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002008 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09002009 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002010 }
2011
Lorenzo Colitti18660282016-07-04 12:55:44 +09002012 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002013 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002014 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07002015 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002016 }
2017
2018 private void sendInetConditionBroadcast(NetworkInfo info) {
2019 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2020 }
2021
Wink Saville628b0852011-08-04 15:01:58 -07002022 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09002023 synchronized (mVpns) {
2024 if (mLockdownTracker != null) {
2025 info = new NetworkInfo(info);
2026 mLockdownTracker.augmentNetworkInfo(info);
2027 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002028 }
2029
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002030 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002031 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002032 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 if (info.isFailover()) {
2034 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2035 info.setFailover(false);
2036 }
2037 if (info.getReason() != null) {
2038 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2039 }
2040 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002041 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2042 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002044 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002045 return intent;
2046 }
2047
2048 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2049 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2050 }
2051
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002052 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002053 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2054 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2055 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002056 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002057 final long ident = Binder.clearCallingIdentity();
2058 try {
2059 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2060 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2061 } finally {
2062 Binder.restoreCallingIdentity(ident);
2063 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002064 }
2065
Mike Lockwood0f79b542009-08-14 14:18:49 -04002066 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002067 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002068 if (!mSystemReady
2069 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002070 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002071 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002072 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002073 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002074 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002075 }
2076
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002077 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002078 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002079 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002080 final NetworkInfo ni = intent.getParcelableExtra(
2081 ConnectivityManager.EXTRA_NETWORK_INFO);
2082 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2083 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2084 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002085 } else {
2086 BroadcastOptions opts = BroadcastOptions.makeBasic();
2087 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2088 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002089 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002090 final IBatteryStats bs = BatteryStatsService.getService();
2091 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002092 bs.noteConnectivityChanged(intent.getIntExtra(
2093 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002094 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002095 } catch (RemoteException e) {
2096 }
Chad Brubakerac925012018-03-08 10:37:09 -08002097 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002098 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002099 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002100 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002104 }
2105 }
2106
2107 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002108 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002109 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002110 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002111
Hugo Benichi20035e02017-04-26 14:53:28 +09002112 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002113 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002114 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002115 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002116 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002117 }
2118 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002119
Robin Lee244ce8e2016-01-05 18:03:46 +00002120 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2121 // for user to unlock device too.
2122 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002123
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002124 // Create network requests for always-on networks.
2125 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002126
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002128
2129 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
2131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002134 *
2135 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002136 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002137 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2139 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002140
2141 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002143
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 if (networkAgent.networkCapabilities.hasTransport(
2145 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002146 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2147 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002148 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002149 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 } else if (networkAgent.networkCapabilities.hasTransport(
2151 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002152 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2153 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002154 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002156 } else {
2157 // do not track any other networks
2158 timeout = 0;
2159 }
2160
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002162 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002163 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002164 } catch (Exception e) {
2165 // You shall not crash!
2166 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002167 }
2168 }
2169 }
2170
2171 /**
2172 * Remove data activity tracking when network disconnects.
2173 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002174 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2175 final String iface = networkAgent.linkProperties.getInterfaceName();
2176 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002177
Robert Greenwalt7b816022014-04-18 15:25:25 -07002178 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2179 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002180 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002181 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002182 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002183 } catch (Exception e) {
2184 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002185 }
2186 }
2187 }
2188
2189 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002190 * Update data activity tracking when network state is updated.
2191 */
2192 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2193 NetworkAgentInfo oldNetwork) {
2194 if (newNetwork != null) {
2195 setupDataActivityTracking(newNetwork);
2196 }
2197 if (oldNetwork != null) {
2198 removeDataActivityTracking(oldNetwork);
2199 }
2200 }
2201 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002202 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002203 * and set it on it's iface.
2204 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002205 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2206 final String iface = newLp.getInterfaceName();
2207 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002208 if (oldLp == null && mtu == 0) {
2209 // Silently ignore unset MTU value.
2210 return;
2211 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002212 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2213 if (VDBG) log("identical MTU - not setting");
2214 return;
2215 }
paulhud9736de2019-03-08 16:35:20 +08002216 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002217 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002218 return;
2219 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002220
w1997615afd812014-08-05 15:18:11 -07002221 // Cannot set MTU without interface name
2222 if (TextUtils.isEmpty(iface)) {
2223 loge("Setting MTU size with null iface.");
2224 return;
2225 }
2226
Robert Greenwalt7b816022014-04-18 15:25:25 -07002227 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002228 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002229 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002230 } catch (Exception e) {
2231 Slog.e(TAG, "exception in setMtu()" + e);
2232 }
2233 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002234
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002235 @VisibleForTesting
2236 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002237 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2238
2239 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002240 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002241 protected MockableSystemProperties getSystemProperties() {
2242 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002243 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002244
lucaslin041a1af2018-11-28 19:27:52 +08002245 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002246 String[] values = null;
2247 if (tcpBufferSizes != null) {
2248 values = tcpBufferSizes.split(",");
2249 }
2250
2251 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002252 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002253 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2254 values = tcpBufferSizes.split(",");
2255 }
2256
2257 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2258
2259 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002260 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002261
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002262 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2263 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2264 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002265 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002266 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002267 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002268 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002269
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002270 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002271 Settings.Global.TCP_DEFAULT_INIT_RWND,
2272 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002273 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2274 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002275 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002276 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002277 }
2278
Robert Greenwalt562cc542014-05-15 18:07:26 -07002279 @Override
2280 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002281 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002282 NETWORK_RESTORE_DELAY_PROP_NAME);
2283 if(restoreDefaultNetworkDelayStr != null &&
2284 restoreDefaultNetworkDelayStr.length() != 0) {
2285 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002286 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002287 } catch (NumberFormatException e) {
2288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002290 // if the system property isn't set, use the value for the apn type
2291 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2292
2293 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2294 (mNetConfigs[networkType] != null)) {
2295 ret = mNetConfigs[networkType].restoreTime;
2296 }
2297 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 }
2299
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002300 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2301 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2302 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002303 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002304 // Start gathering diagnostic information.
2305 netDiags.add(new NetworkDiagnostics(
2306 nai.network,
2307 new LinkProperties(nai.linkProperties), // Must be a copy.
2308 DIAG_TIME_MS));
2309 }
2310
2311 for (NetworkDiagnostics netDiag : netDiags) {
2312 pw.println();
2313 netDiag.waitForMeasurements();
2314 netDiag.dump(pw);
2315 }
2316 }
2317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002319 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002320 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2321 }
2322
2323 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002324 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002325 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002326 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002327
Erik Kline3f8306b2018-05-01 16:51:44 +09002328 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002329 dumpNetworkDiagnostics(pw);
2330 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002331 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002332 mTethering.dump(fd, pw, args);
2333 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002334 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2335 dumpNetworks(pw);
2336 return;
2337 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2338 dumpNetworkRequests(pw);
2339 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002340 }
Erik Kline379747a2015-06-05 17:47:34 +09002341
Lorenzo Colittie3805462015-06-03 11:18:24 +09002342 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002343 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002344 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002345 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002346 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002347 pw.println();
2348
Paul Jensen85cf78e2015-06-25 13:25:07 -04002349 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002350 pw.print("Active default network: ");
2351 if (defaultNai == null) {
2352 pw.println("none");
2353 } else {
2354 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002356 pw.println();
2357
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002358 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002359 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002360 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002361 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002362 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002363
junyulai05986c62018-08-07 19:50:45 +08002364 pw.print("Restrict background: ");
2365 pw.println(mRestrictBackground);
2366 pw.println();
2367
2368 pw.println("Status for known UIDs:");
2369 pw.increaseIndent();
2370 final int size = mUidRules.size();
2371 for (int i = 0; i < size; i++) {
2372 // Don't crash if the array is modified while dumping in bugreports.
2373 try {
2374 final int uid = mUidRules.keyAt(i);
2375 final int uidRules = mUidRules.get(uid, RULE_NONE);
2376 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2377 } catch (ArrayIndexOutOfBoundsException e) {
2378 pw.println(" ArrayIndexOutOfBoundsException");
2379 } catch (ConcurrentModificationException e) {
2380 pw.println(" ConcurrentModificationException");
2381 }
2382 }
2383 pw.println();
2384 pw.decreaseIndent();
2385
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002386 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002387 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002388 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002389 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002390 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002391
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002392 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002393
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002394 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002395 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002396
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002397 pw.println();
2398 mKeepaliveTracker.dump(pw);
2399
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002400 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002401 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002402
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002403 pw.println();
2404 mMultipathPolicyTracker.dump(pw);
2405
Erik Kline3f8306b2018-05-01 16:51:44 +09002406 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002407 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002408 pw.println("mNetworkRequestInfoLogs (most recent first):");
2409 pw.increaseIndent();
2410 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2411 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002412
2413 pw.println();
2414 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2415 pw.increaseIndent();
2416 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2417 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002418
2419 pw.println();
2420 pw.println("NetTransition WakeLock activity (most recent first):");
2421 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002422 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2423 pw.println("total releases: " + mTotalWakelockReleases);
2424 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2425 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2426 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2427 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2428 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2429 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002430 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002431
2432 pw.println();
2433 pw.println("bandwidth update requests (by uid):");
2434 pw.increaseIndent();
2435 synchronized (mBandwidthRequests) {
2436 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2437 pw.println("[" + mBandwidthRequests.keyAt(i)
2438 + "]: " + mBandwidthRequests.valueAt(i));
2439 }
2440 }
2441 pw.decreaseIndent();
2442
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002443 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002444 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002445
2446 pw.println();
2447 pw.println("NetworkStackClient logs:");
2448 pw.increaseIndent();
2449 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451
Hugo Benichi14683812018-09-03 08:32:56 +09002452 private void dumpNetworks(IndentingPrintWriter pw) {
2453 for (NetworkAgentInfo nai : networksSortedById()) {
2454 pw.println(nai.toString());
2455 pw.increaseIndent();
2456 pw.println(String.format(
2457 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2458 nai.numForegroundNetworkRequests(),
2459 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2460 nai.numBackgroundNetworkRequests(),
2461 nai.numNetworkRequests()));
2462 pw.increaseIndent();
2463 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2464 pw.println(nai.requestAt(i).toString());
2465 }
2466 pw.decreaseIndent();
2467 pw.println("Lingered:");
2468 pw.increaseIndent();
2469 nai.dumpLingerTimers(pw);
2470 pw.decreaseIndent();
2471 pw.decreaseIndent();
2472 }
2473 }
2474
2475 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2476 for (NetworkRequestInfo nri : requestsSortedById()) {
2477 pw.println(nri.toString());
2478 }
2479 }
2480
Hugo Benichia2a917c2018-09-03 08:19:02 +09002481 /**
2482 * Return an array of all current NetworkAgentInfos sorted by network id.
2483 */
2484 private NetworkAgentInfo[] networksSortedById() {
2485 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2486 networks = mNetworkAgentInfos.values().toArray(networks);
2487 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2488 return networks;
2489 }
2490
2491 /**
2492 * Return an array of all current NetworkRequest sorted by request id.
2493 */
2494 private NetworkRequestInfo[] requestsSortedById() {
2495 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2496 requests = mNetworkRequests.values().toArray(requests);
2497 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2498 return requests;
2499 }
2500
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002501 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002502 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002503 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002504 if (officialNai != null && officialNai.equals(nai)) return true;
2505 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002506 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002507 " - " + nai);
2508 }
2509 return false;
2510 }
2511
Robert Greenwalt42acef32009-08-12 16:08:25 -07002512 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002513 private class NetworkStateTrackerHandler extends Handler {
2514 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002515 super(looper);
2516 }
2517
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002518 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002520 default:
2521 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002522 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002523 handleAsyncChannelHalfConnect(msg);
2524 break;
2525 }
2526 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2527 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2528 if (nai != null) nai.asyncChannel.disconnect();
2529 break;
2530 }
2531 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2532 handleAsyncChannelDisconnected(msg);
2533 break;
2534 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002535 }
2536 return true;
2537 }
2538
2539 private void maybeHandleNetworkAgentMessage(Message msg) {
2540 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2541 if (nai == null) {
2542 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002543 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002544 }
2545 return;
2546 }
2547
2548 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002549 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002550 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002551 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002552 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002553 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002554 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002555 break;
2556 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002557 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002558 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002559 break;
2560 }
2561 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002562 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002563 updateNetworkInfo(nai, info);
2564 break;
2565 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002566 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002567 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002568 break;
2569 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002570 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002571 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2572 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002573 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002574 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002575 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002576 // Mark the network as temporarily accepting partial connectivity so that it
2577 // will be validated (and possibly become default) even if it only provides
2578 // partial internet access. Note that if user connects to partial connectivity
2579 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2580 // out of wifi coverage) and if the same wifi is available again, the device
2581 // will auto connect to this wifi even though the wifi has "no internet".
2582 // TODO: Evaluate using a separate setting in IpMemoryStore.
2583 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002584 break;
2585 }
junyulaie4135282019-01-03 18:50:15 +08002586 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2587 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002588 break;
2589 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002590 }
2591 }
2592
2593 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2594 switch (msg.what) {
2595 default:
2596 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002597 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002598 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002599 if (nai == null) break;
2600
lucasline252a742019-03-12 13:08:03 +08002601 final boolean partialConnectivity =
2602 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
lucasline252a742019-03-12 13:08:03 +08002603 || (nai.networkMisc.acceptPartialConnectivity
2604 && nai.partialConnectivity);
2605 // Once a network is determined to have partial connectivity, it cannot
lucaslin975b7d32019-03-21 11:59:22 +08002606 // go back to full connectivity without a disconnect. This is because
2607 // NetworkMonitor can only communicate either PARTIAL_CONNECTIVITY or VALID,
2608 // but not both.
2609 // TODO: Provide multi-testResult to improve the communication between
2610 // ConnectivityService and NetworkMonitor, so that ConnectivityService could
2611 // know the real status of network.
lucaslin43338992019-03-20 18:21:59 +08002612 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002613 (partialConnectivity && !nai.partialConnectivity);
2614
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002615 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002616 final boolean wasValidated = nai.lastValidated;
2617 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002618 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2619 && valid) {
2620 nai.captivePortalLoginNotified = true;
2621 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2622 }
Erik Klinea24d4592018-01-11 21:07:29 +09002623
Erik Klinea24d4592018-01-11 21:07:29 +09002624 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2625
Erik Klinea24d4592018-01-11 21:07:29 +09002626 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002627 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2628 ? " with redirect to " + redirectUrl
2629 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002630 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2631 }
Erik Klinea24d4592018-01-11 21:07:29 +09002632 if (valid != nai.lastValidated) {
2633 if (wasDefault) {
2634 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2635 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002636 }
Erik Klinea24d4592018-01-11 21:07:29 +09002637 final int oldScore = nai.getCurrentScore();
2638 nai.lastValidated = valid;
2639 nai.everValidated |= valid;
2640 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2641 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2642 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002643 if (valid) {
2644 handleFreshlyValidatedNetwork(nai);
2645 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2646 // valid.
2647 mNotifier.clearNotification(nai.network.netId,
2648 NotificationType.NO_INTERNET);
2649 mNotifier.clearNotification(nai.network.netId,
2650 NotificationType.LOST_INTERNET);
2651 }
lucaslin43338992019-03-20 18:21:59 +08002652 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002653 nai.partialConnectivity = partialConnectivity;
2654 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002655 }
2656 updateInetCondition(nai);
2657 // Let the NetworkAgent know the state of its network
2658 Bundle redirectUrlBundle = new Bundle();
2659 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2660 nai.asyncChannel.sendMessage(
2661 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2662 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2663 0, redirectUrlBundle);
2664 if (wasValidated && !nai.lastValidated) {
2665 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002666 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002667 break;
2668 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002669 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002670 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002671 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002672 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002673 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002674 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002675 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002676 nai.lastCaptivePortalDetected = visible;
2677 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002678 if (visible) {
2679 nai.captivePortalLoginNotified = false;
2680 }
Calvin Onbe96da12016-10-11 15:10:46 -07002681 if (nai.lastCaptivePortalDetected &&
2682 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2683 if (DBG) log("Avoiding captive portal network: " + nai.name());
2684 nai.asyncChannel.sendMessage(
2685 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2686 teardownUnneededNetwork(nai);
2687 break;
2688 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002689 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002690 }
2691 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002692 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002693 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002694 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2695 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002696 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002697 if (nai == null) {
2698 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2699 break;
2700 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002701 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002702 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002703 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002704 }
Paul Jensen869868be2014-05-15 10:33:05 -04002705 }
Paul Jensen869868be2014-05-15 10:33:05 -04002706 break;
2707 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002708 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002709 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002710 if (nai == null) break;
2711
Erik Kline736353a2018-03-21 07:18:33 -07002712 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002713 break;
2714 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002715 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002716 return true;
2717 }
2718
Calvin Onbe96da12016-10-11 15:10:46 -07002719 private int getCaptivePortalMode() {
2720 return Settings.Global.getInt(mContext.getContentResolver(),
2721 Settings.Global.CAPTIVE_PORTAL_MODE,
2722 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2723 }
2724
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002725 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2726 switch (msg.what) {
2727 default:
2728 return false;
2729 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2730 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2731 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2732 handleLingerComplete(nai);
2733 }
2734 break;
2735 }
2736 }
2737 return true;
2738 }
2739
Etan Cohenae574a82019-01-08 12:09:18 -08002740 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2741 switch (msg.what) {
2742 default:
2743 return false;
2744 case NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2745 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2746 /* callOnUnavailable */ true);
2747 break;
2748 }
2749 }
2750 return true;
2751 }
2752
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002753 @Override
2754 public void handleMessage(Message msg) {
Etan Cohenae574a82019-01-08 12:09:18 -08002755 if (!maybeHandleAsyncChannelMessage(msg)
2756 && !maybeHandleNetworkMonitorMessage(msg)
2757 && !maybeHandleNetworkAgentInfoMessage(msg)
2758 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002759 maybeHandleNetworkAgentMessage(msg);
2760 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002761 }
2762 }
2763
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002764 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2765 private final NetworkAgentInfo mNai;
2766
2767 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2768 mNai = nai;
2769 }
2770
2771 @Override
2772 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2773 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2774 new Pair<>(mNai, networkMonitor)));
2775 }
2776
2777 @Override
2778 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2779 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2780 testResult, mNai.network.netId, redirectUrl));
2781 }
2782
2783 @Override
2784 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2785 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2786 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2787 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2788 }
2789
2790 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002791 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002792 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002793 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002794
2795 final PendingIntent pendingIntent;
2796 // Only the system server can register notifications with package "android"
2797 final long token = Binder.clearCallingIdentity();
2798 try {
2799 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2800 } finally {
2801 Binder.restoreCallingIdentity(token);
2802 }
2803 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2804 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2805 mNai.network.netId,
2806 pendingIntent));
2807 }
2808
2809 @Override
2810 public void hideProvisioningNotification() {
2811 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2812 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2813 mNai.network.netId));
2814 }
2815 }
2816
Erik Kline736353a2018-03-21 07:18:33 -07002817 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002818 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002819 }
2820
Erik Klinec6d00222018-06-26 18:53:43 +09002821 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2822 if (nai == null) return;
2823 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2824 // in order to restart a validation pass from within netd.
2825 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2826 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2827 updateDnses(nai.linkProperties, null, nai.network.netId);
2828 }
2829 }
2830
Erik Klinea24d4592018-01-11 21:07:29 +09002831 private void handlePrivateDnsSettingsChanged() {
2832 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2833
2834 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002835 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002836 if (networkRequiresValidation(nai)) {
2837 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2838 }
Erik Klinea24d4592018-01-11 21:07:29 +09002839 }
2840 }
2841
Erik Kline736353a2018-03-21 07:18:33 -07002842 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2843 // Private DNS only ever applies to networks that might provide
2844 // Internet access and therefore also require validation.
2845 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002846
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002847 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002848 // schedule DNS resolutions. If a DNS resolution is required the
2849 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002850 try {
2851 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2852 } catch (RemoteException e) {
2853 e.rethrowFromSystemServer();
2854 }
Erik Kline736353a2018-03-21 07:18:33 -07002855
2856 // With Private DNS bypass support, we can proceed to update the
2857 // Private DNS config immediately, even if we're in strict mode
2858 // and have not yet resolved the provider name into a set of IPs.
2859 updatePrivateDns(nai, cfg);
2860 }
2861
2862 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2863 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002864 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002865 }
2866
dalyk7301aa42018-03-05 12:42:22 -05002867 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2868 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2869 if (nai == null) {
2870 return;
2871 }
2872 mDnsManager.updatePrivateDnsValidation(update);
2873 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2874 }
2875
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002876 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2877 int prefixLength) {
2878 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2879 if (nai == null) return;
2880
2881 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2882 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2883
2884 IpPrefix prefix = null;
2885 if (added) {
2886 try {
2887 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2888 prefixLength);
2889 } catch (IllegalArgumentException e) {
2890 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2891 return;
2892 }
2893 }
2894
2895 nai.clatd.setNat64Prefix(prefix);
2896 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2897 }
2898
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002899 private void updateLingerState(NetworkAgentInfo nai, long now) {
2900 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2901 // 2. If the network was lingering and there are now requests, unlinger it.
2902 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2903 // one lingered request, start lingering.
2904 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002905 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002906 if (DBG) log("Unlingering " + nai.name());
2907 nai.unlinger();
2908 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002909 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002910 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002911 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002912 nai.linger();
2913 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2914 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2915 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002916 }
2917
Robert Greenwalt7b816022014-04-18 15:25:25 -07002918 private void handleAsyncChannelHalfConnect(Message msg) {
2919 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002920 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002921 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2922 if (VDBG) log("NetworkFactory connected");
Etan Cohenae574a82019-01-08 12:09:18 -08002923 // Finish setting up the full connection
2924 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2925 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002926 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002927 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002928 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002929 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002930 final int score;
2931 final int serial;
2932 if (nai != null) {
2933 score = nai.getCurrentScore();
2934 serial = nai.factorySerialNumber;
2935 } else {
2936 score = 0;
2937 serial = NetworkFactory.SerialNumber.NONE;
2938 }
2939 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2940 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002941 }
2942 } else {
2943 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002944 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002945 }
2946 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2947 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2948 if (VDBG) log("NetworkAgent connected");
2949 // A network agent has requested a connection. Establish the connection.
2950 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2951 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2952 } else {
2953 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002954 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002955 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002956 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002957 synchronized (mNetworkForNetId) {
2958 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002959 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002960 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002961 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002962 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002963 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002964 }
2965 }
2966 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002967
Chalard Jean392971c2018-05-11 20:19:20 +09002968 // This is a no-op if it's called with a message designating a network that has
2969 // already been destroyed, because its reference will not be found in the relevant
2970 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002971 private void handleAsyncChannelDisconnected(Message msg) {
2972 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2973 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002974 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002975 } else {
2976 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2977 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002978 }
2979 }
2980
Chalard Jean392971c2018-05-11 20:19:20 +09002981 // Destroys a network, remove references to it from the internal state managed by
2982 // ConnectivityService, free its interfaces and clean up.
2983 // Must be called on the Handler thread.
2984 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2985 if (DBG) {
2986 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2987 }
lucaslinf80b83b2019-02-12 15:30:13 +08002988 // Clear all notifications of this network.
2989 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002990 // A network agent has disconnected.
2991 // TODO - if we move the logic to the network agent (have them disconnect
2992 // because they lost all their requests or because their score isn't good)
2993 // then they would disconnect organically, report their new state and then
2994 // disconnect the channel.
2995 if (nai.networkInfo.isConnected()) {
2996 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2997 null, null);
2998 }
2999 final boolean wasDefault = isDefaultNetwork(nai);
3000 if (wasDefault) {
3001 mDefaultInetConditionPublished = 0;
3002 // Log default network disconnection before required book-keeping.
3003 // Let rematchAllNetworksAndRequests() below record a new default network event
3004 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
3005 // whose timestamps tell how long it takes to recover a default network.
3006 long now = SystemClock.elapsedRealtime();
3007 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
3008 }
3009 notifyIfacesChangedForNetworkStats();
3010 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3011 // by other networks that are already connected. Perhaps that can be done by
3012 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3013 // of rematchAllNetworksAndRequests
3014 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulaie4135282019-01-03 18:50:15 +08003015 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09003016 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3017 // Disable wakeup packet monitoring for each interface.
3018 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3019 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003020 try {
3021 nai.networkMonitor().notifyNetworkDisconnected();
3022 } catch (RemoteException e) {
3023 e.rethrowFromSystemServer();
3024 }
Chalard Jean392971c2018-05-11 20:19:20 +09003025 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09003026 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09003027 synchronized (mNetworkForNetId) {
3028 // Remove the NetworkAgent, but don't mark the netId as
3029 // available until we've told netd to delete it below.
3030 mNetworkForNetId.remove(nai.network.netId);
3031 }
3032 // Remove all previously satisfied requests.
3033 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3034 NetworkRequest request = nai.requestAt(i);
3035 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
3036 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3037 clearNetworkForRequest(request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09003038 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003039 }
3040 }
3041 nai.clearLingerState();
3042 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003043 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003044 notifyLockdownVpn(nai);
3045 ensureNetworkTransitionWakelock(nai.name());
3046 }
3047 mLegacyTypeTracker.remove(nai, wasDefault);
3048 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3049 updateAllVpnsCapabilities();
3050 }
3051 rematchAllNetworksAndRequests(null, 0);
3052 mLingerMonitor.noteDisconnect(nai);
3053 if (nai.created) {
3054 // Tell netd to clean up the configuration for this network
3055 // (routing rules, DNS, etc).
3056 // This may be slow as it requires a lot of netd shelling out to ip and
3057 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3058 // after we've rematched networks with requests which should make a potential
3059 // fallback network the default or requested a new network from the
3060 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3061 // long time.
3062 try {
Luke Huang65914772019-03-16 00:31:46 +08003063 mNetd.networkDestroy(nai.network.netId);
3064 } catch (RemoteException | ServiceSpecificException e) {
3065 loge("Exception destroying network: " + e);
Chalard Jean392971c2018-05-11 20:19:20 +09003066 }
3067 mDnsManager.removeNetwork(nai.network);
3068 }
3069 synchronized (mNetworkForNetId) {
3070 mNetIdInUse.delete(nai.network.netId);
3071 }
3072 }
3073
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003074 // If this method proves to be too slow then we can maintain a separate
3075 // pendingIntent => NetworkRequestInfo map.
3076 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3077 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3078 Intent intent = pendingIntent.getIntent();
3079 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3080 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3081 if (existingPendingIntent != null &&
3082 existingPendingIntent.getIntent().filterEquals(intent)) {
3083 return entry.getValue();
3084 }
3085 }
3086 return null;
3087 }
3088
3089 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3090 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3091
3092 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3093 if (existingRequest != null) { // remove the existing request.
3094 if (DBG) log("Replacing " + existingRequest.request + " with "
3095 + nri.request + " because their intents matched.");
Etan Cohenae574a82019-01-08 12:09:18 -08003096 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3097 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003098 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003099 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003100 }
3101
Erik Klineda4bfa82015-04-30 12:58:40 +09003102 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003103 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003104 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003105 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003106 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003107 if (nri.request.networkCapabilities.hasSignalStrength() &&
3108 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3109 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003110 }
3111 }
3112 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003113 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003114 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean08577fc2018-05-02 21:14:54 +09003115 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003116 }
3117 }
3118
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003119 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3120 int callingUid) {
3121 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3122 if (nri != null) {
Etan Cohenae574a82019-01-08 12:09:18 -08003123 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003124 }
3125 }
3126
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003127 // Determines whether the network is the best (or could become the best, if it validated), for
3128 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3129 // on the value of reason:
3130 //
3131 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3132 // then it should be torn down.
3133 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3134 // then it should be lingered.
3135 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3136 final int numRequests;
3137 switch (reason) {
3138 case TEARDOWN:
3139 numRequests = nai.numRequestNetworkRequests();
3140 break;
3141 case LINGER:
3142 numRequests = nai.numForegroundNetworkRequests();
3143 break;
3144 default:
3145 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3146 return true;
3147 }
3148
3149 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003150 return false;
3151 }
Paul Jensene0988542015-06-25 15:30:08 -04003152 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003153 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3154 // Background requests don't affect lingering.
3155 continue;
3156 }
3157
Paul Jensene0988542015-06-25 15:30:08 -04003158 // If this Network is already the highest scoring Network for a request, or if
3159 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003160 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003161 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003162 // Note that this catches two important cases:
3163 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3164 // is currently satisfying the request. This is desirable when
3165 // cellular ends up validating but WiFi does not.
3166 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003167 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003168 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003169 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003170 nai.getCurrentScoreAsValidated())) {
3171 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003172 }
3173 }
Paul Jensene0988542015-06-25 15:30:08 -04003174 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003175 }
3176
Erik Klineacdd6392016-07-07 16:50:58 +09003177 private NetworkRequestInfo getNriForAppRequest(
3178 NetworkRequest request, int callingUid, String requestedOperation) {
3179 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3180
Robert Greenwalt9258c642014-03-26 16:47:06 -07003181 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003182 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003183 log(String.format("UID %d attempted to %s for unowned request %s",
3184 callingUid, requestedOperation, nri));
3185 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003186 }
Erik Klineacdd6392016-07-07 16:50:58 +09003187 }
3188
3189 return nri;
3190 }
3191
Erik Kline57faba92015-11-25 12:49:38 +09003192 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003193 if (mNetworkRequests.get(nri.request) == null) {
3194 return;
Erik Kline57faba92015-11-25 12:49:38 +09003195 }
Hugo Benichicd952782017-09-20 11:20:14 +09003196 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003197 return;
3198 }
3199 if (VDBG || (DBG && nri.request.isRequest())) {
3200 log("releasing " + nri.request + " (timeout)");
3201 }
3202 handleRemoveNetworkRequest(nri);
3203 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003204 }
3205
Etan Cohenae574a82019-01-08 12:09:18 -08003206 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3207 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003208 final NetworkRequestInfo nri =
3209 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3210 if (nri == null) {
3211 return;
Erik Kline57faba92015-11-25 12:49:38 +09003212 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003213 if (VDBG || (DBG && nri.request.isRequest())) {
3214 log("releasing " + nri.request + " (release request)");
3215 }
3216 handleRemoveNetworkRequest(nri);
Etan Cohenae574a82019-01-08 12:09:18 -08003217 if (callOnUnavailable) {
3218 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3219 }
Erik Kline57faba92015-11-25 12:49:38 +09003220 }
Erik Klineacdd6392016-07-07 16:50:58 +09003221
Hugo Benichidba33db2017-03-23 22:40:44 +09003222 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003223 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003224 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003225
Erik Klineacdd6392016-07-07 16:50:58 +09003226 synchronized (mUidToNetworkRequestCount) {
3227 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3228 if (requests < 1) {
3229 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3230 nri.mUid);
3231 } else if (requests == 1) {
3232 mUidToNetworkRequestCount.removeAt(
3233 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3234 } else {
3235 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3236 }
3237 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003238
Erik Klineacdd6392016-07-07 16:50:58 +09003239 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3240 if (nri.request.isRequest()) {
3241 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003242 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003243 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003244 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003245 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003246 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003247 log(" Removing from current network " + nai.name() +
3248 ", leaving " + nai.numNetworkRequests() + " requests.");
3249 }
3250 // If there are still lingered requests on this network, don't tear it down,
3251 // but resume lingering instead.
3252 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003253 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003254 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3255 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003256 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003257 wasKept = true;
3258 }
Hugo Benichicd952782017-09-20 11:20:14 +09003259 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003260 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3261 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003262 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003263 }
Erik Klineacdd6392016-07-07 16:50:58 +09003264 }
3265
Erik Klineacdd6392016-07-07 16:50:58 +09003266 // Maintain the illusion. When this request arrived, we might have pretended
3267 // that a network connected to serve it, even though the network was already
3268 // connected. Now that this request has gone away, we might have to pretend
3269 // that the network disconnected. LegacyTypeTracker will generate that
3270 // phantom disconnect for this type.
3271 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3272 boolean doRemove = true;
3273 if (wasKept) {
3274 // check if any of the remaining requests for this network are for the
3275 // same legacy type - if so, don't remove the nai
3276 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3277 NetworkRequest otherRequest = nai.requestAt(i);
3278 if (otherRequest.legacyType == nri.request.legacyType &&
3279 otherRequest.isRequest()) {
3280 if (DBG) log(" still have other legacy request - leaving");
3281 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003282 }
3283 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003284 }
3285
Erik Klineacdd6392016-07-07 16:50:58 +09003286 if (doRemove) {
3287 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003288 }
3289 }
Erik Klineacdd6392016-07-07 16:50:58 +09003290
3291 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3292 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3293 nri.request);
3294 }
3295 } else {
3296 // listens don't have a singular affectedNetwork. Check all networks to see
3297 // if this listen request applies and remove it.
3298 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3299 nai.removeRequest(nri.request.requestId);
3300 if (nri.request.networkCapabilities.hasSignalStrength() &&
3301 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3302 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3303 }
3304 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003305 }
3306 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003307
Lorenzo Colitti18660282016-07-04 12:55:44 +09003308 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003309 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003310 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003311 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003312 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003313 }
3314
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003315 @Override
lucasline252a742019-03-12 13:08:03 +08003316 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3317 enforceNetworkStackSettingsOrSetup();
3318 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3319 encodeBool(accept), encodeBool(always), network));
3320 }
3321
3322 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003323 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003324 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003325 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3326 }
3327
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003328 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3329 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3330 " accept=" + accept + " always=" + always);
3331
3332 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3333 if (nai == null) {
3334 // Nothing to do.
3335 return;
3336 }
3337
3338 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003339 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003340 return;
3341 }
3342
3343 if (!nai.networkMisc.explicitlySelected) {
3344 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3345 }
3346
3347 if (accept != nai.networkMisc.acceptUnvalidated) {
3348 int oldScore = nai.getCurrentScore();
3349 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003350 // If network becomes partial connectivity and user already accepted to use this
3351 // network, we should respect the user's option and don't need to popup the
3352 // PARTIAL_CONNECTIVITY notification to user again.
3353 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003354 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003355 sendUpdatedScoreToFactories(nai);
3356 }
3357
3358 if (always) {
3359 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003360 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003361 }
3362
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003363 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003364 // Tell the NetworkAgent to not automatically reconnect to the network.
3365 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003366 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003367 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003368 }
3369
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003370 }
3371
lucasline252a742019-03-12 13:08:03 +08003372 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3373 boolean always) {
3374 if (DBG) {
3375 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3376 + " always=" + always);
3377 }
3378
3379 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3380 if (nai == null) {
3381 // Nothing to do.
3382 return;
3383 }
3384
3385 if (nai.lastValidated) {
3386 // The network validated while the dialog box was up. Take no action.
3387 return;
3388 }
3389
3390 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3391 nai.networkMisc.acceptPartialConnectivity = accept;
3392 }
3393
3394 // TODO: Use the current design or save the user choice into IpMemoryStore.
3395 if (always) {
3396 nai.asyncChannel.sendMessage(
3397 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3398 }
3399
3400 if (!accept) {
3401 // Tell the NetworkAgent to not automatically reconnect to the network.
3402 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3403 // Tear down the network.
3404 teardownUnneededNetwork(nai);
3405 } else {
lucaslin43338992019-03-20 18:21:59 +08003406 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3407 // result in a partial connectivity result which will be processed by
3408 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003409 try {
lucaslin43338992019-03-20 18:21:59 +08003410 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003411 } catch (RemoteException e) {
3412 e.rethrowFromSystemServer();
3413 }
3414 }
3415 }
3416
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003417 private void handleSetAvoidUnvalidated(Network network) {
3418 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3419 if (nai == null || nai.lastValidated) {
3420 // Nothing to do. The network either disconnected or revalidated.
3421 return;
3422 }
3423 if (!nai.avoidUnvalidated) {
3424 int oldScore = nai.getCurrentScore();
3425 nai.avoidUnvalidated = true;
3426 rematchAllNetworksAndRequests(nai, oldScore);
3427 sendUpdatedScoreToFactories(nai);
3428 }
3429 }
3430
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003431 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003432 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003433 mHandler.sendMessageDelayed(
3434 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3435 PROMPT_UNVALIDATED_DELAY_MS);
3436 }
3437
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003438 @Override
3439 public void startCaptivePortalApp(Network network) {
3440 enforceConnectivityInternalPermission();
3441 mHandler.post(() -> {
3442 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3443 if (nai == null) return;
3444 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003445 try {
3446 nai.networkMonitor().launchCaptivePortalApp();
3447 } catch (RemoteException e) {
3448 e.rethrowFromSystemServer();
3449 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003450 });
3451 }
3452
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003453 /**
3454 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3455 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003456 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003457 * @param appExtras Bundle to use as intent extras for the captive portal application.
3458 * Must be treated as opaque to avoid preventing the captive portal app to
3459 * update its arguments.
3460 */
3461 @Override
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003462 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003463 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3464
3465 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3466 appIntent.putExtras(appExtras);
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003467 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3468 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003469 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3470
3471 Binder.withCleanCallingIdentity(() ->
3472 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3473 }
3474
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003475 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3476 private final Network mNetwork;
3477
3478 private CaptivePortalImpl(Network network) {
3479 mNetwork = network;
3480 }
3481
3482 @Override
3483 public void appResponse(final int response) throws RemoteException {
3484 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3485 enforceSettingsPermission();
3486 }
3487
3488 // getNetworkAgentInfoForNetwork is thread-safe
3489 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3490 if (nai == null) return;
3491
3492 // nai.networkMonitor() is thread-safe
3493 final INetworkMonitor nm = nai.networkMonitor();
3494 if (nm == null) return;
3495
3496 final long token = Binder.clearCallingIdentity();
3497 try {
3498 nm.notifyCaptivePortalAppFinished(response);
3499 } finally {
3500 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3501 Binder.restoreCallingIdentity(token);
3502 }
3503 }
3504
3505 @Override
3506 public void logEvent(int eventId, String packageName) {
3507 enforceSettingsPermission();
3508
3509 new MetricsLogger().action(eventId, packageName);
3510 }
3511 }
3512
Hugo Benichic8e9e122016-09-14 23:23:08 +00003513 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003514 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003515 }
3516
Remi NGUYEN VAN24ec3ff2019-03-22 17:16:52 +09003517 /**
3518 * Return whether the device should maintain continuous, working connectivity by switching away
3519 * from WiFi networks having no connectivity.
3520 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3521 */
3522 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003523 if (!checkNetworkStackPermission()) {
3524 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3525 }
3526 return avoidBadWifi();
3527 }
3528
3529
Erik Kline065ab6e2016-10-02 18:02:14 +09003530 private void rematchForAvoidBadWifiUpdate() {
3531 rematchAllNetworksAndRequests(null, 0);
3532 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3533 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3534 sendUpdatedScoreToFactories(nai);
3535 }
3536 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003537 }
3538
Erik Kline065ab6e2016-10-02 18:02:14 +09003539 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003540 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003541 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003542 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003543 if (!configRestrict) {
3544 pw.println("Bad Wi-Fi avoidance: unrestricted");
3545 return;
3546 }
3547
3548 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3549 pw.increaseIndent();
3550 pw.println("Config restrict: " + configRestrict);
3551
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003552 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003553 String description;
3554 // Can't use a switch statement because strings are legal case labels, but null is not.
3555 if ("0".equals(value)) {
3556 description = "get stuck";
3557 } else if (value == null) {
3558 description = "prompt";
3559 } else if ("1".equals(value)) {
3560 description = "avoid";
3561 } else {
3562 description = value + " (?)";
3563 }
3564 pw.println("User setting: " + description);
3565 pw.println("Network overrides:");
3566 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003567 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003568 if (nai.avoidUnvalidated) {
3569 pw.println(nai.name());
3570 }
3571 }
3572 pw.decreaseIndent();
3573 pw.decreaseIndent();
3574 }
3575
lucaslind2e045e02019-01-24 15:55:30 +08003576 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003577 final String action;
3578 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003579 case LOGGED_IN:
3580 action = Settings.ACTION_WIFI_SETTINGS;
3581 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3582 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3583 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3584 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003585 case NO_INTERNET:
3586 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3587 break;
3588 case LOST_INTERNET:
3589 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3590 break;
lucasline252a742019-03-12 13:08:03 +08003591 case PARTIAL_CONNECTIVITY:
3592 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3593 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003594 default:
3595 Slog.wtf(TAG, "Unknown notification type " + type);
3596 return;
3597 }
3598
3599 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003600 if (type != NotificationType.LOGGED_IN) {
3601 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3602 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3603 intent.setClassName("com.android.settings",
3604 "com.android.settings.wifi.WifiNoInternetDialog");
3605 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003606
3607 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3608 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3609 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3610 }
3611
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003612 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003613 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003614 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3615
lucasline252a742019-03-12 13:08:03 +08003616 // Only prompt if the network is unvalidated or network has partial internet connectivity
3617 // and was explicitly selected by the user, and if we haven't already been told to switch
3618 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3619 // because we're already prompting the user to sign in.
3620 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3621 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003622 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3623 // we should reevaluate how to handle acceptPartialConnectivity when network just
3624 // connected.
lucasline252a742019-03-12 13:08:03 +08003625 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003626 return;
3627 }
lucasline252a742019-03-12 13:08:03 +08003628 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3629 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3630 // popup the notification immediately when the network is partial connectivity.
3631 if (nai.partialConnectivity) {
lucaslin975b7d32019-03-21 11:59:22 +08003632 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucasline252a742019-03-12 13:08:03 +08003633 } else {
3634 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3635 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003636 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003637
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003638 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3639 NetworkCapabilities nc = nai.networkCapabilities;
3640 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003641
lucasline252a742019-03-12 13:08:03 +08003642 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3643 return;
3644 }
3645
3646 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003647 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003648 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003649 }
3650
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003651 @Override
3652 public int getMultipathPreference(Network network) {
3653 enforceAccessPermission();
3654
3655 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003656 if (nai != null && nai.networkCapabilities
3657 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003658 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3659 }
3660
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003661 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3662 if (networkPreference != null) {
3663 return networkPreference;
3664 }
3665
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003666 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3667 }
3668
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003669 @Override
3670 public NetworkRequest getDefaultRequest() {
3671 return mDefaultRequest;
3672 }
3673
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003674 private class InternalHandler extends Handler {
3675 public InternalHandler(Looper looper) {
3676 super(looper);
3677 }
3678
3679 @Override
3680 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003681 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003682 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003683 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003684 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003685 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003686 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003687 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003688 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003689 break;
3690 }
Jason Monkdecd2952013-10-10 14:02:51 -04003691 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003692 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003693 break;
3694 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003695 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003696 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3697 break;
3698 }
3699 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3700 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003701 break;
3702 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003703 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003704 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3705 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3706 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003707 break;
3708 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003709 case EVENT_REGISTER_NETWORK_REQUEST:
3710 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003711 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003712 break;
3713 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003714 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3715 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003716 handleRegisterNetworkRequestWithIntent(msg);
3717 break;
3718 }
Erik Kline57faba92015-11-25 12:49:38 +09003719 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3720 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3721 handleTimedOutNetworkRequest(nri);
3722 break;
3723 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003724 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3725 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3726 break;
3727 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003728 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenae574a82019-01-08 12:09:18 -08003729 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3730 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003731 break;
3732 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003733 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003734 Network network = (Network) msg.obj;
3735 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003736 break;
3737 }
lucasline252a742019-03-12 13:08:03 +08003738 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3739 Network network = (Network) msg.obj;
3740 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3741 toBool(msg.arg2));
3742 break;
3743 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003744 case EVENT_SET_AVOID_UNVALIDATED: {
3745 handleSetAvoidUnvalidated((Network) msg.obj);
3746 break;
3747 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003748 case EVENT_PROMPT_UNVALIDATED: {
3749 handlePromptUnvalidated((Network) msg.obj);
3750 break;
3751 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003752 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3753 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003754 break;
3755 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003756 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003757 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003758 mKeepaliveTracker.handleStartKeepalive(msg);
3759 break;
3760 }
3761 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003762 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003763 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3764 int slot = msg.arg1;
3765 int reason = msg.arg2;
3766 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3767 break;
3768 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003769 case EVENT_SYSTEM_READY: {
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003770 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003771 break;
3772 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003773 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003774 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003775 break;
3776 }
Erik Klinea24d4592018-01-11 21:07:29 +09003777 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3778 handlePrivateDnsSettingsChanged();
3779 break;
dalyk7301aa42018-03-05 12:42:22 -05003780 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3781 handlePrivateDnsValidationUpdate(
3782 (PrivateDnsValidationUpdate) msg.obj);
3783 break;
junyulai05986c62018-08-07 19:50:45 +08003784 case EVENT_UID_RULES_CHANGED:
3785 handleUidRulesChanged(msg.arg1, msg.arg2);
3786 break;
3787 case EVENT_DATA_SAVER_CHANGED:
3788 handleRestrictBackgroundChanged(toBool(msg.arg1));
3789 break;
lucaslind2e045e02019-01-24 15:55:30 +08003790 case EVENT_TIMEOUT_NOTIFICATION:
3791 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3792 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 }
3794 }
3795 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003796
3797 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003798 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003799 public int tether(String iface, String callerPkg) {
3800 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003801 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003802 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003803 } else {
3804 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3805 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003806 }
3807
3808 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003809 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003810 public int untether(String iface, String callerPkg) {
3811 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003812
3813 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003814 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003815 } else {
3816 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3817 }
3818 }
3819
3820 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003821 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003822 public int getLastTetherError(String iface) {
3823 enforceTetherAccessPermission();
3824
3825 if (isTetheringSupported()) {
3826 return mTethering.getLastTetherError(iface);
3827 } else {
3828 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3829 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003830 }
3831
3832 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003833 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003834 public String[] getTetherableUsbRegexs() {
3835 enforceTetherAccessPermission();
3836 if (isTetheringSupported()) {
3837 return mTethering.getTetherableUsbRegexs();
3838 } else {
3839 return new String[0];
3840 }
3841 }
3842
Lorenzo Colitti18660282016-07-04 12:55:44 +09003843 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003844 public String[] getTetherableWifiRegexs() {
3845 enforceTetherAccessPermission();
3846 if (isTetheringSupported()) {
3847 return mTethering.getTetherableWifiRegexs();
3848 } else {
3849 return new String[0];
3850 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003851 }
3852
Lorenzo Colitti18660282016-07-04 12:55:44 +09003853 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003854 public String[] getTetherableBluetoothRegexs() {
3855 enforceTetherAccessPermission();
3856 if (isTetheringSupported()) {
3857 return mTethering.getTetherableBluetoothRegexs();
3858 } else {
3859 return new String[0];
3860 }
3861 }
3862
Lorenzo Colitti18660282016-07-04 12:55:44 +09003863 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003864 public int setUsbTethering(boolean enable, String callerPkg) {
3865 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003866 if (isTetheringSupported()) {
3867 return mTethering.setUsbTethering(enable);
3868 } else {
3869 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3870 }
3871 }
3872
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003873 // TODO - move iface listing, queries, etc to new module
3874 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003875 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003876 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003877 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003878 return mTethering.getTetherableIfaces();
3879 }
3880
Lorenzo Colitti18660282016-07-04 12:55:44 +09003881 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003882 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003883 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003884 return mTethering.getTetheredIfaces();
3885 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003886
Lorenzo Colitti18660282016-07-04 12:55:44 +09003887 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003888 public String[] getTetheringErroredIfaces() {
3889 enforceTetherAccessPermission();
3890 return mTethering.getErroredIfaces();
3891 }
3892
Lorenzo Colitti18660282016-07-04 12:55:44 +09003893 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003894 public String[] getTetheredDhcpRanges() {
3895 enforceConnectivityInternalPermission();
3896 return mTethering.getTetheredDhcpRanges();
3897 }
3898
Udam Saini0e94c362017-06-07 12:06:28 -07003899 @Override
3900 public boolean isTetheringSupported(String callerPkg) {
3901 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3902 return isTetheringSupported();
3903 }
3904
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003905 // if ro.tether.denied = true we default to no tethering
3906 // gservices could set the secure setting to 1 though to enable it on a build where it
3907 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003908 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003909 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3910 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3911 Settings.Global.TETHER_SUPPORTED, defaultVal));
3912 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003913 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003914
3915 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3916 boolean adminUser = false;
3917 final long token = Binder.clearCallingIdentity();
3918 try {
3919 adminUser = mUserManager.isAdminUser();
3920 } finally {
3921 Binder.restoreCallingIdentity(token);
3922 }
3923
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003924 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003925 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003926
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003927 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003928 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3929 String callerPkg) {
3930 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003931 if (!isTetheringSupported()) {
3932 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3933 return;
3934 }
3935 mTethering.startTethering(type, receiver, showProvisioningUi);
3936 }
3937
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003938 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003939 public void stopTethering(int type, String callerPkg) {
3940 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003941 mTethering.stopTethering(type);
3942 }
3943
markchienf2731272019-01-16 17:44:13 +08003944 /**
3945 * Get the latest value of the tethering entitlement check.
3946 *
3947 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3948 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3949 * if it's really needed.
3950 */
3951 @Override
markchien9554abf2019-03-06 16:25:00 +08003952 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003953 boolean showEntitlementUi, String callerPkg) {
3954 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003955 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003956 }
3957
markchien6ea34542019-02-27 14:56:11 +08003958 /** Register tethering event callback. */
3959 @Override
3960 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3961 String callerPkg) {
3962 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3963 mTethering.registerTetheringEventCallback(callback);
3964 }
3965
3966 /** Unregister tethering event callback. */
3967 @Override
3968 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3969 String callerPkg) {
3970 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3971 mTethering.unregisterTetheringEventCallback(callback);
3972 }
3973
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003974 // Called when we lose the default network and have no replacement yet.
3975 // This will automatically be cleared after X seconds or a new default network
3976 // becomes CONNECTED, whichever happens first. The timer is started by the
3977 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003978 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003979 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003980 if (mNetTransitionWakeLock.isHeld()) {
3981 return;
3982 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003983 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003984 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3985 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003986 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003987 mWakelockLogs.log("ACQUIRE for " + forWhom);
3988 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3989 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003990 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003991
Hugo Benichi4c31b342017-03-30 23:18:10 +09003992 // Called when we gain a new default network to release the network transition wakelock in a
3993 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3994 // message is cancelled.
3995 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003996 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003997 if (!mNetTransitionWakeLock.isHeld()) {
3998 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003999 }
4000 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004001 // Cancel self timeout on wakelock hold.
4002 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4003 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4004 mHandler.sendMessageDelayed(msg, 1000);
4005 }
4006
4007 // Called when either message of ensureNetworkTransitionWakelock or
4008 // scheduleReleaseNetworkTransitionWakelock is processed.
4009 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4010 String event = eventName(eventId);
4011 synchronized (this) {
4012 if (!mNetTransitionWakeLock.isHeld()) {
4013 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4014 Slog.w(TAG, "expected Net Transition WakeLock to be held");
4015 return;
4016 }
4017 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09004018 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4019 mTotalWakelockDurationMs += lockDuration;
4020 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4021 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004022 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004023 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004024 }
4025
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004026 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09004027 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004028 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004029 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004030 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004031 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004032 }
4033
Lorenzo Colitti18660282016-07-04 12:55:44 +09004034 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004035 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004036 enforceAccessPermission();
4037 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004038 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004039 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004040 mHandler.sendMessage(
4041 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4042 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004043
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004044 private void handleReportNetworkConnectivity(
4045 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004046 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004047 if (network == null) {
4048 nai = getDefaultNetwork();
4049 } else {
4050 nai = getNetworkAgentInfoForNetwork(network);
4051 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004052 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4053 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4054 return;
4055 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004056 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004057 if (hasConnectivity == nai.lastValidated) {
4058 return;
4059 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004060 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004061 int netid = nai.network.netId;
4062 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004063 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004064 // Validating a network that has not yet connected could result in a call to
4065 // rematchNetworkAndRequests() which is not meant to work on such networks.
4066 if (!nai.everConnected) {
4067 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004068 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004069 LinkProperties lp = getLinkProperties(nai);
4070 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4071 return;
4072 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004073 try {
4074 nai.networkMonitor().forceReevaluation(uid);
4075 } catch (RemoteException e) {
4076 e.rethrowFromSystemServer();
4077 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078 }
4079
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004080 /**
4081 * Returns information about the proxy a certain network is using. If given a null network, it
4082 * it will return the proxy for the bound network for the caller app or the default proxy if
4083 * none.
4084 *
4085 * @param network the network we want to get the proxy information for.
4086 * @return Proxy information if a network has a proxy configured, or otherwise null.
4087 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004088 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004089 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004090 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004091 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004092 if (network == null) {
4093 // Get the network associated with the calling UID.
4094 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4095 true);
4096 if (activeNetwork == null) {
4097 return null;
4098 }
4099 return getLinkPropertiesProxyInfo(activeNetwork);
4100 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4101 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4102 // caller may not have.
4103 return getLinkPropertiesProxyInfo(network);
4104 }
4105 // No proxy info available if the calling UID does not have network access.
4106 return null;
4107 }
4108
4109 @VisibleForTesting
4110 protected boolean queryUserAccess(int uid, int netId) {
4111 return NetworkUtils.queryUserAccess(uid, netId);
4112 }
4113
4114 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004115 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4116 if (nai == null) return null;
4117 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004118 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4119 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004120 }
4121 }
4122
Chalard Jean3c443fc2018-06-07 18:37:59 +09004123 @Override
4124 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004125 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004126 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004127 }
4128
Chalard Jean5afbc832018-06-07 18:02:37 +09004129 @Override
4130 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004131 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004132 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004133 }
4134
Jason Monk207900c2014-04-25 15:00:09 -04004135 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004136 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004137 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004138 proxy = null;
4139 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004140 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004141 }
4142
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004143 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4144 // when any network changes proxy.
4145 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4146 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004147 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004148 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4149 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4150
Chalard Jean4949dd72018-06-07 17:41:29 +09004151 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004152 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004153 }
4154 }
4155
Robert Greenwalt434203a2010-10-11 16:00:27 -07004156 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004157 final private HashMap<Uri, Integer> mUriEventMap;
4158 final private Context mContext;
4159 final private Handler mHandler;
4160
4161 SettingsObserver(Context context, Handler handler) {
4162 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004163 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004164 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004165 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004166 }
4167
Erik Klineda4bfa82015-04-30 12:58:40 +09004168 void observe(Uri uri, int what) {
4169 mUriEventMap.put(uri, what);
4170 final ContentResolver resolver = mContext.getContentResolver();
4171 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004172 }
4173
4174 @Override
4175 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004176 Slog.wtf(TAG, "Should never be reached.");
4177 }
4178
4179 @Override
4180 public void onChange(boolean selfChange, Uri uri) {
4181 final Integer what = mUriEventMap.get(uri);
4182 if (what != null) {
4183 mHandler.obtainMessage(what.intValue()).sendToTarget();
4184 } else {
4185 loge("No matching event to send for URI=" + uri);
4186 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004187 }
4188 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004189
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004190 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004191 Slog.d(TAG, s);
4192 }
4193
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004194 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004195 Slog.e(TAG, s);
4196 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004197
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004198 private static void loge(String s, Throwable t) {
4199 Slog.e(TAG, s, t);
4200 }
4201
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004202 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004203 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004204 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4205 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4206 *
4207 * @param oldPackage Package name of the application which currently controls VPN, which will
4208 * be replaced. If there is no such application, this should should either be
4209 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4210 * @param newPackage Package name of the application which should gain control of VPN, or
4211 * {@code null} to disable.
4212 * @param userId User for whom to prepare the new VPN.
4213 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004214 * @hide
4215 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004216 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004217 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4218 int userId) {
4219 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004220
Hugo Benichi20035e02017-04-26 14:53:28 +09004221 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004222 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004223 Vpn vpn = mVpns.get(userId);
4224 if (vpn != null) {
4225 return vpn.prepare(oldPackage, newPackage);
4226 } else {
4227 return false;
4228 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004229 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004230 }
4231
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004232 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004233 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4234 * This method is used by system-privileged apps.
4235 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4236 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4237 *
4238 * @param packageName The package for which authorization state should change.
4239 * @param userId User for whom {@code packageName} is installed.
4240 * @param authorized {@code true} if this app should be able to start a VPN connection without
4241 * explicit user approval, {@code false} if not.
4242 *
Jeff Davidson05542602014-08-11 14:07:27 -07004243 * @hide
4244 */
4245 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004246 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4247 enforceCrossUserPermission(userId);
4248
Hugo Benichi20035e02017-04-26 14:53:28 +09004249 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004250 Vpn vpn = mVpns.get(userId);
4251 if (vpn != null) {
4252 vpn.setPackageAuthorization(packageName, authorized);
4253 }
Jeff Davidson05542602014-08-11 14:07:27 -07004254 }
4255 }
4256
4257 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004258 * Configure a TUN interface and return its file descriptor. Parameters
4259 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004260 * and not available in ConnectivityManager. Permissions are checked in
4261 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004262 * @hide
4263 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004264 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004265 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004266 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004267 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004268 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004269 return mVpns.get(user).establish(config);
4270 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004271 }
4272
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004273 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004274 * Start legacy VPN, controlling native daemons as needed. Creates a
4275 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004276 */
4277 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004278 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004279 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004280 final LinkProperties egress = getActiveLinkProperties();
4281 if (egress == null) {
4282 throw new IllegalStateException("Missing active network connection");
4283 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004284 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004285 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004286 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4287 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004288 }
4289
4290 /**
4291 * Return the information of the ongoing legacy VPN. This method is used
4292 * by VpnSettings and not available in ConnectivityManager. Permissions
4293 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004294 */
4295 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004296 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4297 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004298
Hugo Benichi20035e02017-04-26 14:53:28 +09004299 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004300 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004301 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004302 }
4303
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004304 /**
Varun Anand02c50ef2019-02-07 14:13:13 -08004305 * Return the information of all ongoing VPNs.
4306 *
4307 * <p>This method is used to update NetworkStatsService.
4308 *
4309 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004310 */
Varun Anand02c50ef2019-02-07 14:13:13 -08004311 private VpnInfo[] getAllVpnInfo() {
4312 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004313 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004314 if (mLockdownEnabled) {
4315 return new VpnInfo[0];
4316 }
4317
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004318 List<VpnInfo> infoList = new ArrayList<>();
4319 for (int i = 0; i < mVpns.size(); i++) {
4320 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4321 if (info != null) {
4322 infoList.add(info);
4323 }
4324 }
4325 return infoList.toArray(new VpnInfo[infoList.size()]);
4326 }
4327 }
4328
4329 /**
4330 * @return VPN information for accounting, or null if we can't retrieve all required
4331 * information, e.g primary underlying iface.
4332 */
4333 @Nullable
4334 private VpnInfo createVpnInfo(Vpn vpn) {
4335 VpnInfo info = vpn.getVpnInfo();
4336 if (info == null) {
4337 return null;
4338 }
4339 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4340 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4341 // the underlyingNetworks list.
4342 if (underlyingNetworks == null) {
4343 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4344 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4345 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4346 }
4347 } else if (underlyingNetworks.length > 0) {
4348 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4349 if (linkProperties != null) {
4350 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4351 }
4352 }
4353 return info.primaryUnderlyingIface == null ? null : info;
4354 }
4355
4356 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004357 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4358 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004359 * Permissions are checked in Vpn class.
4360 * @hide
4361 */
4362 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004363 public VpnConfig getVpnConfig(int userId) {
4364 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004365 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004366 Vpn vpn = mVpns.get(userId);
4367 if (vpn != null) {
4368 return vpn.getVpnConfig();
4369 } else {
4370 return null;
4371 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004372 }
4373 }
4374
Chalard Jean6b65ec72018-05-18 22:02:56 +09004375 /**
4376 * Ask all VPN objects to recompute and update their capabilities.
4377 *
4378 * When underlying networks change, VPNs may have to update capabilities to reflect things
4379 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4380 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4381 * handler thread through their agent, this is asynchronous. When the capabilities objects
4382 * are computed they will be up-to-date as they are computed synchronously from here and
4383 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004384 */
4385 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004386 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004387 synchronized (mVpns) {
4388 for (int i = 0; i < mVpns.size(); i++) {
4389 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004390 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4391 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004392 }
4393 }
4394 }
4395
Varun Anand4fa80e82019-02-06 10:13:38 -08004396 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4397 ensureRunningOnConnectivityServiceThread();
4398 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4399 if (vpnNai == null || nc == null) {
4400 return;
4401 }
4402 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4403 }
4404
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004405 @Override
4406 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004407 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4408 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4409 return false;
4410 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004411
Hugo Benichi69744342017-11-27 10:57:16 +09004412 synchronized (mVpns) {
4413 // Tear down existing lockdown if profile was removed
4414 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4415 if (mLockdownEnabled) {
4416 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4417 if (profileTag == null) {
4418 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4419 return false;
4420 }
4421 String profileName = new String(profileTag);
4422 final VpnProfile profile = VpnProfile.decode(
4423 profileName, mKeyStore.get(Credentials.VPN + profileName));
4424 if (profile == null) {
4425 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4426 setLockdownTracker(null);
4427 return true;
4428 }
4429 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004430 Vpn vpn = mVpns.get(user);
4431 if (vpn == null) {
4432 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4433 return false;
4434 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004435 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004436 } else {
4437 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004438 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004439 }
4440
4441 return true;
4442 }
4443
4444 /**
4445 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4446 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4447 */
Hugo Benichi69744342017-11-27 10:57:16 +09004448 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004449 private void setLockdownTracker(LockdownVpnTracker tracker) {
4450 // Shutdown any existing tracker
4451 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004452 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4453 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004454 mLockdownTracker = null;
4455 if (existing != null) {
4456 existing.shutdown();
4457 }
4458
Robin Leec3736bc2017-03-10 16:19:54 +00004459 if (tracker != null) {
4460 mLockdownTracker = tracker;
4461 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004462 }
4463 }
4464
Hugo Benichi69744342017-11-27 10:57:16 +09004465 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004466 private void throwIfLockdownEnabled() {
4467 if (mLockdownEnabled) {
4468 throw new IllegalStateException("Unavailable in lockdown mode");
4469 }
4470 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004471
Robin Lee244ce8e2016-01-05 18:03:46 +00004472 /**
Robin Lee17e61832016-05-09 13:46:28 +01004473 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4474 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004475 *
Robin Lee17e61832016-05-09 13:46:28 +01004476 * @return {@code true} if the service was started, the service was already connected, or there
4477 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004478 */
Robin Lee17e61832016-05-09 13:46:28 +01004479 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004480 synchronized (mVpns) {
4481 Vpn vpn = mVpns.get(userId);
4482 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004483 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004484 // exists already.
4485 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4486 return false;
4487 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004488
Robin Lee812800c2016-05-13 15:38:08 +01004489 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004490 }
4491 }
4492
4493 @Override
Charles He36738632017-05-15 17:07:18 +01004494 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4495 enforceSettingsPermission();
4496 enforceCrossUserPermission(userId);
4497
4498 synchronized (mVpns) {
4499 Vpn vpn = mVpns.get(userId);
4500 if (vpn == null) {
4501 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4502 return false;
4503 }
4504 return vpn.isAlwaysOnPackageSupported(packageName);
4505 }
4506 }
4507
4508 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004509 public boolean setAlwaysOnVpnPackage(
4510 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4511 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004512 enforceCrossUserPermission(userId);
4513
Robin Lee244ce8e2016-01-05 18:03:46 +00004514 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004515 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4516 if (LockdownVpnTracker.isEnabled()) {
4517 return false;
4518 }
4519
Robin Lee244ce8e2016-01-05 18:03:46 +00004520 Vpn vpn = mVpns.get(userId);
4521 if (vpn == null) {
4522 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4523 return false;
4524 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004525 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004526 return false;
4527 }
Robin Lee17e61832016-05-09 13:46:28 +01004528 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004529 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004530 return false;
4531 }
4532 }
4533 return true;
4534 }
4535
4536 @Override
4537 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004538 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004539 enforceCrossUserPermission(userId);
4540
4541 synchronized (mVpns) {
4542 Vpn vpn = mVpns.get(userId);
4543 if (vpn == null) {
4544 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4545 return null;
4546 }
4547 return vpn.getAlwaysOnPackage();
4548 }
4549 }
4550
Wink Savilleab9321d2013-06-29 21:10:57 -07004551 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004552 public boolean isVpnLockdownEnabled(int userId) {
4553 enforceControlAlwaysOnVpnPermission();
4554 enforceCrossUserPermission(userId);
4555
4556 synchronized (mVpns) {
4557 Vpn vpn = mVpns.get(userId);
4558 if (vpn == null) {
4559 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4560 return false;
4561 }
4562 return vpn.getLockdown();
4563 }
4564 }
4565
4566 @Override
4567 public List<String> getVpnLockdownWhitelist(int userId) {
4568 enforceControlAlwaysOnVpnPermission();
4569 enforceCrossUserPermission(userId);
4570
4571 synchronized (mVpns) {
4572 Vpn vpn = mVpns.get(userId);
4573 if (vpn == null) {
4574 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4575 return null;
4576 }
4577 return vpn.getLockdownWhitelist();
4578 }
4579 }
4580
4581 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004582 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004583 // TODO: Remove? Any reason to trigger a provisioning check?
4584 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004585 }
4586
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004587 /** Location to an updatable file listing carrier provisioning urls.
4588 * An example:
4589 *
4590 * <?xml version="1.0" encoding="utf-8"?>
4591 * <provisioningUrls>
4592 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004593 * </provisioningUrls>
4594 */
4595 private static final String PROVISIONING_URL_PATH =
4596 "/data/misc/radio/provisioning_urls.xml";
4597 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004598
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004599 /** XML tag for root element. */
4600 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4601 /** XML tag for individual url */
4602 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004603 /** XML attribute for mcc */
4604 private static final String ATTR_MCC = "mcc";
4605 /** XML attribute for mnc */
4606 private static final String ATTR_MNC = "mnc";
4607
Paul Jensen434dde82015-06-11 09:43:30 -04004608 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004609 FileReader fileReader = null;
4610 XmlPullParser parser = null;
4611 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004612
4613 try {
4614 fileReader = new FileReader(mProvisioningUrlFile);
4615 parser = Xml.newPullParser();
4616 parser.setInput(fileReader);
4617 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4618
4619 while (true) {
4620 XmlUtils.nextElement(parser);
4621
4622 String element = parser.getName();
4623 if (element == null) break;
4624
Paul Jensen434dde82015-06-11 09:43:30 -04004625 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004626 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4627 try {
4628 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4629 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4630 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4631 parser.next();
4632 if (parser.getEventType() == XmlPullParser.TEXT) {
4633 return parser.getText();
4634 }
4635 }
4636 }
4637 } catch (NumberFormatException e) {
4638 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4639 }
4640 }
4641 }
4642 return null;
4643 } catch (FileNotFoundException e) {
4644 loge("Carrier Provisioning Urls file not found");
4645 } catch (XmlPullParserException e) {
4646 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4647 } catch (IOException e) {
4648 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4649 } finally {
4650 if (fileReader != null) {
4651 try {
4652 fileReader.close();
4653 } catch (IOException e) {}
4654 }
4655 }
4656 return null;
4657 }
4658
Wink Saville42d4f082013-07-20 20:31:59 -07004659 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004660 public String getMobileProvisioningUrl() {
4661 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004662 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004663 if (TextUtils.isEmpty(url)) {
4664 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004665 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004666 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004667 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004668 }
Wink Saville8cf35602013-07-10 23:00:07 -07004669 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004670 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004671 String phoneNumber = mTelephonyManager.getLine1Number();
4672 if (TextUtils.isEmpty(phoneNumber)) {
4673 phoneNumber = "0000000000";
4674 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004675 url = String.format(url,
4676 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4677 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004678 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004679 }
4680
Wink Savilleab9321d2013-06-29 21:10:57 -07004681 return url;
4682 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004683
Wink Saville948282b2013-08-29 08:55:16 -07004684 @Override
4685 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004686 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004687 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004688 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4689 return;
4690 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004691 final long ident = Binder.clearCallingIdentity();
4692 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004693 // Concatenate the range of types onto the range of NetIDs.
4694 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4695 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004696 } finally {
4697 Binder.restoreCallingIdentity(ident);
4698 }
Wink Saville948282b2013-08-29 08:55:16 -07004699 }
Wink Saville7788c612013-08-29 14:57:08 -07004700
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004701 @Override
4702 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004703 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004704 final long ident = Binder.clearCallingIdentity();
4705 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004706 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004707 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004708 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4709 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004710 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004711 } finally {
4712 Binder.restoreCallingIdentity(ident);
4713 }
4714 }
4715
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004716 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004717 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004718 Vpn userVpn = mVpns.get(userId);
4719 if (userVpn != null) {
4720 loge("Starting user already has a VPN");
4721 return;
4722 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004723 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004724 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004725 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4726 updateLockdownVpn();
4727 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004728 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004729 }
4730
4731 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004732 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004733 Vpn userVpn = mVpns.get(userId);
4734 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004735 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004736 return;
4737 }
Robin Lee17e61832016-05-09 13:46:28 +01004738 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004739 mVpns.delete(userId);
4740 }
4741 }
4742
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004743 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004744 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004745 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004746 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004747 final int vpnsSize = mVpns.size();
4748 for (int i = 0; i < vpnsSize; i++) {
4749 Vpn vpn = mVpns.valueAt(i);
4750 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004751 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4752 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004753 }
4754 }
4755 }
4756
4757 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004758 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004759 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004760 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004761 final int vpnsSize = mVpns.size();
4762 for (int i = 0; i < vpnsSize; i++) {
4763 Vpn vpn = mVpns.valueAt(i);
4764 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004765 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4766 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004767 }
4768 }
4769 }
4770
junyulai2454b692018-11-01 17:16:31 +08004771 private void onPackageAdded(String packageName, int uid) {
4772 if (TextUtils.isEmpty(packageName) || uid < 0) {
4773 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4774 return;
4775 }
4776 mPermissionMonitor.onPackageAdded(packageName, uid);
4777 }
4778
junyulaiefb04d32018-11-12 22:39:30 +08004779 private void onPackageReplaced(String packageName, int uid) {
4780 if (TextUtils.isEmpty(packageName) || uid < 0) {
4781 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4782 return;
4783 }
4784 final int userId = UserHandle.getUserId(uid);
4785 synchronized (mVpns) {
4786 final Vpn vpn = mVpns.get(userId);
4787 if (vpn == null) {
4788 return;
4789 }
4790 // Legacy always-on VPN won't be affected since the package name is not set.
4791 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4792 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4793 + userId);
4794 vpn.startAlwaysOnVpn();
4795 }
4796 }
4797 }
4798
4799 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004800 if (TextUtils.isEmpty(packageName) || uid < 0) {
4801 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4802 return;
4803 }
4804 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004805
4806 final int userId = UserHandle.getUserId(uid);
4807 synchronized (mVpns) {
4808 final Vpn vpn = mVpns.get(userId);
4809 if (vpn == null) {
4810 return;
4811 }
4812 // Legacy always-on VPN won't be affected since the package name is not set.
4813 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4814 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4815 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004816 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004817 }
4818 }
junyulai2454b692018-11-01 17:16:31 +08004819 }
4820
Robin Lee89e7a692016-02-29 14:38:17 +00004821 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004822 synchronized (mVpns) {
4823 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4824 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4825 updateLockdownVpn();
4826 } else {
4827 startAlwaysOnVpn(userId);
4828 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004829 }
4830 }
4831
junyulai2454b692018-11-01 17:16:31 +08004832 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004833 @Override
4834 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004835 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004836 final String action = intent.getAction();
4837 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004838 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4839 final Uri packageData = intent.getData();
4840 final String packageName =
4841 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004842 if (userId == UserHandle.USER_NULL) return;
4843
Robin Lee323f29d2016-05-04 16:38:06 +01004844 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004845 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004846 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004847 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004848 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4849 onUserAdded(userId);
4850 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4851 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004852 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4853 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004854 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4855 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004856 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4857 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004858 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004859 final boolean isReplacing = intent.getBooleanExtra(
4860 Intent.EXTRA_REPLACING, false);
4861 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004862 }
4863 }
4864 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004865
Robin Lee95204e02017-01-27 11:59:22 +00004866 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4867 @Override
4868 public void onReceive(Context context, Intent intent) {
4869 // Try creating lockdown tracker, since user present usually means
4870 // unlocked keystore.
4871 updateLockdownVpn();
4872 mContext.unregisterReceiver(this);
4873 }
4874 };
4875
Chalard Jean4133a122018-06-04 13:33:12 +09004876 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4877 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004878
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004879 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4880 // Map from UID to number of NetworkRequests that UID has filed.
4881 @GuardedBy("mUidToNetworkRequestCount")
4882 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4883
Robert Greenwalta67be032014-05-16 15:49:14 -07004884 private static class NetworkFactoryInfo {
4885 public final String name;
4886 public final Messenger messenger;
4887 public final AsyncChannel asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004888 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004889
Chalard Jean08577fc2018-05-02 21:14:54 +09004890 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4891 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004892 this.name = name;
4893 this.messenger = messenger;
4894 this.asyncChannel = asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004895 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004896 }
4897 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004898
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004899 private void ensureNetworkRequestHasType(NetworkRequest request) {
4900 if (request.type == NetworkRequest.Type.NONE) {
4901 throw new IllegalArgumentException(
4902 "All NetworkRequests in ConnectivityService must have a type");
4903 }
4904 }
4905
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004906 /**
4907 * Tracks info about the requester.
4908 * Also used to notice when the calling process dies so we can self-expire
4909 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004910 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004911 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004912 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004913 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004914 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004915 final int mPid;
4916 final int mUid;
4917 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004918
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004919 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004920 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004921 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004922 mPendingIntent = pi;
4923 messenger = null;
4924 mBinder = null;
4925 mPid = getCallingPid();
4926 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004927 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004928 }
4929
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004930 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004931 super();
4932 messenger = m;
4933 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004934 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004935 mBinder = binder;
4936 mPid = getCallingPid();
4937 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004938 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004939 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004940
4941 try {
4942 mBinder.linkToDeath(this, 0);
4943 } catch (RemoteException e) {
4944 binderDied();
4945 }
4946 }
4947
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004948 private void enforceRequestCountLimit() {
4949 synchronized (mUidToNetworkRequestCount) {
4950 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4951 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004952 throw new ServiceSpecificException(
4953 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004954 }
4955 mUidToNetworkRequestCount.put(mUid, networkRequests);
4956 }
4957 }
4958
Robert Greenwalt9258c642014-03-26 16:47:06 -07004959 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004960 if (mBinder != null) {
4961 mBinder.unlinkToDeath(this, 0);
4962 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004963 }
4964
4965 public void binderDied() {
4966 log("ConnectivityService NetworkRequestInfo binderDied(" +
4967 request + ", " + mBinder + ")");
4968 releaseNetworkRequest(request);
4969 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004970
4971 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004972 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004973 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004974 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004975 }
4976
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004977 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4978 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4979 if (badCapability != null) {
4980 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004981 }
4982 }
4983
paulhu3d67f532019-03-22 16:35:06 +08004984 // This checks that the passed capabilities either do not request a specific SSID/SignalStrength
4985 // , or the calling app has permission to do so.
Chalard Jeanb03a6222018-04-11 21:09:10 +09004986 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4987 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004988 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004989 throw new SecurityException("Insufficient permissions to request a specific SSID");
4990 }
paulhu3d67f532019-03-22 16:35:06 +08004991
4992 if (nc.hasSignalStrength()
4993 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
4994 throw new SecurityException(
4995 "Insufficient permissions to request a specific signal strength");
4996 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09004997 }
4998
Erik Kline9d598e12015-07-13 16:37:51 +09004999 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09005000 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005001 synchronized (nai) {
5002 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5003 if (nri.request.networkCapabilities.hasSignalStrength() &&
5004 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
5005 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
5006 }
5007 }
5008 }
Chalard Jean4133a122018-06-04 13:33:12 +09005009 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005010 }
5011
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005012 private void updateSignalStrengthThresholds(
5013 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5014 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09005015 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005016 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
5017
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005018 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005019 String detail;
5020 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5021 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5022 } else {
5023 detail = reason;
5024 }
5025 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5026 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
5027 }
5028
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005029 nai.asyncChannel.sendMessage(
5030 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09005031 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005032 }
5033
Etan Cohen859748f2017-04-03 17:42:34 -07005034 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5035 if (nc == null) {
5036 return;
5037 }
5038 NetworkSpecifier ns = nc.getNetworkSpecifier();
5039 if (ns == null) {
5040 return;
5041 }
5042 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5043 ns.assertValidFromUid(Binder.getCallingUid());
5044 }
5045
Robert Greenwalt9258c642014-03-26 16:47:06 -07005046 @Override
5047 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005048 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005049 final NetworkRequest.Type type = (networkCapabilities == null)
5050 ? NetworkRequest.Type.TRACK_DEFAULT
5051 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005052 // If the requested networkCapabilities is null, take them instead from
5053 // the default network request. This allows callers to keep track of
5054 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005055 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005056 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005057 enforceAccessPermission();
5058 } else {
5059 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5060 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005061 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5062 // of the app when the request is filed, but we never change the request if the app
5063 // changes network state. http://b/29964605
5064 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005065 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005066 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005067 ensureSufficientPermissionsForRequest(networkCapabilities,
5068 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005069 // Set the UID range for this request to the single UID of the requester, or to an empty
5070 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005071 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5072 // are no visible methods to set the UIDs, an app could use reflection to try and get
5073 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005074 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005075
Etan Cohenba07c8c2017-02-05 10:42:27 -08005076 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005077 throw new IllegalArgumentException("Bad timeout specified");
5078 }
Etan Cohen859748f2017-04-03 17:42:34 -07005079 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005080
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005081 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005082 nextNetworkRequestId(), type);
5083 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005084 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005085
5086 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005087 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005088 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005089 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005090 }
5091 return networkRequest;
5092 }
5093
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005094 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005095 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005096 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005097 } else {
5098 enforceChangePermission();
5099 }
5100 }
5101
fenglub15e72b2015-03-20 11:29:56 -07005102 @Override
fengludb571472015-04-21 17:12:05 -07005103 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005104 enforceAccessPermission();
5105 NetworkAgentInfo nai = null;
5106 if (network == null) {
5107 return false;
5108 }
5109 synchronized (mNetworkForNetId) {
5110 nai = mNetworkForNetId.get(network.netId);
5111 }
5112 if (nai != null) {
5113 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005114 synchronized (mBandwidthRequests) {
5115 final int uid = Binder.getCallingUid();
5116 Integer uidReqs = mBandwidthRequests.get(uid);
5117 if (uidReqs == null) {
5118 uidReqs = new Integer(0);
5119 }
5120 mBandwidthRequests.put(uid, ++uidReqs);
5121 }
fenglub15e72b2015-03-20 11:29:56 -07005122 return true;
5123 }
5124 return false;
5125 }
5126
Felipe Lemeee27cab2016-06-20 16:36:29 -07005127 private boolean isSystem(int uid) {
5128 return uid < Process.FIRST_APPLICATION_UID;
5129 }
fenglub15e72b2015-03-20 11:29:56 -07005130
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005131 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005132 final int uid = Binder.getCallingUid();
5133 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005134 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005135 return;
5136 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005137 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5138 // Policy already enforced.
5139 return;
5140 }
5141 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5142 // If UID is restricted, don't allow them to bring up metered APNs.
5143 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005144 }
5145 }
5146
Robert Greenwalt9258c642014-03-26 16:47:06 -07005147 @Override
5148 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5149 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005150 checkNotNull(operation, "PendingIntent cannot be null.");
5151 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5152 enforceNetworkRequestPermissions(networkCapabilities);
5153 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005154 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005155 ensureSufficientPermissionsForRequest(networkCapabilities,
5156 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005157 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005158 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005159
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005160 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005161 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5162 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005163 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005164 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5165 nri));
5166 return networkRequest;
5167 }
5168
Jeremy Joslin79294842014-12-03 17:15:28 -08005169 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5170 mHandler.sendMessageDelayed(
5171 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5172 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5173 }
5174
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005175 @Override
5176 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005177 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005178 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5179 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005180 }
5181
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005182 // In order to implement the compatibility measure for pre-M apps that call
5183 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5184 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5185 // This ensures it has permission to do so.
5186 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5187 if (nc == null) {
5188 return false;
5189 }
5190 int[] transportTypes = nc.getTransportTypes();
5191 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5192 return false;
5193 }
5194 try {
5195 mContext.enforceCallingOrSelfPermission(
5196 android.Manifest.permission.ACCESS_WIFI_STATE,
5197 "ConnectivityService");
5198 } catch (SecurityException e) {
5199 return false;
5200 }
5201 return true;
5202 }
5203
Robert Greenwalt9258c642014-03-26 16:47:06 -07005204 @Override
5205 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5206 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005207 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5208 enforceAccessPermission();
5209 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005210
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005211 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005212 ensureSufficientPermissionsForRequest(networkCapabilities,
5213 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005214 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005215 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5216 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5217 // onLost and onAvailable callbacks when networks move in and out of the background.
5218 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5219 // can't request networks.
5220 restrictBackgroundRequestForCaller(nc);
5221 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005222
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005223 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005224 NetworkRequest.Type.LISTEN);
5225 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005226 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005227
5228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5229 return networkRequest;
5230 }
5231
5232 @Override
5233 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5234 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005235 checkNotNull(operation, "PendingIntent cannot be null.");
5236 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5237 enforceAccessPermission();
5238 }
Etan Cohen859748f2017-04-03 17:42:34 -07005239 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005240 ensureSufficientPermissionsForRequest(networkCapabilities,
5241 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005242
Chalard Jeandda156a2018-01-10 21:19:32 +09005243 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005244 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005245
5246 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005247 NetworkRequest.Type.LISTEN);
5248 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005249 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005250
5251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005252 }
5253
Erik Klineacdd6392016-07-07 16:50:58 +09005254 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005255 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005256 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005257 mHandler.sendMessage(mHandler.obtainMessage(
5258 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005259 }
5260
5261 @Override
Chalard Jean08577fc2018-05-02 21:14:54 +09005262 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005263 enforceConnectivityInternalPermission();
Chalard Jean08577fc2018-05-02 21:14:54 +09005264 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5265 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005266 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean08577fc2018-05-02 21:14:54 +09005267 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005268 }
5269
Robert Greenwalta67be032014-05-16 15:49:14 -07005270 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005271 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005272 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5273 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5274 }
5275
5276 @Override
5277 public void unregisterNetworkFactory(Messenger messenger) {
5278 enforceConnectivityInternalPermission();
5279 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5280 }
5281
5282 private void handleUnregisterNetworkFactory(Messenger messenger) {
5283 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5284 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005285 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005286 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005287 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005288 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005289 }
5290
Robert Greenwalt7b816022014-04-18 15:25:25 -07005291 /**
5292 * NetworkAgentInfo supporting a request by requestId.
5293 * These have already been vetted (their Capabilities satisfy the request)
5294 * and the are the highest scored network available.
5295 * the are keyed off the Requests requestId.
5296 */
Hugo Benichicd952782017-09-20 11:20:14 +09005297 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5298 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005299 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005300
Paul Jensen31a94f42015-02-13 14:18:39 -05005301 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5302 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005303 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005304 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5305 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5306 // there may not be a strict 1:1 correlation between the two.
5307 @GuardedBy("mNetworkForNetId")
5308 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005309
Robert Greenwalt7b816022014-04-18 15:25:25 -07005310 // NetworkAgentInfo keyed off its connecting messenger
5311 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005312 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005313 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005314
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005315 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005316 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005317
Paul Jensen2c311d62014-11-17 12:34:51 -05005318 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005319 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005320
Erik Klineda4bfa82015-04-30 12:58:40 +09005321 // Request used to optionally keep mobile data active even when higher
5322 // priority networks like Wi-Fi are active.
5323 private final NetworkRequest mDefaultMobileDataRequest;
5324
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005325 // Request used to optionally keep wifi data active even when higher
5326 // priority networks like ethernet are active.
5327 private final NetworkRequest mDefaultWifiRequest;
5328
Hugo Benichicd952782017-09-20 11:20:14 +09005329 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5330 synchronized (mNetworkForRequestId) {
5331 return mNetworkForRequestId.get(requestId);
5332 }
5333 }
5334
5335 private void clearNetworkForRequest(int requestId) {
5336 synchronized (mNetworkForRequestId) {
5337 mNetworkForRequestId.remove(requestId);
5338 }
5339 }
5340
5341 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5342 synchronized (mNetworkForRequestId) {
5343 mNetworkForRequestId.put(requestId, nai);
5344 }
5345 }
5346
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005347 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005348 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005349 }
5350
Varun Anand4fa80e82019-02-06 10:13:38 -08005351 @Nullable
5352 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5353 return nai != null ? nai.network : null;
5354 }
5355
5356 private void ensureRunningOnConnectivityServiceThread() {
5357 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5358 throw new IllegalStateException(
5359 "Not running on ConnectivityService thread: "
5360 + Thread.currentThread().getName());
5361 }
5362 }
5363
Chalard Jeanff46a252019-04-10 23:07:55 +09005364 @VisibleForTesting
5365 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005366 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005367 }
5368
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005369 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5370 return nri.request.requestId == mDefaultRequest.requestId;
5371 }
5372
Chalard Jean08577fc2018-05-02 21:14:54 +09005373 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5374 // changes that would conflict throughout the automerger graph. Having this method temporarily
5375 // helps with the process of going through with all these dependent changes across the entire
5376 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005377 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005378 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005379 int currentScore, NetworkMisc networkMisc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005380 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5381 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5382 }
5383
5384 /**
5385 * Register a new agent with ConnectivityService to handle a network.
5386 *
5387 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5388 * @param networkInfo the initial info associated with this network. It can be updated later :
5389 * see {@link #updateNetworkInfo}.
5390 * @param linkProperties the initial link properties of this network. They can be updated
5391 * later : see {@link #updateLinkProperties}.
5392 * @param networkCapabilities the initial capabilites of this network. They can be updated
5393 * later : see {@link #updateNetworkCapabilities}.
5394 * @param currentScore the initial score of the network. See
5395 * {@link NetworkAgentInfo#getCurrentScore}.
5396 * @param networkMisc metadata about the network. This is never updated.
5397 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5398 */
5399 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5400 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5401 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005402 enforceConnectivityInternalPermission();
5403
Rubin Xu1bb5c082017-09-05 18:40:49 +01005404 LinkProperties lp = new LinkProperties(linkProperties);
5405 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005406 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5407 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005408 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005409 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005410 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Luke Huang65914772019-03-16 00:31:46 +08005411 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mDnsResolver,
5412 mNMS, factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005413 // Make sure the network capabilities reflect what the agent info says.
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005414 nai.setNetworkCapabilities(mixInCapabilities(nai, nc));
Chalard Jeand771aa02018-04-26 16:16:10 +09005415 final String extraInfo = networkInfo.getExtraInfo();
5416 final String name = TextUtils.isEmpty(extraInfo)
5417 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005418 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005419 final long token = Binder.clearCallingIdentity();
5420 try {
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005421 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005422 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005423 } finally {
5424 Binder.restoreCallingIdentity(token);
5425 }
5426 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5427 // If the network disconnects or sends any other event before that, messages are deferred by
5428 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5429 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005430 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005431 }
5432
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005433 @VisibleForTesting
5434 protected NetworkStackClient getNetworkStack() {
5435 return NetworkStackClient.getInstance();
5436 }
5437
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005438 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5439 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005440 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005441 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005442 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005443 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005444 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005445
5446 try {
5447 networkMonitor.start();
5448 } catch (RemoteException e) {
5449 e.rethrowFromSystemServer();
5450 }
Erik Klinee5dac902018-03-04 21:01:01 +09005451 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5452 NetworkInfo networkInfo = nai.networkInfo;
5453 nai.networkInfo = null;
5454 updateNetworkInfo(nai, networkInfo);
5455 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005456 }
5457
lucaslin25a4ec32018-11-28 12:51:55 +08005458 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5459 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005460 int netId = networkAgent.network.netId;
5461
Lorenzo Colittidf595632019-01-08 14:43:37 +09005462 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5463 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5464 // are accurate.
5465 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005466
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005467 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005468 updateMtu(newLp, oldLp);
5469 // TODO - figure out what to do for clat
5470// for (LinkProperties lp : newLp.getStackedLinks()) {
5471// updateMtu(lp, null);
5472// }
lucaslin041a1af2018-11-28 19:27:52 +08005473 if (isDefaultNetwork(networkAgent)) {
5474 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5475 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005476
Erik Kline94887872016-04-05 13:30:49 +09005477 updateRoutes(newLp, oldLp, netId);
5478 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005479 // Make sure LinkProperties represents the latest private DNS status.
5480 // This does not need to be done before updateDnses because the
5481 // LinkProperties are not the source of the private DNS configuration.
5482 // updateDnses will fetch the private DNS configuration from DnsManager.
5483 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005484
Paul Jensene0bef712014-12-10 15:12:18 -05005485 if (isDefaultNetwork(networkAgent)) {
5486 handleApplyDefaultProxy(newLp.getHttpProxy());
5487 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005488 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005489 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005490 // TODO - move this check to cover the whole function
5491 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005492 synchronized (networkAgent) {
5493 networkAgent.linkProperties = newLp;
5494 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005495 // Start or stop DNS64 detection and 464xlat according to network state.
5496 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005497 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005498 try {
5499 networkAgent.networkMonitor().notifyLinkPropertiesChanged(newLp);
5500 } catch (RemoteException e) {
5501 e.rethrowFromSystemServer();
5502 }
lucaslin25a4ec32018-11-28 12:51:55 +08005503 if (networkAgent.everConnected) {
5504 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5505 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005506 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005507
5508 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005509 }
5510
Joel Scherpelz668370b2017-06-08 15:35:21 +09005511 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005512 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005513 // marks on unsupported interfaces is harmless.
5514 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5515 return;
5516 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005517
Joel Scherpelz668370b2017-06-08 15:35:21 +09005518 int mark = mContext.getResources().getInteger(
5519 com.android.internal.R.integer.config_networkWakeupPacketMark);
5520 int mask = mContext.getResources().getInteger(
5521 com.android.internal.R.integer.config_networkWakeupPacketMask);
5522
5523 // Mask/mark of zero will not detect anything interesting.
5524 // Don't install rules unless both values are nonzero.
5525 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005526 return;
5527 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005528
5529 final String prefix = "iface:" + iface;
5530 try {
5531 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005532 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005533 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005534 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005535 }
5536 } catch (Exception e) {
5537 loge("Exception modifying wakeup packet monitoring: " + e);
5538 }
5539
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005540 }
5541
5542 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5543 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005544 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005545 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5546 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005547 for (String iface : interfaceDiff.added) {
5548 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005549 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005550 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005551 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005552 } catch (Exception e) {
5553 loge("Exception adding interface: " + e);
5554 }
5555 }
5556 for (String iface : interfaceDiff.removed) {
5557 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005558 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005559 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005560 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005561 } catch (Exception e) {
5562 loge("Exception removing interface: " + e);
5563 }
5564 }
5565 }
5566
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005567 /**
5568 * Have netd update routes from oldLp to newLp.
5569 * @return true if routes changed between oldLp and newLp
5570 */
5571 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005572 // Compare the route diff to determine which routes should be added and removed.
5573 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5574 oldLp != null ? oldLp.getAllRoutes() : null,
5575 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005576
5577 // add routes before removing old in case it helps with continuous connectivity
5578
Chalard Jean4d660112018-06-04 16:52:49 +09005579 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005580 for (RouteInfo route : routeDiff.added) {
5581 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005582 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005583 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005584 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005585 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005586 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5587 loge("Exception in addRoute for non-gateway: " + e);
5588 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005589 }
5590 }
5591 for (RouteInfo route : routeDiff.added) {
5592 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005593 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005594 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005595 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005596 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005597 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5598 loge("Exception in addRoute for gateway: " + e);
5599 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005600 }
5601 }
5602
5603 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005604 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005605 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005606 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005607 } catch (Exception e) {
5608 loge("Exception in removeRoute: " + e);
5609 }
5610 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005611 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005612 }
Erik Kline41368502015-06-17 13:19:54 +09005613
Erik Kline94887872016-04-05 13:30:49 +09005614 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5615 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5616 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005617 }
Erik Kline94887872016-04-05 13:30:49 +09005618
Erik Kline1742fe12017-12-13 19:40:49 +09005619 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5620 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5621
Erik Klinea24d4592018-01-11 21:07:29 +09005622 if (DBG) {
5623 final Collection<InetAddress> dnses = newLp.getDnsServers();
5624 log("Setting DNS servers for network " + netId + " to " + dnses);
5625 }
Erik Kline94887872016-04-05 13:30:49 +09005626 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005627 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005628 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005629 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005630 }
Erik Kline4edba012017-04-07 15:29:29 +09005631 }
5632
Luke Huang8a462ec2018-08-24 20:33:16 +08005633 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005634 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005635 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005636 }
5637 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005638 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005639 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005640 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005641 }
5642
Paul Jensen3d194ea2015-06-16 14:27:36 -04005643 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005644 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5645 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5646 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005647 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005648 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005649 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005650 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5651 // causing a connect/teardown loop.
5652 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5653 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005654 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005655 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005656 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5657 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005658 // does not cause any request (that is not a listen) currently matching that agent to
5659 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005660 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005661 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005662 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005663 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005664 }
5665
Paul Jensen3d194ea2015-06-16 14:27:36 -04005666 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005667 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005668 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005669 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005670 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005671 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005672 }
Paul Jensene0988542015-06-25 15:30:08 -04005673 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005674 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005675 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005676 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005677 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005678 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005679 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005680 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005681 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005682 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005683 if (nai.isSuspended()) {
5684 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5685 } else {
5686 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5687 }
lucasline252a742019-03-12 13:08:03 +08005688 if (nai.partialConnectivity) {
5689 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5690 } else {
5691 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5692 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005693
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005694 return newNc;
5695 }
5696
5697 /**
5698 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5699 *
5700 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5701 * capabilities we manage and store in {@code nai}, such as validated status and captive
5702 * portal status)
5703 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5704 * potentially triggers rematches.
5705 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5706 * change.)
5707 *
5708 * @param oldScore score of the network before any of the changes that prompted us
5709 * to call this function.
5710 * @param nai the network having its capabilities updated.
5711 * @param nc the new network capabilities.
5712 */
5713 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5714 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5715
5716 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005717
Luke Huang8a462ec2018-08-24 20:33:16 +08005718 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5719 final int newPermission = getNetworkPermission(newNc);
5720 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005721 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005722 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005723 } catch (RemoteException e) {
5724 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005725 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005726 }
5727
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005728 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005729 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005730 prevNc = nai.networkCapabilities;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005731 nai.setNetworkCapabilities(newNc);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005732 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005733
Chalard Jeanf213ca12018-01-16 18:43:05 +09005734 updateUids(nai, prevNc, newNc);
5735
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005736 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005737 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5738 // the change we're processing can't affect any requests, it can only affect the listens
5739 // on this network. We might have been called by rematchNetworkAndRequests when a
5740 // network changed foreground state.
5741 processListenRequests(nai, true);
5742 } else {
5743 // If the requestable capabilities have changed or the score changed, we can't have been
5744 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005745 rematchAllNetworksAndRequests(nai, oldScore);
5746 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005747 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005748
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005749 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005750 final boolean oldMetered = prevNc.isMetered();
5751 final boolean newMetered = newNc.isMetered();
5752 final boolean meteredChanged = oldMetered != newMetered;
5753
5754 if (meteredChanged) {
5755 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5756 mRestrictBackground);
5757 }
5758
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005759 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005760 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005761
5762 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005763 if (meteredChanged || roamingChanged) {
5764 notifyIfacesChangedForNetworkStats();
5765 }
5766 }
5767
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005768 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005769 // Tell VPNs about updated capabilities, since they may need to
5770 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005771 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005772 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005773 }
5774
Chalard Jeanf213ca12018-01-16 18:43:05 +09005775 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5776 NetworkCapabilities newNc) {
5777 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5778 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5779 if (null == prevRanges) prevRanges = new ArraySet<>();
5780 if (null == newRanges) newRanges = new ArraySet<>();
5781 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5782
5783 prevRanges.removeAll(newRanges);
5784 newRanges.removeAll(prevRangesCopy);
5785
5786 try {
5787 if (!newRanges.isEmpty()) {
5788 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5789 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005790 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005791 }
5792 if (!prevRanges.isEmpty()) {
5793 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5794 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005795 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005796 }
5797 } catch (Exception e) {
5798 // Never crash!
5799 loge("Exception in updateUids: " + e);
5800 }
5801 }
5802
Hugo Benichief502882017-09-01 01:23:32 +00005803 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005804 ensureRunningOnConnectivityServiceThread();
5805
Erik Kline736353a2018-03-21 07:18:33 -07005806 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005807 // Ignore updates for disconnected networks
5808 return;
5809 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005810 // newLp is already a defensive copy.
5811 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005812 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005813 log("Update of LinkProperties for " + nai.name() +
5814 "; created=" + nai.created +
5815 "; everConnected=" + nai.everConnected);
5816 }
lucaslin25a4ec32018-11-28 12:51:55 +08005817 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005818 }
5819
Paul Jensenc8b9a742014-09-30 15:37:41 -04005820 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005821 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5822 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005823 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005824 if (nr.isListen()) continue;
Chalard Jean08577fc2018-05-02 21:14:54 +09005825 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005826 }
5827 }
5828
Chalard Jean08577fc2018-05-02 21:14:54 +09005829 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5830 int score = 0;
5831 int serial = 0;
5832 if (nai != null) {
5833 score = nai.getCurrentScore();
5834 serial = nai.factorySerialNumber;
5835 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005836 if (VDBG || DDBG){
5837 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5838 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005839 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005840 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5841 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005842 }
5843 }
5844
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005845 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5846 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005847 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005848 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005849 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5850 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005851 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005852 sendIntent(nri.mPendingIntent, intent);
5853 }
5854 // else not handled
5855 }
5856
5857 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5858 mPendingIntentWakeLock.acquire();
5859 try {
5860 if (DBG) log("Sending " + pendingIntent);
5861 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5862 } catch (PendingIntent.CanceledException e) {
5863 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5864 mPendingIntentWakeLock.release();
5865 releasePendingNetworkRequest(pendingIntent);
5866 }
5867 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5868 }
5869
5870 @Override
5871 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5872 String resultData, Bundle resultExtras) {
5873 if (DBG) log("Finished sending " + pendingIntent);
5874 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005875 // Release with a delay so the receiving client has an opportunity to put in its
5876 // own request.
5877 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005878 }
5879
Chalard Jeanf19db372018-01-26 19:24:40 +09005880 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005881 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005882 if (nri.messenger == null) {
5883 return; // Default request has no msgr
5884 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005885 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005886 // TODO: check if defensive copies of data is needed.
5887 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005888 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005889 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5890 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005891 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005892 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005893 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005894 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5895 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005896 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005897 // For this notification, arg1 contains the blocked status.
5898 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005899 break;
5900 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005901 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005902 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005903 break;
5904 }
5905 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005906 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005907 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005908 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005909 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005910 break;
5911 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005912 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005913 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005914 break;
5915 }
junyulai05986c62018-08-07 19:50:45 +08005916 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005917 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005918 msg.arg1 = arg1;
5919 break;
5920 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005921 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005922 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005923 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005924 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005925 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005926 String notification = ConnectivityManager.getCallbackName(notificationType);
5927 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005928 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005929 nri.messenger.send(msg);
5930 } catch (RemoteException e) {
5931 // may occur naturally in the race of binder death.
5932 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5933 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005934 }
5935
Hugo Benichidba33db2017-03-23 22:40:44 +09005936 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5937 bundle.putParcelable(t.getClass().getSimpleName(), t);
5938 }
5939
Paul Jensenc8b9a742014-09-30 15:37:41 -04005940 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005941 if (nai.numRequestNetworkRequests() != 0) {
5942 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5943 NetworkRequest nr = nai.requestAt(i);
5944 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005945 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005946 loge("Dead network still had at least " + nr);
5947 break;
5948 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005949 }
5950 nai.asyncChannel.disconnect();
5951 }
5952
Robert Greenwalt7b816022014-04-18 15:25:25 -07005953 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5954 if (oldNetwork == null) {
5955 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5956 return;
5957 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005958 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005959
5960 // If we get here it means that the last linger timeout for this network expired. So there
5961 // must be no other active linger timers, and we must stop lingering.
5962 oldNetwork.clearLingerState();
5963
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005964 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005965 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005966 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005967 } else {
5968 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005969 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5970 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005971 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005972 }
5973
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005974 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005975 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005976
Paul Jensen27b02b72014-07-14 12:03:33 -04005977 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005978 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005979 } catch (Exception e) {
5980 loge("Exception setting default network :" + e);
5981 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005982
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005983 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005984 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005985 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005986 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005987 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005988 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5989 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005990 }
5991
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005992 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005993 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5994 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5995 NetworkRequest nr = nri.request;
5996 if (!nr.isListen()) continue;
5997 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5998 nai.removeRequest(nri.request.requestId);
5999 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
6000 }
6001 }
6002
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006003 if (capabilitiesChanged) {
6004 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
6005 }
6006
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006007 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6008 NetworkRequest nr = nri.request;
6009 if (!nr.isListen()) continue;
6010 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
6011 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006012 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006013 }
6014 }
6015 }
6016
Paul Jensen2161a8e2014-09-11 11:00:39 -04006017 // Handles a network appearing or improving its score.
6018 //
6019 // - Evaluates all current NetworkRequests that can be
6020 // satisfied by newNetwork, and reassigns to newNetwork
6021 // any such requests for which newNetwork is the best.
6022 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006023 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006024 // needed. A network is needed if it is the best network for
6025 // one or more NetworkRequests, or if it is a VPN.
6026 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006027 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006028 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006029 //
6030 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6031 // networks that have no chance (i.e. even if validated)
6032 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006033 //
6034 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6035 // it does not remove NetworkRequests that other Networks could better satisfy.
6036 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6037 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6038 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006039 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006040 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006041 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6042 // performed to tear down unvalidated networks that have no chance (i.e. even if
6043 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006044 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006045 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006046 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006047 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006048 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006049 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006050
6051 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6052 final int score = newNetwork.getCurrentScore();
6053
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006054 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006055
Paul Jensen2161a8e2014-09-11 11:00:39 -04006056 // Find and migrate to this Network any NetworkRequests for
6057 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006058 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6059 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006060 NetworkCapabilities nc = newNetwork.networkCapabilities;
6061 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006062 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006063 // Process requests in the first pass and listens in the second pass. This allows us to
6064 // change a network's capabilities depending on which requests it has. This is only
6065 // correct if the change in capabilities doesn't affect whether the network satisfies
6066 // requests or not, and doesn't affect the network's score.
6067 if (nri.request.isListen()) continue;
6068
Hugo Benichicd952782017-09-20 11:20:14 +09006069 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006070 final boolean satisfies = newNetwork.satisfies(nri.request);
6071 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006072 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006073 log("Network " + newNetwork.name() + " was already satisfying" +
6074 " request " + nri.request.requestId + ". No change.");
6075 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006076 keep = true;
6077 continue;
6078 }
6079
6080 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006081 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006082 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006083 // next check if it's better than any current network we're using for
6084 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006085 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006086 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006087 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006088 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006089 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006090 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006091 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006092 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006093 if (VDBG || DDBG){
6094 log(" accepting network in place of " + currentNetwork.name());
6095 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006096 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006097 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006098 affectedNetworks.add(currentNetwork);
6099 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006100 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006101 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006102 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006103 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006104 if (!newNetwork.addRequest(nri.request)) {
6105 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6106 }
6107 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006108 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006109 // Tell NetworkFactories about the new score, so they can stop
6110 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006111 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006112 // network. Think about if there is a way to reduce this. Push
6113 // netid->request mapping to each factory?
Chalard Jean08577fc2018-05-02 21:14:54 +09006114 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006115 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006116 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006117 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006118 if (currentNetwork != null) {
6119 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6120 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006121 }
6122 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006123 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006124 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6125 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006126 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006127 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6128 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6129 // This means this code doesn't have to handle the case where "currentNetwork" no
6130 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6131 if (DBG) {
6132 log("Network " + newNetwork.name() + " stopped satisfying" +
6133 " request " + nri.request.requestId);
6134 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006135 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006136 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006137 clearNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09006138 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006139 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006140 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6141 newNetwork.name() +
6142 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006143 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006144 // TODO: Technically, sending CALLBACK_LOST here is
6145 // incorrect if there is a replacement network currently
6146 // connected that can satisfy nri, which is a request
6147 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006148 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6149 // so this code is only incorrect for a network that loses
6150 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006151 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006152 }
6153 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006154 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006155 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006156 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006157 makeDefault(newNetwork);
6158 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006159 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006160 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006161 // Have a new default network, release the transition wakelock in
6162 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006163 }
6164
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006165 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6166 Slog.wtf(TAG, String.format(
6167 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006168 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006169 }
6170 if (newNetwork.getCurrentScore() != score) {
6171 Slog.wtf(TAG, String.format(
6172 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006173 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006174 }
6175
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006176 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006177 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6178 // If the network went from background to foreground or vice versa, we need to update
6179 // its foreground state. It is safe to do this after rematching the requests because
6180 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6181 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006182 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006183 } else {
6184 processListenRequests(newNetwork, false);
6185 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006186
Paul Jensencf4c2c62015-07-01 14:16:32 -04006187 // do this after the default net is switched, but
6188 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006189 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006190
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006191 // Linger any networks that are no longer needed. This should be done after sending the
6192 // available callback for newNetwork.
6193 for (NetworkAgentInfo nai : affectedNetworks) {
6194 updateLingerState(nai, now);
6195 }
6196 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6197 // does not need to be done in any particular order.
6198 updateLingerState(newNetwork, now);
6199
Paul Jensencf4c2c62015-07-01 14:16:32 -04006200 if (isNewDefault) {
6201 // Maintain the illusion: since the legacy API only
6202 // understands one network at a time, we must pretend
6203 // that the current default network disconnected before
6204 // the new one connected.
6205 if (oldDefaultNetwork != null) {
6206 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6207 oldDefaultNetwork, true);
6208 }
6209 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6210 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6211 notifyLockdownVpn(newNetwork);
6212 }
6213
Robert Greenwalt7b816022014-04-18 15:25:25 -07006214 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006215 // Notify battery stats service about this network, both the normal
6216 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006217 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006218 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006219 final IBatteryStats bs = BatteryStatsService.getService();
6220 final int type = newNetwork.networkInfo.getType();
6221
6222 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6223 bs.noteNetworkInterfaceType(baseIface, type);
6224 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6225 final String stackedIface = stacked.getInterfaceName();
6226 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006227 }
6228 } catch (RemoteException ignored) {
6229 }
6230
Robert Greenwalt152ed372014-12-17 17:19:53 -08006231 // This has to happen after the notifyNetworkCallbacks as that tickles each
6232 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006233 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006234 // and will generally do a dns request so they can ensureRouteToHost and if
6235 // they do that before the callbacks happen they'll use the default network.
6236 //
6237 // TODO: Is there still a race here? We send the broadcast
6238 // after sending the callback, but if the app can receive the
6239 // broadcast before the callback, it might still break.
6240 //
6241 // This *does* introduce a race where if the user uses the new api
6242 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6243 // they may get old info. Reverse this after the old startUsing api is removed.
6244 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006245 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6246 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006247 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006248 // legacy type tracker filters out repeat adds
6249 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6250 }
6251 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006252
6253 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6254 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6255 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6256 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6257 if (newNetwork.isVPN()) {
6258 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6259 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006260 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006261 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6262 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006263 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006264 if (nai.getLingerExpiry() > 0) {
6265 // This network has active linger timers and no requests, but is not
6266 // lingering. Linger it.
6267 //
6268 // One way (the only way?) this can happen if this network is unvalidated
6269 // and became unneeded due to another network improving its score to the
6270 // point where this network will no longer be able to satisfy any requests
6271 // even if it validates.
6272 updateLingerState(nai, now);
6273 } else {
6274 if (DBG) log("Reaping " + nai.name());
6275 teardownUnneededNetwork(nai);
6276 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006277 }
6278 }
6279 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006280 }
6281
Paul Jensen1c7ba022015-06-16 14:27:36 -04006282 /**
6283 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6284 * being disconnected.
6285 * @param changed If only one Network's score or capabilities have been modified since the last
6286 * time this function was called, pass this Network in this argument, otherwise pass
6287 * null.
6288 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6289 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6290 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6291 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6292 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006293 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006294 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006295 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6296 // to avoid the slowness. It is not simply enough to process just "changed", for
6297 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006298 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006299
6300 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6301 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6302 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006303 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006304 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006305 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006306 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006307 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6308 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6309 // Rematch higher scoring networks first to prevent requests first matching a lower
6310 // scoring network and then a higher scoring network, which could produce multiple
6311 // callbacks and inadvertently unlinger networks.
6312 Arrays.sort(nais);
6313 for (NetworkAgentInfo nai : nais) {
6314 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006315 // Only reap the last time through the loop. Reaping before all rematching
6316 // is complete could incorrectly teardown a network that hasn't yet been
6317 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006318 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006319 : ReapUnvalidatedNetworks.REAP,
6320 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006321 }
6322 }
6323 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006324
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006325 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006326 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006327 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006328 // For now only update icons for default connection.
6329 // TODO: Update WiFi and cellular icons separately. b/17237507
6330 if (!isDefaultNetwork(nai)) return;
6331
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006332 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006333 // Don't repeat publish.
6334 if (newInetCondition == mDefaultInetConditionPublished) return;
6335
6336 mDefaultInetConditionPublished = newInetCondition;
6337 sendInetConditionBroadcast(nai.networkInfo);
6338 }
6339
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006340 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006341 synchronized (mVpns) {
6342 if (mLockdownTracker != null) {
6343 if (nai != null && nai.isVPN()) {
6344 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6345 } else {
6346 mLockdownTracker.onNetworkInfoChanged();
6347 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006348 }
6349 }
6350 }
6351
Robert Greenwalt7b816022014-04-18 15:25:25 -07006352 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006353 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006354 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006355 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006356 synchronized (networkAgent) {
6357 oldInfo = networkAgent.networkInfo;
6358 networkAgent.networkInfo = newInfo;
6359 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006360 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006361
Robert Greenwalt7b816022014-04-18 15:25:25 -07006362 if (DBG) {
6363 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6364 (oldInfo == null ? "null" : oldInfo.getState()) +
6365 " to " + state);
6366 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006367
Robin Lee585e2482016-05-01 23:00:00 +01006368 if (!networkAgent.created
6369 && (state == NetworkInfo.State.CONNECTED
6370 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006371
6372 // A network that has just connected has zero requests and is thus a foreground network.
6373 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6374
Robert Greenwalt7b816022014-04-18 15:25:25 -07006375 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006376 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006377 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006378 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006379 (networkAgent.networkMisc == null ||
6380 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006381 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006382 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006383 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006385 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006386 loge("Error creating network " + networkAgent.network.netId + ": "
6387 + e.getMessage());
6388 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006389 }
Paul Jenseneec75412014-08-04 12:21:19 -04006390 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006391 }
6392
6393 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6394 networkAgent.everConnected = true;
6395
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006396 if (networkAgent.linkProperties == null) {
6397 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6398 }
6399
lucaslin8175ac992019-04-03 17:09:28 +08006400 // NetworkCapabilities need to be set before sending the private DNS config to
6401 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
6402 synchronized (networkAgent) {
6403 networkAgent.setNetworkCapabilities(networkAgent.networkCapabilities);
6404 }
Erik Kline736353a2018-03-21 07:18:33 -07006405 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006406 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6407 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006408
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006409 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6410 // command must be sent after updating LinkProperties to maximize chances of
6411 // NetworkMonitor seeing the correct LinkProperties when starting.
6412 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6413 try {
lucaslin43338992019-03-20 18:21:59 +08006414 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6415 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6416 }
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09006417 networkAgent.networkMonitor().notifyNetworkConnected(
6418 networkAgent.linkProperties, networkAgent.networkCapabilities);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006419 } catch (RemoteException e) {
6420 e.rethrowFromSystemServer();
6421 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006422 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006423
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006424 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6425 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6426 // capabilities, so it only needs to be done once on initial connect, not every time the
6427 // network's capabilities change. Note that we do this before rematching the network,
6428 // so we could decide to tear it down immediately afterwards. That's fine though - on
6429 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6430 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006431 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006432
Varun Anand4fa80e82019-02-06 10:13:38 -08006433 if (networkAgent.isVPN()) {
6434 updateAllVpnsCapabilities();
6435 }
6436
Paul Jensen2161a8e2014-09-11 11:00:39 -04006437 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006438 final long now = SystemClock.elapsedRealtime();
6439 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006440
6441 // This has to happen after matching the requests, because callbacks are just requests.
6442 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006443 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006444 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006445 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006446 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006447 }
Chalard Jean392971c2018-05-11 20:19:20 +09006448 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006449 if (networkAgent.isVPN()) {
6450 // As the active or bound network changes for apps, broadcast the default proxy, as
6451 // apps may need to update their proxy data. This is called after disconnecting from
6452 // VPN to make sure we do not broadcast the old proxy data.
6453 // TODO(b/122649188): send the broadcast only to VPN users.
6454 mProxyTracker.sendProxyBroadcast();
6455 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006456 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6457 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006458 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006459 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006460 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006461 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006462 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6463 networkAgent.networkCapabilities);
6464 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6465 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006466 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6467 ConnectivityManager.CALLBACK_SUSPENDED :
6468 ConnectivityManager.CALLBACK_RESUMED));
6469 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006470 }
6471 }
6472
Robert Greenwaltac96c522014-06-03 16:43:57 -07006473 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006474 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006475 if (score < 0) {
6476 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6477 "). Bumping score to min of 0");
6478 score = 0;
6479 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006480
Paul Jensen2161a8e2014-09-11 11:00:39 -04006481 final int oldScore = nai.getCurrentScore();
6482 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006483
Paul Jensen85cf78e2015-06-25 13:25:07 -04006484 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006485
Paul Jensenc8b9a742014-09-30 15:37:41 -04006486 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006487 }
6488
Erik Klinec75d4fa2017-02-15 19:59:17 +09006489 // Notify only this one new request of the current state. Transfer all the
6490 // current state by calling NetworkCapabilities and LinkProperties callbacks
6491 // so that callers can be guaranteed to have as close to atomicity in state
6492 // transfer as can be supported by this current API.
6493 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006494 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006495 if (nri.mPendingIntent != null) {
6496 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6497 // Attempt no subsequent state pushes where intents are involved.
6498 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006499 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006500
junyulai05986c62018-08-07 19:50:45 +08006501 final boolean metered = nai.networkCapabilities.isMetered();
6502 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6503 metered, mRestrictBackground);
6504 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6505 }
6506
6507 /**
6508 * Notify of the blocked state apps with a registered callback matching a given NAI.
6509 *
6510 * Unlike other callbacks, blocked status is different between each individual uid. So for
6511 * any given nai, all requests need to be considered according to the uid who filed it.
6512 *
6513 * @param nai The target NetworkAgentInfo.
6514 * @param oldMetered True if the previous network capabilities is metered.
6515 * @param newRestrictBackground True if data saver is enabled.
6516 */
6517 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6518 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6519
6520 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6521 NetworkRequest nr = nai.requestAt(i);
6522 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6523 final int uidRules = mUidRules.get(nri.mUid);
6524 final boolean oldBlocked, newBlocked;
6525 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6526 // between these two calls.
6527 synchronized (mVpns) {
6528 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6529 oldRestrictBackground);
6530 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6531 newRestrictBackground);
6532 }
6533 if (oldBlocked != newBlocked) {
6534 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6535 encodeBool(newBlocked));
6536 }
6537 }
6538 }
6539
6540 /**
6541 * Notify apps with a given UID of the new blocked state according to new uid rules.
6542 * @param uid The uid for which the rules changed.
6543 * @param newRules The new rules to apply.
6544 */
6545 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6546 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6547 final boolean metered = nai.networkCapabilities.isMetered();
6548 final boolean oldBlocked, newBlocked;
6549 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6550 // rules changed event. And this function actually loop through all connected nai and
6551 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6552 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6553 synchronized (mVpns) {
6554 oldBlocked = isUidNetworkingWithVpnBlocked(
6555 uid, mUidRules.get(uid), metered, mRestrictBackground);
6556 newBlocked = isUidNetworkingWithVpnBlocked(
6557 uid, newRules, metered, mRestrictBackground);
6558 }
6559 if (oldBlocked == newBlocked) {
Junyu Laic685f502019-04-09 08:59:00 -07006560 continue;
junyulai05986c62018-08-07 19:50:45 +08006561 }
6562 final int arg = encodeBool(newBlocked);
6563 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6564 NetworkRequest nr = nai.requestAt(i);
6565 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6566 if (nri != null && nri.mUid == uid) {
6567 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6568 }
6569 }
6570 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006571 }
6572
Chalard Jeanff46a252019-04-10 23:07:55 +09006573 @VisibleForTesting
6574 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006575 // The NetworkInfo we actually send out has no bearing on the real
6576 // state of affairs. For example, if the default connection is mobile,
6577 // and a request for HIPRI has just gone away, we need to pretend that
6578 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6579 // the state to DISCONNECTED, even though the network is of type MOBILE
6580 // and is still connected.
6581 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6582 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006583 if (state != DetailedState.DISCONNECTED) {
6584 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006585 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006586 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006587 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006588 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6589 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6590 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6591 if (info.isFailover()) {
6592 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6593 nai.networkInfo.setFailover(false);
6594 }
6595 if (info.getReason() != null) {
6596 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6597 }
6598 if (info.getExtraInfo() != null) {
6599 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6600 }
6601 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006602 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006603 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006604 if (newDefaultAgent != null) {
6605 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6606 newDefaultAgent.networkInfo);
6607 } else {
6608 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6609 }
6610 }
6611 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6612 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006613 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006614 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006615 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006616 }
6617 }
6618 }
6619
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006620 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006621 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006622 String notification = ConnectivityManager.getCallbackName(notifyType);
6623 log("notifyType " + notification + " for " + networkAgent.name());
6624 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006625 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6626 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006627 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6628 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006629 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6630 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006631 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006632 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006633 } else {
6634 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6635 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006636 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006637 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006638
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006639 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6640 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6641 }
6642
Jeff Sharkey69736342014-12-08 14:50:12 -08006643 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006644 * Returns the list of all interfaces that could be used by network traffic that does not
6645 * explicitly specify a network. This includes the default network, but also all VPNs that are
6646 * currently connected.
6647 *
6648 * Must be called on the handler thread.
6649 */
6650 private Network[] getDefaultNetworks() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006651 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006652 ArrayList<Network> defaultNetworks = new ArrayList<>();
6653 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6654 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6655 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6656 defaultNetworks.add(nai.network);
6657 }
6658 }
6659 return defaultNetworks.toArray(new Network[0]);
6660 }
6661
6662 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006663 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6664 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006665 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006666 private void notifyIfacesChangedForNetworkStats() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006667 ensureRunningOnConnectivityServiceThread();
6668 String activeIface = null;
6669 LinkProperties activeLinkProperties = getActiveLinkProperties();
6670 if (activeLinkProperties != null) {
6671 activeIface = activeLinkProperties.getInterfaceName();
6672 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006673 try {
Varun Anand02c50ef2019-02-07 14:13:13 -08006674 mStatsService.forceUpdateIfaces(
6675 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006676 } catch (Exception ignored) {
6677 }
6678 }
6679
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006680 @Override
6681 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006682 int user = UserHandle.getUserId(Binder.getCallingUid());
6683 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006684 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006685 return mVpns.get(user).addAddress(address, prefixLength);
6686 }
6687 }
6688
6689 @Override
6690 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006691 int user = UserHandle.getUserId(Binder.getCallingUid());
6692 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006693 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006694 return mVpns.get(user).removeAddress(address, prefixLength);
6695 }
6696 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006697
6698 @Override
6699 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006700 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006701 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006702 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006703 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006704 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006705 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006706 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006707 mHandler.post(() -> {
6708 // Update VPN's capabilities based on updated underlying network set.
6709 updateAllVpnsCapabilities();
6710 notifyIfacesChangedForNetworkStats();
6711 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006712 }
6713 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006714 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006715
6716 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006717 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006718 enforceConnectivityInternalPermission();
Remi NGUYEN VAN9ca4c622019-04-09 02:04:54 -07006719 String settingUrl = mContext.getResources().getString(
6720 R.string.config_networkCaptivePortalServerUrl);
6721
6722 if (!TextUtils.isEmpty(settingUrl)) {
6723 return settingUrl;
6724 }
6725
6726 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
6727 Settings.Global.CAPTIVE_PORTAL_HTTP_URL);
6728 if (!TextUtils.isEmpty(settingUrl)) {
6729 return settingUrl;
6730 }
6731
6732 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainib7c24872016-01-04 12:16:14 -08006733 }
6734
6735 @Override
junyulai7c469172019-01-16 20:23:34 +08006736 public void startNattKeepalive(Network network, int intervalSeconds,
6737 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006738 enforceKeepalivePermission();
6739 mKeepaliveTracker.startNattKeepalive(
junyulai0c666972019-03-04 22:45:36 +08006740 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai7c469172019-01-16 20:23:34 +08006741 intervalSeconds, cb,
junyulaie4135282019-01-03 18:50:15 +08006742 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006743 }
6744
6745 @Override
junyulai215b8772019-01-15 11:32:44 +08006746 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006747 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006748 String dstAddr) {
junyulai215b8772019-01-15 11:32:44 +08006749 mKeepaliveTracker.startNattKeepalive(
6750 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006751 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006752 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6753 }
6754
6755 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006756 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006757 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006758 enforceKeepalivePermission();
6759 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006760 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006761 }
6762
6763 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006764 public void stopKeepalive(Network network, int slot) {
6765 mHandler.sendMessage(mHandler.obtainMessage(
junyulaie4135282019-01-03 18:50:15 +08006766 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006767 }
6768
6769 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006770 public void factoryReset() {
6771 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006772
6773 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6774 return;
6775 }
6776
Robin Lee3b3dd942015-05-12 18:14:58 +01006777 final int userId = UserHandle.getCallingUserId();
6778
Stuart Scottf1fb3972015-04-02 18:00:02 -07006779 // Turn airplane mode off
6780 setAirplaneMode(false);
6781
Stuart Scotte3e314d2015-04-20 14:07:45 -07006782 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6783 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006784 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006785 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006786 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006787 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006788 }
6789
Stuart Scotte3e314d2015-04-20 14:07:45 -07006790 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006791 // Remove always-on package
6792 synchronized (mVpns) {
6793 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6794 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006795 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006796 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6797 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006798
Hugo Benichi69744342017-11-27 10:57:16 +09006799 // Turn Always-on VPN off
6800 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6801 final long ident = Binder.clearCallingIdentity();
6802 try {
6803 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6804 mLockdownEnabled = false;
6805 setLockdownTracker(null);
6806 } finally {
6807 Binder.restoreCallingIdentity(ident);
6808 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006809 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006810
Hugo Benichi69744342017-11-27 10:57:16 +09006811 // Turn VPN off
6812 VpnConfig vpnConfig = getVpnConfig(userId);
6813 if (vpnConfig != null) {
6814 if (vpnConfig.legacy) {
6815 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6816 } else {
6817 // Prevent this app (packagename = vpnConfig.user) from initiating
6818 // VPN connections in the future without user intervention.
6819 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006820
Hugo Benichi69744342017-11-27 10:57:16 +09006821 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6822 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006823 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006824 }
6825 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006826
6827 Settings.Global.putString(mContext.getContentResolver(),
6828 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006829 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006830
Ricky Wai44dcbde2018-01-23 04:09:45 +00006831 @Override
6832 public byte[] getNetworkWatchlistConfigHash() {
6833 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6834 if (nwm == null) {
6835 loge("Unable to get NetworkWatchlistManager");
6836 return null;
6837 }
6838 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6839 return nwm.getWatchlistConfigHash();
6840 }
6841
Paul Jensencf4c2c62015-07-01 14:16:32 -04006842 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006843 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6844 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006845 }
6846
6847 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006848 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6849 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6850 }
6851
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006852 @VisibleForTesting
6853 public boolean hasService(String name) {
6854 return ServiceManager.checkService(name) != null;
6855 }
6856
Hugo Benichi64901e52017-10-19 14:42:40 +09006857 @VisibleForTesting
6858 protected IpConnectivityMetrics.Logger metricsLogger() {
6859 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6860 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006861 }
6862
6863 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006864 int[] transports = nai.networkCapabilities.getTransportTypes();
6865 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006866 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006867
6868 private static boolean toBool(int encodedBoolean) {
6869 return encodedBoolean != 0; // Only 0 means false.
6870 }
6871
6872 private static int encodeBool(boolean b) {
6873 return b ? 1 : 0;
6874 }
mswest46386886f2018-03-12 10:34:34 -07006875
6876 @Override
6877 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6878 FileDescriptor err, String[] args, ShellCallback callback,
6879 ResultReceiver resultReceiver) {
6880 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6881 }
6882
6883 private class ShellCmd extends ShellCommand {
6884
6885 @Override
6886 public int onCommand(String cmd) {
6887 if (cmd == null) {
6888 return handleDefaultCommands(cmd);
6889 }
6890 final PrintWriter pw = getOutPrintWriter();
6891 try {
6892 switch (cmd) {
6893 case "airplane-mode":
6894 final String action = getNextArg();
6895 if ("enable".equals(action)) {
6896 setAirplaneMode(true);
6897 return 0;
6898 } else if ("disable".equals(action)) {
6899 setAirplaneMode(false);
6900 return 0;
6901 } else if (action == null) {
6902 final ContentResolver cr = mContext.getContentResolver();
6903 final int enabled = Settings.Global.getInt(cr,
6904 Settings.Global.AIRPLANE_MODE_ON);
6905 pw.println(enabled == 0 ? "disabled" : "enabled");
6906 return 0;
6907 } else {
6908 onHelp();
6909 return -1;
6910 }
6911 default:
6912 return handleDefaultCommands(cmd);
6913 }
6914 } catch (Exception e) {
6915 pw.println(e);
6916 }
6917 return -1;
6918 }
6919
6920 @Override
6921 public void onHelp() {
6922 PrintWriter pw = getOutPrintWriter();
6923 pw.println("Connectivity service commands:");
6924 pw.println(" help");
6925 pw.println(" Print this help text.");
6926 pw.println(" airplane-mode [enable|disable]");
6927 pw.println(" Turn airplane mode on or off.");
6928 pw.println(" airplane-mode");
6929 pw.println(" Get airplane mode.");
6930 }
6931 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006932
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006933 @GuardedBy("mVpns")
6934 private Vpn getVpnIfOwner() {
6935 final int uid = Binder.getCallingUid();
6936 final int user = UserHandle.getUserId(uid);
6937
6938 final Vpn vpn = mVpns.get(user);
6939 if (vpn == null) {
6940 return null;
6941 } else {
6942 final VpnInfo info = vpn.getVpnInfo();
6943 return (info == null || info.ownerUid != uid) ? null : vpn;
6944 }
6945 }
6946
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006947 /**
6948 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6949 * for testing.
6950 */
6951 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6952 if (checkNetworkStackPermission()) {
6953 return null;
6954 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006955 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006956 Vpn vpn = getVpnIfOwner();
6957 if (vpn != null) {
6958 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006959 }
6960 }
6961 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6962 + "permission");
6963 }
6964
6965 /**
6966 * @param connectionInfo the connection to resolve.
6967 * @return {@code uid} if the connection is found and the app has permission to observe it
6968 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6969 * connection is not found.
6970 */
6971 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6972 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6973 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6974 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6975 }
6976
6977 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6978 connectionInfo.local, connectionInfo.remote);
6979
6980 /* Filter out Uids not associated with the VPN. */
6981 if (vpn != null && !vpn.appliesToUid(uid)) {
6982 return INVALID_UID;
6983 }
6984
6985 return uid;
6986 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006987
6988 @Override
6989 public boolean isCallerCurrentAlwaysOnVpnApp() {
6990 synchronized (mVpns) {
6991 Vpn vpn = getVpnIfOwner();
6992 return vpn != null && vpn.getAlwaysOn();
6993 }
6994 }
6995
6996 @Override
6997 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6998 synchronized (mVpns) {
6999 Vpn vpn = getVpnIfOwner();
7000 return vpn != null && vpn.getLockdown();
7001 }
7002 }
Benedict Wong99a48412018-11-09 14:45:34 -08007003
7004 /**
7005 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
7006 *
7007 * <p>The TestNetworkService must be run in the system server due to TUN creation.
7008 */
7009 @Override
7010 public IBinder startOrGetTestNetworkService() {
7011 synchronized (mTNSLock) {
7012 TestNetworkService.enforceTestNetworkPermissions(mContext);
7013
7014 if (mTNS == null) {
7015 mTNS = new TestNetworkService(mContext, mNMS);
7016 }
7017
7018 return mTNS;
7019 }
7020 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07007021}