blob: 1cb2c4a2f5eea6dd5f82ccc93c565d16b271c708 [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;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040029import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060038import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080039import static android.net.NetworkPolicyManager.RULE_NONE;
40import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090041import static android.net.NetworkStack.NETWORKSTACK_PACKAGE_NAME;
42import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090043import static android.net.shared.NetworkParcelableUtil.toStableParcelable;
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
Wenchao Tongf5ea3402015-03-04 13:26:38 -080050import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080051import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090052import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070053import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070054import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.ContentResolver;
56import android.content.Context;
57import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070058import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070059import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070060import android.database.ContentObserver;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070061import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.ConnectivityManager;
63import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050064import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080065import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050066import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070067import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090068import android.net.INetworkMonitor;
69import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070070import android.net.INetworkPolicyListener;
71import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070072import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080073import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070074import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010075import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080076import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070077import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070078import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070079import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070080import android.net.NetworkConfig;
Chalard Jean08577fc2018-05-02 21:14:54 +090081import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070083import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070084import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090085import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070086import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070087import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070088import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090089import android.net.NetworkStack;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070090import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070091import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000092import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090093import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -040094import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070095import android.net.RouteInfo;
junyulaie4135282019-01-03 18:50:15 +080096import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040097import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040098import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060099import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900100import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900101import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700102import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900103import android.net.shared.NetworkMonitorUtils;
104import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900105import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900106import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800108import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700109import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700111import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700112import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700113import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.Looper;
115import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700116import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900118import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700119import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700120import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700121import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800122import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900123import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900124import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700125import android.os.ShellCallback;
126import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900127import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700128import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400129import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700131import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700132import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700133import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700134import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900135import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700136import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600137import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900138import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800139import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700140import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500141import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700142import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700143import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Wink Savilleab9321d2013-06-29 21:10:57 -0700145import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400146import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400147import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700148import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANd4a9de202019-01-30 22:01:20 +0900149import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700150import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700151import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800152import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700153import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900154import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700155import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600156import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700157import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900158import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900159import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700160import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700161import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400162import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900163import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500164import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900165import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900166import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100167import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700168import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900169import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700170import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600171import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900172import com.android.server.connectivity.NetworkNotificationManager;
173import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700174import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900175import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800176import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700177import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100178import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500179import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700180import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700181import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900182import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700183import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600184
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700185import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700186
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700187import org.xmlpull.v1.XmlPullParser;
188import org.xmlpull.v1.XmlPullParserException;
189
190import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700192import java.io.FileNotFoundException;
193import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700194import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700196import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700197import java.net.InetAddress;
198import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700199import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700200import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700201import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900202import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800203import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700204import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700205import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700206import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700207import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700208import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900209import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600210import java.util.SortedSet;
211import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
213/**
214 * @hide
215 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800216public class ConnectivityService extends IConnectivityManager.Stub
217 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900218 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Chalard Jean4133a122018-06-04 13:33:12 +0900220 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900221 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900222 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900223 private static final String NETWORK_ARG = "networks";
224 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900225
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900226 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900227 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
228 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900230 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700231
Jeff Sharkey899223b2012-08-04 15:24:58 -0700232 // TODO: create better separation between radio types and network types
233
Robert Greenwalt42acef32009-08-12 16:08:25 -0700234 // how long to wait before switching back to a radio's default network
235 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
236 // system property that can override the above value
237 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
238 "android.telephony.apn-restore";
239
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900240 // How long to wait before putting up a "This network doesn't have an Internet connection,
241 // connect anyway?" dialog after the user selects a network that doesn't validate.
242 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
243
lucaslind2e045e02019-01-24 15:55:30 +0800244 // How long to dismiss network notification.
245 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
246
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900247 // Default to 30s linger time-out. Modifiable only for testing.
248 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
249 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
250 @VisibleForTesting
251 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
252
Jeremy Joslin79294842014-12-03 17:15:28 -0800253 // How long to delay to removal of a pending intent based request.
254 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
255 private final int mReleasePendingIntentDelayMs;
256
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900257 private MockableSystemProperties mSystemProperties;
258
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800259 private Tethering mTethering;
260
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700261 private final PermissionMonitor mPermissionMonitor;
262
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700263 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700264
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900265 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700266 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900267 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700268
Hugo Benichi69744342017-11-27 10:57:16 +0900269 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
270 // a direct call to LockdownVpnTracker.isEnabled().
271 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700272 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900273 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700274 private LockdownVpnTracker mLockdownTracker;
275
junyulai05986c62018-08-07 19:50:45 +0800276 /**
277 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
278 * handler thread, they don't need a lock.
279 */
280 private SparseIntArray mUidRules = new SparseIntArray();
281 /** Flag indicating if background data is restricted. */
282 private boolean mRestrictBackground;
283
Erik Klineda4bfa82015-04-30 12:58:40 +0900284 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700285 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700286 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287
Luke Huang4e25ec62018-09-27 16:58:23 +0800288 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800289 @VisibleForTesting
290 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800291 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700292 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900293 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700294
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700295 private String mCurrentTcpBufferSizes;
296
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900297 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900298 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
299 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900300
Paul Jensenb10e37f2014-11-25 12:33:08 -0500301 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400302 // Tear down networks that have no chance (e.g. even if validated) of becoming
303 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500304 // all networks have been rematched against all NetworkRequests.
305 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400306 // Don't reap networks. This should be passed when some networks have not yet been
307 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500308 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900309 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500310
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900311 private enum UnneededFor {
312 LINGER, // Determine whether this network is unneeded and should be lingered.
313 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
314 }
315
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700316 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700317 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700318 * from one net to another. Clear happens when we get a new
319 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
320 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700321 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700322 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700323
Robert Greenwalt434203a2010-10-11 16:00:27 -0700324 /**
325 * used internally to reload global proxy settings
326 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700327 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700328
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700329 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400330 * PAC manager has received new port.
331 */
332 private static final int EVENT_PROXY_HAS_CHANGED = 16;
333
Robert Greenwalte049c232014-04-11 15:53:27 -0700334 /**
335 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700336 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700337 */
338 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
339
Robert Greenwalt7b816022014-04-18 15:25:25 -0700340 /**
341 * used internally when registering NetworkAgents
342 * obj = Messenger
343 */
344 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
345
Robert Greenwalt9258c642014-03-26 16:47:06 -0700346 /**
347 * used to add a network request
348 * includes a NetworkRequestInfo
349 */
350 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
351
352 /**
353 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900354 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700355 * cancel it.
356 * includes a NetworkRequestInfo
357 */
358 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
359
360 /**
361 * used to add a network listener - no request
362 * includes a NetworkRequestInfo
363 */
364 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
365
366 /**
367 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400368 * arg1 = UID of caller
369 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700370 */
371 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
372
Robert Greenwalta67be032014-05-16 15:49:14 -0700373 /**
374 * used internally when registering NetworkFactories
375 * obj = Messenger
376 */
377 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
378
Robert Greenwalt27711812014-06-25 16:45:57 -0700379 /**
380 * used internally to expire a wakelock when transitioning
381 * from one net to another. Expire happens when we fail to find
382 * a new network (typically after 1 minute) -
383 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
384 * a replacement network.
385 */
386 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
387
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700388 /**
389 * Used internally to indicate the system is ready.
390 */
391 private static final int EVENT_SYSTEM_READY = 25;
392
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800393 /**
394 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400395 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800396 */
397 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
398
399 /**
400 * used to remove a pending intent and its associated network request.
401 * arg1 = UID of caller
402 * obj = PendingIntent
403 */
404 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
405
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900406 /**
407 * used to specify whether a network should be used even if unvalidated.
408 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
409 * arg2 = whether to remember this choice in the future (1 or 0)
410 * obj = network
411 */
412 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
413
414 /**
415 * used to ask the user to confirm a connection to an unvalidated network.
416 * obj = network
417 */
418 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700419
Erik Klineda4bfa82015-04-30 12:58:40 +0900420 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700421 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900422 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700423 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900424
Paul Jensen694f2b82015-06-17 14:15:39 -0400425 /**
426 * used to add a network listener with a pending intent
427 * obj = NetworkRequestInfo
428 */
429 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
430
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900431 /**
432 * used to specify whether a network should not be penalized when it becomes unvalidated.
433 */
434 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
435
436 /**
437 * used to trigger revalidation of a network.
438 */
439 private static final int EVENT_REVALIDATE_NETWORK = 36;
440
Erik Klinea24d4592018-01-11 21:07:29 +0900441 // Handle changes in Private DNS settings.
442 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
443
dalyk7301aa42018-03-05 12:42:22 -0500444 // Handle private DNS validation status updates.
445 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
446
junyulai05986c62018-08-07 19:50:45 +0800447 /**
448 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
449 */
450 private static final int EVENT_UID_RULES_CHANGED = 39;
451
452 /**
453 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
454 */
455 private static final int EVENT_DATA_SAVER_CHANGED = 40;
456
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900457 /**
458 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
459 * been tested.
460 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
461 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
462 * arg2 = NetID.
463 */
464 public static final int EVENT_NETWORK_TESTED = 41;
465
466 /**
467 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
468 * config was resolved.
469 * obj = PrivateDnsConfig
470 * arg2 = netid
471 */
472 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
473
474 /**
475 * Request ConnectivityService display provisioning notification.
476 * arg1 = Whether to make the notification visible.
477 * arg2 = NetID.
478 * obj = Intent to be launched when notification selected by user, null if !arg1.
479 */
480 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
481
482 /**
lucaslind2e045e02019-01-24 15:55:30 +0800483 * This event can handle dismissing notification by given network id.
484 */
485 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
486
487 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900488 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
489 * should be shown.
490 */
491 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
492
493 /**
494 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
495 * should be hidden.
496 */
497 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
498
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900499 private static String eventName(int what) {
500 return sMagicDecoderRing.get(what, Integer.toString(what));
501 }
502
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900503 /** Handler thread used for both of the handlers below. */
504 @VisibleForTesting
505 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700506 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700507 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700508 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700509 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900510 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700511
Mike Lockwood0f79b542009-08-14 14:18:49 -0400512 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800513 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400514
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700515 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700516 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800517 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700518
Chalard Jean52c2aa72018-06-07 16:44:04 +0900519 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
520 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000521 @VisibleForTesting
522 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400523
Erik Klineda4bfa82015-04-30 12:58:40 +0900524 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700525
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400526 private UserManager mUserManager;
527
Chalard Jean4133a122018-06-04 13:33:12 +0900528 private NetworkConfig[] mNetConfigs;
529 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700530
Robert Greenwalt50393202011-06-21 17:26:14 -0700531 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900532 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700533
Chalard Jean4133a122018-06-04 13:33:12 +0900534 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400535
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900536 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900537 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900538 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900539
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700540 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800541 private static final int MIN_NET_ID = 100; // some reserved marks
542 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700543 private int mNextNetId = MIN_NET_ID;
544
Robert Greenwalt34524f02014-05-18 16:22:10 -0700545 // sequence number of NetworkRequests
546 private int mNextNetworkRequestId = 1;
547
Erik Kline7523eb32015-07-09 18:24:03 +0900548 // NetworkRequest activity String log entries.
549 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
550 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
551
Hugo Benichic2ae2872016-07-11 11:05:12 +0900552 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900553 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900554 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
555
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900556 private static final int MAX_WAKELOCK_LOGS = 20;
557 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900558 private int mTotalWakelockAcquisitions = 0;
559 private int mTotalWakelockReleases = 0;
560 private long mTotalWakelockDurationMs = 0;
561 private long mMaxWakelockDurationMs = 0;
562 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900563
Hugo Benichif9fdf872016-07-28 17:53:06 +0900564 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900565
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700566 @GuardedBy("mBandwidthRequests")
567 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
568
Erik Kline065ab6e2016-10-02 18:02:14 +0900569 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900570 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900571
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900572 @VisibleForTesting
573 final MultipathPolicyTracker mMultipathPolicyTracker;
574
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 /**
576 * Implements support for the legacy "one network per network type" model.
577 *
578 * We used to have a static array of NetworkStateTrackers, one for each
579 * network type, but that doesn't work any more now that we can have,
580 * for example, more that one wifi network. This class stores all the
581 * NetworkAgentInfo objects that support a given type, but the legacy
582 * API will only see the first one.
583 *
584 * It serves two main purposes:
585 *
586 * 1. Provide information about "the network for a given type" (since this
587 * API only supports one).
588 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
589 * the first network for a given type changes, or if the default network
590 * changes.
591 */
592 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900593
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900594 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900595 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900596
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 /**
598 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
599 * Each list holds references to all NetworkAgentInfos that are used to
600 * satisfy requests for that network type.
601 *
602 * This array is built out at startup such that an unsupported network
603 * doesn't get an ArrayList instance, making this a tristate:
604 * unsupported, supported but not active and active.
605 *
606 * The actual lists are populated when we scan the network types that
607 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 *
609 * Threading model:
610 * - addSupportedType() is only called in the constructor
611 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
612 * They are therefore not thread-safe with respect to each other.
613 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
614 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
615 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700616 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900617 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700618
619 public LegacyTypeTracker() {
620 mTypeLists = (ArrayList<NetworkAgentInfo>[])
621 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
622 }
623
624 public void addSupportedType(int type) {
625 if (mTypeLists[type] != null) {
626 throw new IllegalStateException(
627 "legacy list for type " + type + "already initialized");
628 }
Chalard Jean4133a122018-06-04 13:33:12 +0900629 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
631
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 public boolean isTypeSupported(int type) {
633 return isNetworkTypeValid(type) && mTypeLists[type] != null;
634 }
635
636 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900637 synchronized (mTypeLists) {
638 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
639 return mTypeLists[type].get(0);
640 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900642 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700643 }
644
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900646 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900647 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700648 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900649 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900650 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 }
652 }
653
654 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 public void add(int type, NetworkAgentInfo nai) {
656 if (!isTypeSupported(type)) {
657 return; // Invalid network type.
658 }
659 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
660
661 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
662 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700663 return;
664 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900665 synchronized (mTypeLists) {
666 list.add(nai);
667 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900668
669 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900670 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900671 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700672 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
673 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700674 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700675 }
676
Lorenzo Colittia793a672014-07-31 23:20:17 +0900677 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900678 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900679 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
680 if (list == null || list.isEmpty()) {
681 return;
682 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900683 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900684
Hugo Benichi78caa2582016-06-21 09:48:07 +0900685 synchronized (mTypeLists) {
686 if (!list.remove(nai)) {
687 return;
688 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900689 }
690
Robert Greenwalt8d482522015-06-24 13:23:42 -0700691 final DetailedState state = DetailedState.DISCONNECTED;
692
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900693 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700694 maybeLogBroadcast(nai, state, type, wasDefault);
695 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900696 }
697
698 if (!list.isEmpty() && wasFirstNetwork) {
699 if (DBG) log("Other network available for type " + type +
700 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900701 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700702 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
703 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900704 }
705 }
706
707 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900708 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
709 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700710 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900711 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700712 }
713 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700714
Robert Greenwalt8d482522015-06-24 13:23:42 -0700715 // send out another legacy broadcast - currently only used for suspend/unsuspend
716 // toggle
717 public void update(NetworkAgentInfo nai) {
718 final boolean isDefault = isDefaultNetwork(nai);
719 final DetailedState state = nai.networkInfo.getDetailedState();
720 for (int type = 0; type < mTypeLists.length; type++) {
721 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700722 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900723 final boolean isFirst = contains && (nai == list.get(0));
724 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700725 maybeLogBroadcast(nai, state, type, isDefault);
726 sendLegacyNetworkBroadcast(nai, state, type);
727 }
728 }
729 }
730
Lorenzo Colittia793a672014-07-31 23:20:17 +0900731 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900732 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900733 String state = (nai.networkInfo != null) ?
734 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
735 "???/???";
736 return name + " " + state;
737 }
738
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700739 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900740 pw.println("mLegacyTypeTracker:");
741 pw.increaseIndent();
742 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700743 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900744 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700745 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900746 pw.println();
747 pw.println("Current state:");
748 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900749 synchronized (mTypeLists) {
750 for (int type = 0; type < mTypeLists.length; type++) {
751 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
752 for (NetworkAgentInfo nai : mTypeLists[type]) {
753 pw.println(type + " " + naiToString(nai));
754 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900755 }
756 }
757 pw.decreaseIndent();
758 pw.decreaseIndent();
759 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700760 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700761 }
762 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
763
Vishnu Nair5c010902017-10-26 10:08:50 -0700764 /**
765 * Helper class which parses out priority arguments and dumps sections according to their
766 * priority. If priority arguments are omitted, function calls the legacy dump command.
767 */
768 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
769 @Override
770 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
771 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
772 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
773 }
774
775 @Override
776 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
777 doDump(fd, pw, args, asProto);
778 }
779
780 @Override
781 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
782 doDump(fd, pw, args, asProto);
783 }
784 };
785
Jeff Sharkey899223b2012-08-04 15:24:58 -0700786 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700787 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900788 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
789 }
790
791 @VisibleForTesting
792 protected ConnectivityService(Context context, INetworkManagementService netManager,
793 INetworkStatsService statsService, INetworkPolicyManager policyManager,
794 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800795 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800796
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900797 mSystemProperties = getSystemProperties();
798
Hugo Benichif9fdf872016-07-28 17:53:06 +0900799 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900800 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900801 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900802 mNetworkRequests.put(mDefaultRequest, defaultNRI);
803 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900804
Chalard Jeandda156a2018-01-10 21:19:32 +0900805 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900806 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700807
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700808 // The default WiFi request is a background request so that apps using WiFi are
809 // migrated to a better network (typically ethernet) when one comes up, instead
810 // of staying on WiFi forever.
811 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
812 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
813
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900814 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900815 mHandlerThread.start();
816 mHandler = new InternalHandler(mHandlerThread.getLooper());
817 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700818
Jeremy Joslin79294842014-12-03 17:15:28 -0800819 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
820 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
821
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900822 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900823
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700824 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800825 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800826 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700827 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900828 mPolicyManagerInternal = checkNotNull(
829 LocalServices.getService(NetworkPolicyManagerInternal.class),
830 "missing NetworkPolicyManagerInternal");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000831 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900832
Luke Huang674660f2018-09-27 19:33:11 +0800833 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700834 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700835 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700836
junyulai05986c62018-08-07 19:50:45 +0800837 // To ensure uid rules are synchronized with Network Policy, register for
838 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
839 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700840 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900841 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700842 } catch (RemoteException e) {
843 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700844 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700845 }
846
847 final PowerManager powerManager = (PowerManager) context.getSystemService(
848 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700849 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
850 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
851 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800852 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700853
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700854 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700855
Wink Saville51f456f2013-04-23 14:26:51 -0700856 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900857 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700858 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700859 String[] naStrings = context.getResources().getStringArray(
860 com.android.internal.R.array.networkAttributes);
861 for (String naString : naStrings) {
862 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700863 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700864 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700865 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800866 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700867 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700868 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700869 }
Wink Saville51f456f2013-04-23 14:26:51 -0700870 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
871 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
872 n.type);
873 continue;
874 }
Wink Saville975c8482011-04-07 14:23:45 -0700875 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800876 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700877 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700878 continue;
879 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700880 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700881
Wink Saville975c8482011-04-07 14:23:45 -0700882 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700883 mNetworksDefined++;
884 } catch(Exception e) {
885 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700886 }
887 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700888
889 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
890 if (mNetConfigs[TYPE_VPN] == null) {
891 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
892 // don't need to add TYPE_VPN to mNetConfigs.
893 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
894 mNetworksDefined++; // used only in the log() statement below.
895 }
896
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900897 // Do the same for Ethernet, since it's often not specified in the configs, although many
898 // devices can use it via USB host adapters.
899 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
900 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
901 mNetworksDefined++;
902 }
903
Wink Saville5e56bc52013-07-29 15:00:57 -0700904 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700905
Robert Greenwalt50393202011-06-21 17:26:14 -0700906 mProtectedNetworks = new ArrayList<Integer>();
907 int[] protectedNetworks = context.getResources().getIntArray(
908 com.android.internal.R.array.config_protectedNetworks);
909 for (int p : protectedNetworks) {
910 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
911 mProtectedNetworks.add(p);
912 } else {
913 if (DBG) loge("Ignoring protectedNetwork " + p);
914 }
915 }
916
Erik Kline47222fc2017-04-30 19:36:15 +0900917 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800918
Luke Huang4e25ec62018-09-27 16:58:23 +0800919 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700920
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700921 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700922 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100923 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700924 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700925 intentFilter.addAction(Intent.ACTION_USER_ADDED);
926 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000927 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700928 mContext.registerReceiverAsUser(
junyulai2454b692018-11-01 17:16:31 +0800929 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000930 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
931 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900932
junyulai2454b692018-11-01 17:16:31 +0800933 // Listen to package add and removal events for all users.
934 intentFilter = new IntentFilter();
935 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800936 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800937 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
938 intentFilter.addDataScheme("package");
939 mContext.registerReceiverAsUser(
940 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
941
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700942 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800943 mNMS.registerObserver(mTethering);
944 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700945 } catch (RemoteException e) {
946 loge("Error registering observer :" + e);
947 }
948
Erik Klineda4bfa82015-04-30 12:58:40 +0900949 mSettingsObserver = new SettingsObserver(mContext, mHandler);
950 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800951
Chalard Jean4133a122018-06-04 13:33:12 +0900952 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
953 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400954
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400955 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900956
957 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900958 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
959 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900960
961 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
962 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
963 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
964 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
965 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
966 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
967 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900968
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900969 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900970 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900971 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900972
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900973 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
974
Luke Huang4e25ec62018-09-27 16:58:23 +0800975 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900976 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700978
Mike Yuf9729752018-08-17 15:22:05 +0800979 @VisibleForTesting
980 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +0900981 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900982 final TetheringDependencies deps = new TetheringDependencies() {
983 @Override
984 public boolean isTetheringSupported() {
985 return ConnectivityService.this.isTetheringSupported();
986 }
Erik Kline72302902018-06-14 17:36:40 +0900987 @Override
988 public NetworkRequest getDefaultNetworkRequest() {
989 return mDefaultRequest;
990 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900991 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800992 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900993 IoThread.get().getLooper(), new MockableSystemProperties(),
994 deps);
995 }
996
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000997 @VisibleForTesting
998 protected ProxyTracker makeProxyTracker() {
999 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1000 }
1001
Chalard Jean26400492018-04-18 20:18:38 +09001002 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1003 final NetworkCapabilities netCap = new NetworkCapabilities();
1004 netCap.addCapability(NET_CAPABILITY_INTERNET);
1005 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1006 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1007 netCap.setSingleUid(uid);
1008 return netCap;
1009 }
1010
Chalard Jeandda156a2018-01-10 21:19:32 +09001011 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001012 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001013 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001014 netCap.addCapability(NET_CAPABILITY_INTERNET);
1015 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001016 if (transportType > -1) {
1017 netCap.addTransportType(transportType);
1018 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001019 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001020 }
1021
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001022 // Used only for testing.
1023 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001024 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001025 // changing ContentResolver to make registerContentObserver non-final).
1026 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1027 // by subclassing SettingsObserver.
1028 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001029 void updateAlwaysOnNetworks() {
1030 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001031 }
1032
Erik Kline736353a2018-03-21 07:18:33 -07001033 // See FakeSettingsProvider comment above.
1034 @VisibleForTesting
1035 void updatePrivateDnsSettings() {
1036 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1037 }
1038
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001039 private void handleAlwaysOnNetworkRequest(
1040 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001041 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001042 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1043 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001044 if (enable == isEnabled) {
1045 return; // Nothing to do.
1046 }
1047
1048 if (enable) {
1049 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001050 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001051 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001052 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +09001053 }
1054 }
1055
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001056 private void handleConfigureAlwaysOnNetworks() {
1057 handleAlwaysOnNetworkRequest(
1058 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1059 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1060 false);
1061 }
1062
Erik Klineda4bfa82015-04-30 12:58:40 +09001063 private void registerSettingsCallbacks() {
1064 // Watch for global HTTP proxy changes.
1065 mSettingsObserver.observe(
1066 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1067 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1068
1069 // Watch for whether or not to keep mobile data always on.
1070 mSettingsObserver.observe(
1071 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001072 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1073
1074 // Watch for whether or not to keep wifi always on.
1075 mSettingsObserver.observe(
1076 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1077 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001078 }
1079
Erik Klinea24d4592018-01-11 21:07:29 +09001080 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001081 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1082 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001083 }
1084 }
1085
Robert Greenwalt34524f02014-05-18 16:22:10 -07001086 private synchronized int nextNetworkRequestId() {
1087 return mNextNetworkRequestId++;
1088 }
1089
Paul Jensen67b0b072015-06-10 11:22:17 -04001090 @VisibleForTesting
1091 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001092 synchronized (mNetworkForNetId) {
1093 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1094 int netId = mNextNetId;
1095 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1096 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001097 if (!mNetIdInUse.get(netId)) {
1098 mNetIdInUse.put(netId, true);
1099 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001100 }
1101 }
1102 }
1103 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001104 }
1105
Chalard Jeanc0982912018-06-07 16:11:34 +09001106 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001108 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1109 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001110 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001111 state = nai.getNetworkState();
1112 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001113 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001114 final NetworkInfo info = new NetworkInfo(networkType, 0,
1115 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001116 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1117 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001118 final NetworkCapabilities capabilities = new NetworkCapabilities();
1119 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1120 !info.isRoaming());
1121 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001122 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001123 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001124 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001125 return state;
1126 } else {
1127 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001128 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001129 }
1130
junyulai4a192e22018-06-13 15:00:37 +08001131 @VisibleForTesting
1132 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001133 if (network == null) {
1134 return null;
1135 }
Erik Kline736353a2018-03-21 07:18:33 -07001136 return getNetworkAgentInfoForNetId(network.netId);
1137 }
1138
1139 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001141 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001142 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001144
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001145 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001146 synchronized (mVpns) {
1147 if (!mLockdownEnabled) {
1148 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001149 Vpn vpn = mVpns.get(user);
1150 if (vpn != null && vpn.appliesToUid(uid)) {
1151 return vpn.getUnderlyingNetworks();
1152 }
1153 }
1154 }
1155 return null;
1156 }
1157
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001159 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001160
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001161 final Network[] networks = getVpnUnderlyingNetworks(uid);
1162 if (networks != null) {
1163 // getUnderlyingNetworks() returns:
1164 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1165 // empty array => the VPN explicitly said "no default network".
1166 // non-empty array => the VPN specified one or more default networks; we use the
1167 // first one.
1168 if (networks.length > 0) {
1169 nai = getNetworkAgentInfoForNetwork(networks[0]);
1170 } else {
1171 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001172 }
1173 }
1174
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001176 return nai.getNetworkState();
1177 } else {
1178 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001180 }
1181
1182 /**
1183 * Check if UID should be blocked from using the network with the given LinkProperties.
1184 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1186 boolean ignoreBlocked) {
1187 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001188 if (ignoreBlocked) {
1189 return false;
1190 }
Robin Lee17e61832016-05-09 13:46:28 +01001191 synchronized (mVpns) {
1192 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001193 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001194 return true;
1195 }
1196 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001197 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001198 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001199 }
1200
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001201 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001202 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1203 return;
1204 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001205 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001206 synchronized (mBlockedAppUids) {
1207 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001208 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001209 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001210 blocked = false;
1211 } else {
1212 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001213 }
1214 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001215 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1216 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1217 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001218 }
1219
junyulai05986c62018-08-07 19:50:45 +08001220 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1221 boolean blocked) {
1222 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1223 return;
1224 }
1225 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1226 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1227 nri.mUid, nri.request.requestId, net.netId));
1228 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1229 }
1230
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001231 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001232 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1233 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001234 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001235 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001236 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001237 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1238
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001239 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001240 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001241 }
Hugo Benichi69744342017-11-27 10:57:16 +09001242 synchronized (mVpns) {
1243 if (mLockdownTracker != null) {
1244 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1245 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001246 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001247 }
1248
1249 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 * Return NetworkInfo for the active (i.e., connected) network interface.
1251 * It is assumed that at most one network is active at a time. If more
1252 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001253 * @return the info for the active network, or {@code null} if none is
1254 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001256 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001258 enforceAccessPermission();
1259 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001260 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001261 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001262 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1263 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265
Paul Jensen31a94f42015-02-13 14:18:39 -05001266 @Override
1267 public Network getActiveNetwork() {
1268 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001269 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001270 }
1271
1272 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001273 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001274 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001275 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001276 }
1277
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001278 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001279 final int user = UserHandle.getUserId(uid);
1280 int vpnNetId = NETID_UNSET;
1281 synchronized (mVpns) {
1282 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001283 // TODO : now that capabilities contain the UID, the appliesToUid test should
1284 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001285 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1286 }
1287 NetworkAgentInfo nai;
1288 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001289 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001290 if (nai != null) {
1291 final NetworkCapabilities requiredCaps =
1292 createDefaultNetworkCapabilitiesForUid(uid);
1293 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1294 return nai.network;
1295 }
1296 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001297 }
1298 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001299 if (nai != null
1300 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1301 nai = null;
1302 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001303 return nai != null ? nai.network : null;
1304 }
1305
Lorenzo Colitti18660282016-07-04 12:55:44 +09001306 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001307 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1308 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001309 final int uid = Binder.getCallingUid();
1310 NetworkState state = getUnfilteredActiveNetworkState(uid);
1311 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001312 }
1313
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001314 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001315 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001316 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001317 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001318 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001319 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001320 }
1321
1322 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 public NetworkInfo getNetworkInfo(int networkType) {
1324 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001325 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001326 if (getVpnUnderlyingNetworks(uid) != null) {
1327 // A VPN is active, so we may need to return one of its underlying networks. This
1328 // information is not available in LegacyTypeTracker, so we have to get it from
1329 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001330 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001331 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001332 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001333 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001334 }
1335 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001336 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001337 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
1339
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001340 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001341 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001342 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001343 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001344 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001345 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001346 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001347 return state.networkInfo;
1348 } else {
1349 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001350 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001351 }
1352
1353 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 public NetworkInfo[] getAllNetworkInfo() {
1355 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001356 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001357 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1358 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001359 NetworkInfo info = getNetworkInfo(networkType);
1360 if (info != null) {
1361 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001364 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001367 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001368 public Network getNetworkForType(int networkType) {
1369 enforceAccessPermission();
1370 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001371 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001372 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001373 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001374 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001375 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001376 }
1377
1378 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001379 public Network[] getAllNetworks() {
1380 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001381 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001382 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001383 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001384 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001385 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001386 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001387 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001388 }
1389
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001390 @Override
1391 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1392 // The basic principle is: if an app's traffic could possibly go over a
1393 // network, without the app doing anything multinetwork-specific,
1394 // (hence, by "default"), then include that network's capabilities in
1395 // the array.
1396 //
1397 // In the normal case, app traffic only goes over the system's default
1398 // network connection, so that's the only network returned.
1399 //
1400 // With a VPN in force, some app traffic may go into the VPN, and thus
1401 // over whatever underlying networks the VPN specifies, while other app
1402 // traffic may go over the system default network (e.g.: a split-tunnel
1403 // VPN, or an app disallowed by the VPN), so the set of networks
1404 // returned includes the VPN's underlying networks and the system
1405 // default.
1406 enforceAccessPermission();
1407
Chalard Jean4133a122018-06-04 13:33:12 +09001408 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001409
1410 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001411 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001412 if (nc != null) {
1413 result.put(nai.network, nc);
1414 }
1415
Hugo Benichi69744342017-11-27 10:57:16 +09001416 synchronized (mVpns) {
1417 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001418 Vpn vpn = mVpns.get(userId);
1419 if (vpn != null) {
1420 Network[] networks = vpn.getUnderlyingNetworks();
1421 if (networks != null) {
1422 for (Network network : networks) {
1423 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001424 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001425 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001426 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001427 }
1428 }
1429 }
1430 }
1431 }
1432 }
1433
1434 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1435 out = result.values().toArray(out);
1436 return out;
1437 }
1438
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001439 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001440 public boolean isNetworkSupported(int networkType) {
1441 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001442 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001443 }
1444
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001445 /**
1446 * Return LinkProperties for the active (i.e., connected) default
1447 * network interface. It is assumed that at most one default network
1448 * is active at a time. If more than one is active, it is indeterminate
1449 * which will be returned.
1450 * @return the ip properties for the active network, or {@code null} if
1451 * none is active
1452 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001453 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001454 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001455 enforceAccessPermission();
1456 final int uid = Binder.getCallingUid();
1457 NetworkState state = getUnfilteredActiveNetworkState(uid);
1458 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001459 }
1460
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001461 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001462 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001463 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001464 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1465 if (nai != null) {
1466 synchronized (nai) {
1467 return new LinkProperties(nai.linkProperties);
1468 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001469 }
1470 return null;
1471 }
1472
Robert Greenwalt12e67352014-05-13 21:41:06 -07001473 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001474 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001475 public LinkProperties getLinkProperties(Network network) {
1476 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001477 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1478 }
1479
1480 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1481 if (nai == null) {
1482 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001483 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001484 synchronized (nai) {
1485 return new LinkProperties(nai.linkProperties);
1486 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001487 }
1488
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001489 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001490 if (nai != null) {
1491 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001492 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001493 return networkCapabilitiesRestrictedForCallerPermissions(
1494 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001495 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001496 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001497 }
1498 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001499 return null;
1500 }
1501
1502 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001503 public NetworkCapabilities getNetworkCapabilities(Network network) {
1504 enforceAccessPermission();
1505 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1506 }
1507
Chalard Jeanb03a6222018-04-11 21:09:10 +09001508 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001509 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001510 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001511 if (!checkSettingsPermission(callerPid, callerUid)) {
1512 newNc.setUids(null);
1513 newNc.setSSID(null);
1514 }
Etan Cohen836ad572018-12-30 17:59:59 -08001515 if (newNc.getNetworkSpecifier() != null) {
1516 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1517 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001518 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001519 }
1520
Chalard Jeanb552c462018-02-21 18:43:54 +09001521 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1522 if (!checkSettingsPermission()) {
1523 nc.setSingleUid(Binder.getCallingUid());
1524 }
1525 }
1526
Chalard Jean26aa91a2018-03-20 19:13:57 +09001527 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1528 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1529 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1530 }
1531 }
1532
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001533 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001534 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001535 // Require internal since we're handing out IMSI details
1536 enforceConnectivityInternalPermission();
1537
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001538 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001539 for (Network network : getAllNetworks()) {
1540 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1541 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001542 // TODO (b/73321673) : NetworkState contains a copy of the
1543 // NetworkCapabilities, which may contain UIDs of apps to which the
1544 // network applies. Should the UIDs be cleared so as not to leak or
1545 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001546 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001547 }
1548 }
1549 return result.toArray(new NetworkState[result.size()]);
1550 }
1551
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001552 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001553 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001554 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001555 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1556 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1557 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001558 }
1559
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001560 @Override
1561 public boolean isActiveNetworkMetered() {
1562 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001563
Eric Enslenc81ef192018-02-07 18:03:53 -08001564 final int uid = Binder.getCallingUid();
1565 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001566 if (caps != null) {
1567 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1568 } else {
1569 // Always return the most conservative value
1570 return true;
1571 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001572 }
1573
Jeff Sharkey216c1812012-08-05 14:29:23 -07001574 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1575 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001576 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001577 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001578 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001579 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001580 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001581
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001582 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001583 * Ensures that the system cannot call a particular method.
1584 */
1585 private boolean disallowedBecauseSystemCaller() {
1586 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1587 // requestRouteToHost.
1588 if (isSystem(Binder.getCallingUid())) {
1589 log("This method exists only for app backwards compatibility"
1590 + " and must not be called by system services.");
1591 return true;
1592 }
1593 return false;
1594 }
1595
1596 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 * Ensure that a network route exists to deliver traffic to the specified
1598 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001599 * @param networkType the type of the network over which traffic to the
1600 * specified host is to be routed
1601 * @param hostAddress the IP address of the host to which the route is
1602 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 * @return {@code true} on success, {@code false} on failure
1604 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001605 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001606 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001607 if (disallowedBecauseSystemCaller()) {
1608 return false;
1609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001611 if (mProtectedNetworks.contains(networkType)) {
1612 enforceConnectivityInternalPermission();
1613 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001614
Chad Brubakerc0234532014-02-14 13:24:29 -08001615 InetAddress addr;
1616 try {
1617 addr = InetAddress.getByAddress(hostAddress);
1618 } catch (UnknownHostException e) {
1619 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1620 return false;
1621 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001624 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 return false;
1626 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001627
1628 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1629 if (nai == null) {
1630 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1631 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1632 } else {
1633 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1634 }
1635 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001636 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001637
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001638 DetailedState netState;
1639 synchronized (nai) {
1640 netState = nai.networkInfo.getDetailedState();
1641 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001642
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001643 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001644 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001645 log("requestRouteToHostAddress on down network "
1646 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001647 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001648 }
1649 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001651
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001652 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001653 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001654 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001655 LinkProperties lp;
1656 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001657 synchronized (nai) {
1658 lp = nai.linkProperties;
1659 netId = nai.network.netId;
1660 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001661 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001662 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1663 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001664 } finally {
1665 Binder.restoreCallingIdentity(token);
1666 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001667 }
1668
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001669 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001670 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001671 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001672 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001673 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001674 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001675 if (bestRoute.getGateway().equals(addr)) {
1676 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001677 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001678 } else {
1679 // if we will connect to this through another route, add a direct route
1680 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001681 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001682 }
1683 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001684 if (DBG) log("Adding legacy route " + bestRoute +
1685 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001686 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001687 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001688 } catch (Exception e) {
1689 // never crash - catch them all
1690 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001691 return false;
1692 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001693 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695
dalyk7301aa42018-03-05 12:42:22 -05001696 @VisibleForTesting
1697 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1698 @Override
1699 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1700 String hostname, boolean validated) {
1701 try {
1702 mHandler.sendMessage(mHandler.obtainMessage(
1703 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1704 new PrivateDnsValidationUpdate(netId,
1705 InetAddress.parseNumericAddress(ipAddress),
1706 hostname, validated)));
1707 } catch (IllegalArgumentException e) {
1708 loge("Error parsing ip address in validation event");
1709 }
1710 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001711
1712 @Override
1713 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1714 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1715 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1716 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1717 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1718 // event callback for certain nai. e.g. cellular. Register here to pass to
1719 // NetworkMonitor instead.
1720 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1721 // registerNetworkAgent to have NetworkMonitor created with system process as design
1722 // expectation. Also, NetdEventListenerService only allow one callback from each
1723 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1724 // NetworkMonitor registrants.
1725 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001726 try {
1727 nai.networkMonitor().notifyDnsResponse(returnCode);
1728 } catch (RemoteException e) {
1729 e.rethrowFromSystemServer();
1730 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001731 }
1732 }
dalyk7301aa42018-03-05 12:42:22 -05001733 };
1734
1735 @VisibleForTesting
1736 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001737 final IIpConnectivityMetrics ipConnectivityMetrics =
1738 IIpConnectivityMetrics.Stub.asInterface(
1739 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1740 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001741 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001742 return;
dalyk7301aa42018-03-05 12:42:22 -05001743 }
1744
1745 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001746 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001747 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1748 mNetdEventCallback);
1749 } catch (Exception e) {
1750 loge("Error registering netd callback: " + e);
1751 }
1752 }
1753
Jeff Sharkey75d31892018-01-18 22:01:59 +09001754 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001755 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001756 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001757 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001758 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001759 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001760 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001761 // caller is NPMS, since we only register with them
1762 if (LOGD_BLOCKED_NETWORKINFO) {
1763 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1764 }
1765 mHandler.sendMessage(mHandler.obtainMessage(
1766 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1767
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001768 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001769 if (restrictBackground) {
1770 log("onRestrictBackgroundChanged(true): disabling tethering");
1771 mTethering.untetherAll();
1772 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001773 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001774 };
1775
junyulai05986c62018-08-07 19:50:45 +08001776 void handleUidRulesChanged(int uid, int newRules) {
1777 // skip update when we've already applied rules
1778 final int oldRules = mUidRules.get(uid, RULE_NONE);
1779 if (oldRules == newRules) return;
1780
1781 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1782
1783 if (newRules == RULE_NONE) {
1784 mUidRules.delete(uid);
1785 } else {
1786 mUidRules.put(uid, newRules);
1787 }
1788 }
1789
1790 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1791 if (mRestrictBackground == restrictBackground) return;
1792
1793 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1794 final boolean curMetered = nai.networkCapabilities.isMetered();
1795 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1796 restrictBackground);
1797 }
1798
1799 mRestrictBackground = restrictBackground;
1800 }
1801
1802 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1803 boolean isBackgroundRestricted) {
1804 synchronized (mVpns) {
1805 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1806 // Because the return value of this function depends on the list of UIDs the
1807 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1808 // list all state depending on the return value of this function has to be recomputed.
1809 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1810 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001811 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001812 return true;
1813 }
1814 }
1815
1816 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1817 isNetworkMetered, isBackgroundRestricted);
1818 }
1819
Robin Lee3b3dd942015-05-12 18:14:58 +01001820 /**
1821 * Require that the caller is either in the same user or has appropriate permission to interact
1822 * across users.
1823 *
1824 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1825 */
1826 private void enforceCrossUserPermission(int userId) {
1827 if (userId == UserHandle.getCallingUserId()) {
1828 // Not a cross-user call.
1829 return;
1830 }
1831 mContext.enforceCallingOrSelfPermission(
1832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1833 "ConnectivityService");
1834 }
1835
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001836 private void enforceAnyPermissionOf(String... permissions) {
1837 for (String permission : permissions) {
1838 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
1839 return;
1840 }
1841 }
1842 throw new SecurityException(
1843 "Requires one of the following permissions: " + String.join(", ", permissions) + ".");
1844 }
1845
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001846 private void enforceInternetPermission() {
1847 mContext.enforceCallingOrSelfPermission(
1848 android.Manifest.permission.INTERNET,
1849 "ConnectivityService");
1850 }
1851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001853 mContext.enforceCallingOrSelfPermission(
1854 android.Manifest.permission.ACCESS_NETWORK_STATE,
1855 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
1857
1858 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001859 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861
Charles He36738632017-05-15 17:07:18 +01001862 private void enforceSettingsPermission() {
1863 mContext.enforceCallingOrSelfPermission(
1864 android.Manifest.permission.NETWORK_SETTINGS,
1865 "ConnectivityService");
1866 }
1867
Chalard Jeanb552c462018-02-21 18:43:54 +09001868 private boolean checkSettingsPermission() {
1869 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1870 android.Manifest.permission.NETWORK_SETTINGS);
1871 }
1872
1873 private boolean checkSettingsPermission(int pid, int uid) {
1874 return PERMISSION_GRANTED == mContext.checkPermission(
1875 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1876 }
1877
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001878 private void enforceTetherAccessPermission() {
1879 mContext.enforceCallingOrSelfPermission(
1880 android.Manifest.permission.ACCESS_NETWORK_STATE,
1881 "ConnectivityService");
1882 }
1883
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001884 private void enforceConnectivityInternalPermission() {
1885 mContext.enforceCallingOrSelfPermission(
1886 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1887 "ConnectivityService");
1888 }
1889
Pavel Grafova462bcb2019-01-25 08:50:06 +00001890 private void enforceControlAlwaysOnVpnPermission() {
1891 mContext.enforceCallingOrSelfPermission(
1892 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1893 "ConnectivityService");
1894 }
1895
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001896 private void enforceNetworkStackSettingsOrSetup() {
1897 enforceAnyPermissionOf(
1898 android.Manifest.permission.NETWORK_SETTINGS,
1899 android.Manifest.permission.NETWORK_SETUP_WIZARD,
1900 android.Manifest.permission.NETWORK_STACK);
1901 }
1902
Pavel Grafova462bcb2019-01-25 08:50:06 +00001903 private void enforceNetworkStackPermission() {
1904 mContext.enforceCallingOrSelfPermission(
1905 android.Manifest.permission.NETWORK_STACK,
1906 "ConnectivityService");
1907 }
1908
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001909 private boolean checkNetworkStackPermission() {
1910 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1911 android.Manifest.permission.NETWORK_STACK);
1912 }
1913
Hugo Benichi514da602016-07-19 15:59:27 +09001914 private void enforceConnectivityRestrictedNetworksPermission() {
1915 try {
1916 mContext.enforceCallingOrSelfPermission(
1917 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1918 "ConnectivityService");
1919 return;
1920 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1921 enforceConnectivityInternalPermission();
1922 }
1923
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001924 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001925 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001926 }
1927
Lorenzo Colitti18660282016-07-04 12:55:44 +09001928 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001929 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001930 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001931 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001932 }
1933
1934 private void sendInetConditionBroadcast(NetworkInfo info) {
1935 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1936 }
1937
Wink Saville628b0852011-08-04 15:01:58 -07001938 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001939 synchronized (mVpns) {
1940 if (mLockdownTracker != null) {
1941 info = new NetworkInfo(info);
1942 mLockdownTracker.augmentNetworkInfo(info);
1943 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001944 }
1945
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001946 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001947 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001948 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 if (info.isFailover()) {
1950 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1951 info.setFailover(false);
1952 }
1953 if (info.getReason() != null) {
1954 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1955 }
1956 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001957 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1958 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001960 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001961 return intent;
1962 }
1963
1964 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1965 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1966 }
1967
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001968 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001969 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1970 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1971 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001972 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001973 final long ident = Binder.clearCallingIdentity();
1974 try {
1975 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1976 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1977 } finally {
1978 Binder.restoreCallingIdentity(ident);
1979 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001980 }
1981
Mike Lockwood0f79b542009-08-14 14:18:49 -04001982 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001983 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09001984 if (!mSystemReady
1985 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001986 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001987 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001988 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001989 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001990 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001991 }
1992
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001993 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001994 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001995 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001996 final NetworkInfo ni = intent.getParcelableExtra(
1997 ConnectivityManager.EXTRA_NETWORK_INFO);
1998 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1999 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2000 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002001 } else {
2002 BroadcastOptions opts = BroadcastOptions.makeBasic();
2003 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2004 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002005 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002006 final IBatteryStats bs = BatteryStatsService.getService();
2007 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002008 bs.noteConnectivityChanged(intent.getIntExtra(
2009 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002010 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002011 } catch (RemoteException e) {
2012 }
Chad Brubakerac925012018-03-08 10:37:09 -08002013 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002014 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002015 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002016 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002017 } finally {
2018 Binder.restoreCallingIdentity(ident);
2019 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002020 }
2021 }
2022
2023 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002024 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002025 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002026 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002027
Hugo Benichi20035e02017-04-26 14:53:28 +09002028 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002029 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002030 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002031 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002032 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002033 }
2034 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002035
Robin Lee244ce8e2016-01-05 18:03:46 +00002036 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2037 // for user to unlock device too.
2038 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002039
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002040 // Create network requests for always-on networks.
2041 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002042
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002043 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002044
2045 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 }
2047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002049 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002050 *
2051 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002052 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002053 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002054 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2055 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002056
2057 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002058 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002059
Robert Greenwalt7b816022014-04-18 15:25:25 -07002060 if (networkAgent.networkCapabilities.hasTransport(
2061 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002062 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2063 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002064 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002065 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002066 } else if (networkAgent.networkCapabilities.hasTransport(
2067 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002068 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2069 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002070 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002071 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002072 } else {
2073 // do not track any other networks
2074 timeout = 0;
2075 }
2076
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002078 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002079 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002080 } catch (Exception e) {
2081 // You shall not crash!
2082 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002083 }
2084 }
2085 }
2086
2087 /**
2088 * Remove data activity tracking when network disconnects.
2089 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002090 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2091 final String iface = networkAgent.linkProperties.getInterfaceName();
2092 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002093
Robert Greenwalt7b816022014-04-18 15:25:25 -07002094 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2095 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002096 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002097 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002098 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002099 } catch (Exception e) {
2100 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002101 }
2102 }
2103 }
2104
2105 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002106 * Update data activity tracking when network state is updated.
2107 */
2108 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2109 NetworkAgentInfo oldNetwork) {
2110 if (newNetwork != null) {
2111 setupDataActivityTracking(newNetwork);
2112 }
2113 if (oldNetwork != null) {
2114 removeDataActivityTracking(oldNetwork);
2115 }
2116 }
2117 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002118 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002119 * and set it on it's iface.
2120 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2122 final String iface = newLp.getInterfaceName();
2123 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002124 if (oldLp == null && mtu == 0) {
2125 // Silently ignore unset MTU value.
2126 return;
2127 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2129 if (VDBG) log("identical MTU - not setting");
2130 return;
2131 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002132 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002133 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002134 return;
2135 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002136
w1997615afd812014-08-05 15:18:11 -07002137 // Cannot set MTU without interface name
2138 if (TextUtils.isEmpty(iface)) {
2139 loge("Setting MTU size with null iface.");
2140 return;
2141 }
2142
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002144 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002145 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 } catch (Exception e) {
2147 Slog.e(TAG, "exception in setMtu()" + e);
2148 }
2149 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002150
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002151 @VisibleForTesting
2152 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002153 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2154
2155 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002156 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002157 protected MockableSystemProperties getSystemProperties() {
2158 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002159 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002160
lucaslin041a1af2018-11-28 19:27:52 +08002161 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002162 String[] values = null;
2163 if (tcpBufferSizes != null) {
2164 values = tcpBufferSizes.split(",");
2165 }
2166
2167 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002168 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002169 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2170 values = tcpBufferSizes.split(",");
2171 }
2172
2173 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2174
2175 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002176 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002177
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002178 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2179 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2180 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002181 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002182 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002183 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002184 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002185
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002186 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002187 Settings.Global.TCP_DEFAULT_INIT_RWND,
2188 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002189 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2190 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002191 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002192 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002193 }
2194
Robert Greenwalt562cc542014-05-15 18:07:26 -07002195 @Override
2196 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002197 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002198 NETWORK_RESTORE_DELAY_PROP_NAME);
2199 if(restoreDefaultNetworkDelayStr != null &&
2200 restoreDefaultNetworkDelayStr.length() != 0) {
2201 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002202 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002203 } catch (NumberFormatException e) {
2204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002206 // if the system property isn't set, use the value for the apn type
2207 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2208
2209 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2210 (mNetConfigs[networkType] != null)) {
2211 ret = mNetConfigs[networkType].restoreTime;
2212 }
2213 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
2215
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002216 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2217 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2218 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002219 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002220 // Start gathering diagnostic information.
2221 netDiags.add(new NetworkDiagnostics(
2222 nai.network,
2223 new LinkProperties(nai.linkProperties), // Must be a copy.
2224 DIAG_TIME_MS));
2225 }
2226
2227 for (NetworkDiagnostics netDiag : netDiags) {
2228 pw.println();
2229 netDiag.waitForMeasurements();
2230 netDiag.dump(pw);
2231 }
2232 }
2233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002235 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002236 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2237 }
2238
2239 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002240 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002241 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002242 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002243
Erik Kline3f8306b2018-05-01 16:51:44 +09002244 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002245 dumpNetworkDiagnostics(pw);
2246 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002247 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002248 mTethering.dump(fd, pw, args);
2249 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002250 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2251 dumpNetworks(pw);
2252 return;
2253 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2254 dumpNetworkRequests(pw);
2255 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002256 }
Erik Kline379747a2015-06-05 17:47:34 +09002257
Lorenzo Colittie3805462015-06-03 11:18:24 +09002258 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002259 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002260 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002261 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002262 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002263 pw.println();
2264
Paul Jensen85cf78e2015-06-25 13:25:07 -04002265 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002266 pw.print("Active default network: ");
2267 if (defaultNai == null) {
2268 pw.println("none");
2269 } else {
2270 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002272 pw.println();
2273
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002274 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002275 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002276 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002277 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002278 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002279
junyulai05986c62018-08-07 19:50:45 +08002280 pw.print("Restrict background: ");
2281 pw.println(mRestrictBackground);
2282 pw.println();
2283
2284 pw.println("Status for known UIDs:");
2285 pw.increaseIndent();
2286 final int size = mUidRules.size();
2287 for (int i = 0; i < size; i++) {
2288 // Don't crash if the array is modified while dumping in bugreports.
2289 try {
2290 final int uid = mUidRules.keyAt(i);
2291 final int uidRules = mUidRules.get(uid, RULE_NONE);
2292 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2293 } catch (ArrayIndexOutOfBoundsException e) {
2294 pw.println(" ArrayIndexOutOfBoundsException");
2295 } catch (ConcurrentModificationException e) {
2296 pw.println(" ConcurrentModificationException");
2297 }
2298 }
2299 pw.println();
2300 pw.decreaseIndent();
2301
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002302 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002303 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002304 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002305 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002306 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002307
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002308 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002309
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002310 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002311 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002312
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002313 pw.println();
2314 mKeepaliveTracker.dump(pw);
2315
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002316 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002317 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002318
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002319 pw.println();
2320 mMultipathPolicyTracker.dump(pw);
2321
Erik Kline3f8306b2018-05-01 16:51:44 +09002322 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002323 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002324 pw.println("mNetworkRequestInfoLogs (most recent first):");
2325 pw.increaseIndent();
2326 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2327 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002328
2329 pw.println();
2330 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2331 pw.increaseIndent();
2332 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2333 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002334
2335 pw.println();
2336 pw.println("NetTransition WakeLock activity (most recent first):");
2337 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002338 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2339 pw.println("total releases: " + mTotalWakelockReleases);
2340 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2341 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2342 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2343 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2344 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2345 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002346 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002347
2348 pw.println();
2349 pw.println("bandwidth update requests (by uid):");
2350 pw.increaseIndent();
2351 synchronized (mBandwidthRequests) {
2352 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2353 pw.println("[" + mBandwidthRequests.keyAt(i)
2354 + "]: " + mBandwidthRequests.valueAt(i));
2355 }
2356 }
2357 pw.decreaseIndent();
2358
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002359 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 }
2362
Hugo Benichi14683812018-09-03 08:32:56 +09002363 private void dumpNetworks(IndentingPrintWriter pw) {
2364 for (NetworkAgentInfo nai : networksSortedById()) {
2365 pw.println(nai.toString());
2366 pw.increaseIndent();
2367 pw.println(String.format(
2368 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2369 nai.numForegroundNetworkRequests(),
2370 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2371 nai.numBackgroundNetworkRequests(),
2372 nai.numNetworkRequests()));
2373 pw.increaseIndent();
2374 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2375 pw.println(nai.requestAt(i).toString());
2376 }
2377 pw.decreaseIndent();
2378 pw.println("Lingered:");
2379 pw.increaseIndent();
2380 nai.dumpLingerTimers(pw);
2381 pw.decreaseIndent();
2382 pw.decreaseIndent();
2383 }
2384 }
2385
2386 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2387 for (NetworkRequestInfo nri : requestsSortedById()) {
2388 pw.println(nri.toString());
2389 }
2390 }
2391
Hugo Benichia2a917c2018-09-03 08:19:02 +09002392 /**
2393 * Return an array of all current NetworkAgentInfos sorted by network id.
2394 */
2395 private NetworkAgentInfo[] networksSortedById() {
2396 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2397 networks = mNetworkAgentInfos.values().toArray(networks);
2398 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2399 return networks;
2400 }
2401
2402 /**
2403 * Return an array of all current NetworkRequest sorted by request id.
2404 */
2405 private NetworkRequestInfo[] requestsSortedById() {
2406 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2407 requests = mNetworkRequests.values().toArray(requests);
2408 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2409 return requests;
2410 }
2411
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002412 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002413 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002414 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002415 if (officialNai != null && officialNai.equals(nai)) return true;
2416 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002417 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002418 " - " + nai);
2419 }
2420 return false;
2421 }
2422
Robert Greenwalt42acef32009-08-12 16:08:25 -07002423 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002424 private class NetworkStateTrackerHandler extends Handler {
2425 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002426 super(looper);
2427 }
2428
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002429 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002431 default:
2432 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002433 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002434 handleAsyncChannelHalfConnect(msg);
2435 break;
2436 }
2437 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2438 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2439 if (nai != null) nai.asyncChannel.disconnect();
2440 break;
2441 }
2442 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2443 handleAsyncChannelDisconnected(msg);
2444 break;
2445 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002446 }
2447 return true;
2448 }
2449
2450 private void maybeHandleNetworkAgentMessage(Message msg) {
2451 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2452 if (nai == null) {
2453 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002454 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002455 }
2456 return;
2457 }
2458
2459 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002460 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002461 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2462 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002463 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2464 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002465 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002466 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002467 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002468 break;
2469 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002470 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002471 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002472 break;
2473 }
2474 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002475 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002476 updateNetworkInfo(nai, info);
2477 break;
2478 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002479 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002480 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002481 break;
2482 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002483 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002484 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2485 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002486 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002487 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002488 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002489 break;
2490 }
junyulaie4135282019-01-03 18:50:15 +08002491 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2492 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002493 break;
2494 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002495 }
2496 }
2497
2498 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2499 switch (msg.what) {
2500 default:
2501 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002502 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002503 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002504 if (nai == null) break;
2505
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002506 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002507 final boolean wasValidated = nai.lastValidated;
2508 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002509 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2510 && valid) {
2511 nai.captivePortalLoginNotified = true;
2512 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2513 }
Erik Klinea24d4592018-01-11 21:07:29 +09002514
Erik Klinea24d4592018-01-11 21:07:29 +09002515 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2516
Erik Klinea24d4592018-01-11 21:07:29 +09002517 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002518 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2519 ? " with redirect to " + redirectUrl
2520 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002521 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2522 }
Erik Klinea24d4592018-01-11 21:07:29 +09002523 if (valid != nai.lastValidated) {
2524 if (wasDefault) {
2525 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2526 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002527 }
Erik Klinea24d4592018-01-11 21:07:29 +09002528 final int oldScore = nai.getCurrentScore();
2529 nai.lastValidated = valid;
2530 nai.everValidated |= valid;
2531 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2532 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2533 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002534 if (valid) {
2535 handleFreshlyValidatedNetwork(nai);
2536 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2537 // valid.
2538 mNotifier.clearNotification(nai.network.netId,
2539 NotificationType.NO_INTERNET);
2540 mNotifier.clearNotification(nai.network.netId,
2541 NotificationType.LOST_INTERNET);
2542 }
Erik Klinea24d4592018-01-11 21:07:29 +09002543 }
2544 updateInetCondition(nai);
2545 // Let the NetworkAgent know the state of its network
2546 Bundle redirectUrlBundle = new Bundle();
2547 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2548 nai.asyncChannel.sendMessage(
2549 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2550 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2551 0, redirectUrlBundle);
2552 if (wasValidated && !nai.lastValidated) {
2553 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002554 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002555 break;
2556 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002557 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002558 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002559 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002560 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002561 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002562 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002563 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002564 nai.lastCaptivePortalDetected = visible;
2565 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002566 if (visible) {
2567 nai.captivePortalLoginNotified = false;
2568 }
Calvin Onbe96da12016-10-11 15:10:46 -07002569 if (nai.lastCaptivePortalDetected &&
2570 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2571 if (DBG) log("Avoiding captive portal network: " + nai.name());
2572 nai.asyncChannel.sendMessage(
2573 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2574 teardownUnneededNetwork(nai);
2575 break;
2576 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002577 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002578 }
2579 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002580 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
2581 // notifications belong to the same network may be cleared unexpected.
2582 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2583 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002584 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002585 if (nai == null) {
2586 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2587 break;
2588 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002589 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002590 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002591 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002592 }
Paul Jensen869868be2014-05-15 10:33:05 -04002593 }
Paul Jensen869868be2014-05-15 10:33:05 -04002594 break;
2595 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002596 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002597 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002598 if (nai == null) break;
2599
Erik Kline736353a2018-03-21 07:18:33 -07002600 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002601 break;
2602 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002603 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002604 return true;
2605 }
2606
Calvin Onbe96da12016-10-11 15:10:46 -07002607 private int getCaptivePortalMode() {
2608 return Settings.Global.getInt(mContext.getContentResolver(),
2609 Settings.Global.CAPTIVE_PORTAL_MODE,
2610 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2611 }
2612
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002613 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2614 switch (msg.what) {
2615 default:
2616 return false;
2617 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2618 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2619 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2620 handleLingerComplete(nai);
2621 }
2622 break;
2623 }
2624 }
2625 return true;
2626 }
2627
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002628 @Override
2629 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002630 if (!maybeHandleAsyncChannelMessage(msg) &&
2631 !maybeHandleNetworkMonitorMessage(msg) &&
2632 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002633 maybeHandleNetworkAgentMessage(msg);
2634 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002635 }
2636 }
2637
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002638 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2639 private final NetworkAgentInfo mNai;
2640
2641 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2642 mNai = nai;
2643 }
2644
2645 @Override
2646 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2647 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2648 new Pair<>(mNai, networkMonitor)));
2649 }
2650
2651 @Override
2652 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2653 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2654 testResult, mNai.network.netId, redirectUrl));
2655 }
2656
2657 @Override
2658 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2659 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2660 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2661 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2662 }
2663
2664 @Override
2665 public void showProvisioningNotification(String action) {
2666 final Intent intent = new Intent(action);
2667 intent.setPackage(NETWORKSTACK_PACKAGE_NAME);
2668
2669 final PendingIntent pendingIntent;
2670 // Only the system server can register notifications with package "android"
2671 final long token = Binder.clearCallingIdentity();
2672 try {
2673 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2674 } finally {
2675 Binder.restoreCallingIdentity(token);
2676 }
2677 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2678 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2679 mNai.network.netId,
2680 pendingIntent));
2681 }
2682
2683 @Override
2684 public void hideProvisioningNotification() {
2685 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2686 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2687 mNai.network.netId));
2688 }
Remi NGUYEN VANd4a9de202019-01-30 22:01:20 +09002689
2690 @Override
2691 public void logCaptivePortalLoginEvent(int eventId, String packageName) {
2692 new MetricsLogger().action(eventId, packageName);
2693 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002694 }
2695
Erik Kline736353a2018-03-21 07:18:33 -07002696 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002697 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002698 }
2699
Erik Klinec6d00222018-06-26 18:53:43 +09002700 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2701 if (nai == null) return;
2702 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2703 // in order to restart a validation pass from within netd.
2704 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2705 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2706 updateDnses(nai.linkProperties, null, nai.network.netId);
2707 }
2708 }
2709
Erik Klinea24d4592018-01-11 21:07:29 +09002710 private void handlePrivateDnsSettingsChanged() {
2711 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2712
2713 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002714 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002715 if (networkRequiresValidation(nai)) {
2716 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2717 }
Erik Klinea24d4592018-01-11 21:07:29 +09002718 }
2719 }
2720
Erik Kline736353a2018-03-21 07:18:33 -07002721 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2722 // Private DNS only ever applies to networks that might provide
2723 // Internet access and therefore also require validation.
2724 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002725
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002726 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002727 // schedule DNS resolutions. If a DNS resolution is required the
2728 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002729 try {
2730 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2731 } catch (RemoteException e) {
2732 e.rethrowFromSystemServer();
2733 }
Erik Kline736353a2018-03-21 07:18:33 -07002734
2735 // With Private DNS bypass support, we can proceed to update the
2736 // Private DNS config immediately, even if we're in strict mode
2737 // and have not yet resolved the provider name into a set of IPs.
2738 updatePrivateDns(nai, cfg);
2739 }
2740
2741 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2742 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002743 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002744 }
2745
dalyk7301aa42018-03-05 12:42:22 -05002746 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2747 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2748 if (nai == null) {
2749 return;
2750 }
2751 mDnsManager.updatePrivateDnsValidation(update);
2752 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2753 }
2754
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002755 private void updateLingerState(NetworkAgentInfo nai, long now) {
2756 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2757 // 2. If the network was lingering and there are now requests, unlinger it.
2758 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2759 // one lingered request, start lingering.
2760 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002761 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002762 if (DBG) log("Unlingering " + nai.name());
2763 nai.unlinger();
2764 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002765 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002766 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002767 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002768 nai.linger();
2769 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2770 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2771 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002772 }
2773
Robert Greenwalt7b816022014-04-18 15:25:25 -07002774 private void handleAsyncChannelHalfConnect(Message msg) {
2775 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002776 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002777 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2778 if (VDBG) log("NetworkFactory connected");
2779 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002780 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002781 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002782 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002783 final int score;
2784 final int serial;
2785 if (nai != null) {
2786 score = nai.getCurrentScore();
2787 serial = nai.factorySerialNumber;
2788 } else {
2789 score = 0;
2790 serial = NetworkFactory.SerialNumber.NONE;
2791 }
2792 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2793 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002794 }
2795 } else {
2796 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002797 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002798 }
2799 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2800 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2801 if (VDBG) log("NetworkAgent connected");
2802 // A network agent has requested a connection. Establish the connection.
2803 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2804 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2805 } else {
2806 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002807 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002808 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002809 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002810 synchronized (mNetworkForNetId) {
2811 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002812 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002813 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002814 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002815 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002816 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002817 }
2818 }
2819 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002820
Chalard Jean392971c2018-05-11 20:19:20 +09002821 // This is a no-op if it's called with a message designating a network that has
2822 // already been destroyed, because its reference will not be found in the relevant
2823 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002824 private void handleAsyncChannelDisconnected(Message msg) {
2825 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2826 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002827 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002828 } else {
2829 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2830 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002831 }
2832 }
2833
Chalard Jean392971c2018-05-11 20:19:20 +09002834 // Destroys a network, remove references to it from the internal state managed by
2835 // ConnectivityService, free its interfaces and clean up.
2836 // Must be called on the Handler thread.
2837 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2838 if (DBG) {
2839 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2840 }
2841 // A network agent has disconnected.
2842 // TODO - if we move the logic to the network agent (have them disconnect
2843 // because they lost all their requests or because their score isn't good)
2844 // then they would disconnect organically, report their new state and then
2845 // disconnect the channel.
2846 if (nai.networkInfo.isConnected()) {
2847 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2848 null, null);
2849 }
2850 final boolean wasDefault = isDefaultNetwork(nai);
2851 if (wasDefault) {
2852 mDefaultInetConditionPublished = 0;
2853 // Log default network disconnection before required book-keeping.
2854 // Let rematchAllNetworksAndRequests() below record a new default network event
2855 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2856 // whose timestamps tell how long it takes to recover a default network.
2857 long now = SystemClock.elapsedRealtime();
2858 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2859 }
2860 notifyIfacesChangedForNetworkStats();
2861 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2862 // by other networks that are already connected. Perhaps that can be done by
2863 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2864 // of rematchAllNetworksAndRequests
2865 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulaie4135282019-01-03 18:50:15 +08002866 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002867 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2868 // Disable wakeup packet monitoring for each interface.
2869 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2870 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002871 try {
2872 nai.networkMonitor().notifyNetworkDisconnected();
2873 } catch (RemoteException e) {
2874 e.rethrowFromSystemServer();
2875 }
Chalard Jean392971c2018-05-11 20:19:20 +09002876 mNetworkAgentInfos.remove(nai.messenger);
2877 nai.maybeStopClat();
2878 synchronized (mNetworkForNetId) {
2879 // Remove the NetworkAgent, but don't mark the netId as
2880 // available until we've told netd to delete it below.
2881 mNetworkForNetId.remove(nai.network.netId);
2882 }
2883 // Remove all previously satisfied requests.
2884 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2885 NetworkRequest request = nai.requestAt(i);
2886 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2887 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2888 clearNetworkForRequest(request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002889 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09002890 }
2891 }
2892 nai.clearLingerState();
2893 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002894 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002895 notifyLockdownVpn(nai);
2896 ensureNetworkTransitionWakelock(nai.name());
2897 }
2898 mLegacyTypeTracker.remove(nai, wasDefault);
2899 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2900 updateAllVpnsCapabilities();
2901 }
2902 rematchAllNetworksAndRequests(null, 0);
2903 mLingerMonitor.noteDisconnect(nai);
2904 if (nai.created) {
2905 // Tell netd to clean up the configuration for this network
2906 // (routing rules, DNS, etc).
2907 // This may be slow as it requires a lot of netd shelling out to ip and
2908 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2909 // after we've rematched networks with requests which should make a potential
2910 // fallback network the default or requested a new network from the
2911 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2912 // long time.
2913 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002914 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002915 } catch (Exception e) {
2916 loge("Exception removing network: " + e);
2917 }
2918 mDnsManager.removeNetwork(nai.network);
2919 }
2920 synchronized (mNetworkForNetId) {
2921 mNetIdInUse.delete(nai.network.netId);
2922 }
2923 }
2924
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002925 // If this method proves to be too slow then we can maintain a separate
2926 // pendingIntent => NetworkRequestInfo map.
2927 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2928 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2929 Intent intent = pendingIntent.getIntent();
2930 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2931 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2932 if (existingPendingIntent != null &&
2933 existingPendingIntent.getIntent().filterEquals(intent)) {
2934 return entry.getValue();
2935 }
2936 }
2937 return null;
2938 }
2939
2940 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2941 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2942
2943 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2944 if (existingRequest != null) { // remove the existing request.
2945 if (DBG) log("Replacing " + existingRequest.request + " with "
2946 + nri.request + " because their intents matched.");
2947 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2948 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002949 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002950 }
2951
Erik Klineda4bfa82015-04-30 12:58:40 +09002952 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002953 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002954 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002955 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002956 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002957 if (nri.request.networkCapabilities.hasSignalStrength() &&
2958 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2959 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002960 }
2961 }
2962 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002963 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002964 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean08577fc2018-05-02 21:14:54 +09002965 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002966 }
2967 }
2968
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002969 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2970 int callingUid) {
2971 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2972 if (nri != null) {
2973 handleReleaseNetworkRequest(nri.request, callingUid);
2974 }
2975 }
2976
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002977 // Determines whether the network is the best (or could become the best, if it validated), for
2978 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2979 // on the value of reason:
2980 //
2981 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2982 // then it should be torn down.
2983 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2984 // then it should be lingered.
2985 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2986 final int numRequests;
2987 switch (reason) {
2988 case TEARDOWN:
2989 numRequests = nai.numRequestNetworkRequests();
2990 break;
2991 case LINGER:
2992 numRequests = nai.numForegroundNetworkRequests();
2993 break;
2994 default:
2995 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2996 return true;
2997 }
2998
2999 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003000 return false;
3001 }
Paul Jensene0988542015-06-25 15:30:08 -04003002 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003003 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3004 // Background requests don't affect lingering.
3005 continue;
3006 }
3007
Paul Jensene0988542015-06-25 15:30:08 -04003008 // If this Network is already the highest scoring Network for a request, or if
3009 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003010 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003011 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003012 // Note that this catches two important cases:
3013 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3014 // is currently satisfying the request. This is desirable when
3015 // cellular ends up validating but WiFi does not.
3016 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003017 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003018 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003019 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003020 nai.getCurrentScoreAsValidated())) {
3021 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003022 }
3023 }
Paul Jensene0988542015-06-25 15:30:08 -04003024 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003025 }
3026
Erik Klineacdd6392016-07-07 16:50:58 +09003027 private NetworkRequestInfo getNriForAppRequest(
3028 NetworkRequest request, int callingUid, String requestedOperation) {
3029 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3030
Robert Greenwalt9258c642014-03-26 16:47:06 -07003031 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003032 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003033 log(String.format("UID %d attempted to %s for unowned request %s",
3034 callingUid, requestedOperation, nri));
3035 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003036 }
Erik Klineacdd6392016-07-07 16:50:58 +09003037 }
3038
3039 return nri;
3040 }
3041
Erik Kline57faba92015-11-25 12:49:38 +09003042 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003043 if (mNetworkRequests.get(nri.request) == null) {
3044 return;
Erik Kline57faba92015-11-25 12:49:38 +09003045 }
Hugo Benichicd952782017-09-20 11:20:14 +09003046 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003047 return;
3048 }
3049 if (VDBG || (DBG && nri.request.isRequest())) {
3050 log("releasing " + nri.request + " (timeout)");
3051 }
3052 handleRemoveNetworkRequest(nri);
3053 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003054 }
3055
Erik Klineacdd6392016-07-07 16:50:58 +09003056 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003057 final NetworkRequestInfo nri =
3058 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3059 if (nri == null) {
3060 return;
Erik Kline57faba92015-11-25 12:49:38 +09003061 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003062 if (VDBG || (DBG && nri.request.isRequest())) {
3063 log("releasing " + nri.request + " (release request)");
3064 }
3065 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09003066 }
Erik Klineacdd6392016-07-07 16:50:58 +09003067
Hugo Benichidba33db2017-03-23 22:40:44 +09003068 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003069 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003070 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003071
Erik Klineacdd6392016-07-07 16:50:58 +09003072 synchronized (mUidToNetworkRequestCount) {
3073 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3074 if (requests < 1) {
3075 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3076 nri.mUid);
3077 } else if (requests == 1) {
3078 mUidToNetworkRequestCount.removeAt(
3079 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3080 } else {
3081 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3082 }
3083 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003084
Erik Klineacdd6392016-07-07 16:50:58 +09003085 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3086 if (nri.request.isRequest()) {
3087 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003088 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003089 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003090 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003091 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003092 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003093 log(" Removing from current network " + nai.name() +
3094 ", leaving " + nai.numNetworkRequests() + " requests.");
3095 }
3096 // If there are still lingered requests on this network, don't tear it down,
3097 // but resume lingering instead.
3098 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003099 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003100 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3101 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003102 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003103 wasKept = true;
3104 }
Hugo Benichicd952782017-09-20 11:20:14 +09003105 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003106 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3107 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003108 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003109 }
Erik Klineacdd6392016-07-07 16:50:58 +09003110 }
3111
Erik Klineacdd6392016-07-07 16:50:58 +09003112 // Maintain the illusion. When this request arrived, we might have pretended
3113 // that a network connected to serve it, even though the network was already
3114 // connected. Now that this request has gone away, we might have to pretend
3115 // that the network disconnected. LegacyTypeTracker will generate that
3116 // phantom disconnect for this type.
3117 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3118 boolean doRemove = true;
3119 if (wasKept) {
3120 // check if any of the remaining requests for this network are for the
3121 // same legacy type - if so, don't remove the nai
3122 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3123 NetworkRequest otherRequest = nai.requestAt(i);
3124 if (otherRequest.legacyType == nri.request.legacyType &&
3125 otherRequest.isRequest()) {
3126 if (DBG) log(" still have other legacy request - leaving");
3127 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003128 }
3129 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003130 }
3131
Erik Klineacdd6392016-07-07 16:50:58 +09003132 if (doRemove) {
3133 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003134 }
3135 }
Erik Klineacdd6392016-07-07 16:50:58 +09003136
3137 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3138 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3139 nri.request);
3140 }
3141 } else {
3142 // listens don't have a singular affectedNetwork. Check all networks to see
3143 // if this listen request applies and remove it.
3144 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3145 nai.removeRequest(nri.request.requestId);
3146 if (nri.request.networkCapabilities.hasSignalStrength() &&
3147 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3148 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3149 }
3150 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003151 }
3152 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003153
Lorenzo Colitti18660282016-07-04 12:55:44 +09003154 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003155 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3156 enforceConnectivityInternalPermission();
3157 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003158 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003159 }
3160
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003161 @Override
3162 public void setAvoidUnvalidated(Network network) {
3163 enforceConnectivityInternalPermission();
3164 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3165 }
3166
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003167 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3168 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3169 " accept=" + accept + " always=" + always);
3170
3171 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3172 if (nai == null) {
3173 // Nothing to do.
3174 return;
3175 }
3176
3177 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003178 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003179 return;
3180 }
3181
3182 if (!nai.networkMisc.explicitlySelected) {
3183 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3184 }
3185
3186 if (accept != nai.networkMisc.acceptUnvalidated) {
3187 int oldScore = nai.getCurrentScore();
3188 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003189 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003190 sendUpdatedScoreToFactories(nai);
3191 }
3192
3193 if (always) {
3194 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003195 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003196 }
3197
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003198 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003199 // Tell the NetworkAgent to not automatically reconnect to the network.
3200 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003201 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003202 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003203 }
3204
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003205 }
3206
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003207 private void handleSetAvoidUnvalidated(Network network) {
3208 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3209 if (nai == null || nai.lastValidated) {
3210 // Nothing to do. The network either disconnected or revalidated.
3211 return;
3212 }
3213 if (!nai.avoidUnvalidated) {
3214 int oldScore = nai.getCurrentScore();
3215 nai.avoidUnvalidated = true;
3216 rematchAllNetworksAndRequests(nai, oldScore);
3217 sendUpdatedScoreToFactories(nai);
3218 }
3219 }
3220
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003221 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003222 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003223 mHandler.sendMessageDelayed(
3224 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3225 PROMPT_UNVALIDATED_DELAY_MS);
3226 }
3227
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003228 @Override
3229 public void startCaptivePortalApp(Network network) {
3230 enforceConnectivityInternalPermission();
3231 mHandler.post(() -> {
3232 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3233 if (nai == null) return;
3234 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003235 try {
3236 nai.networkMonitor().launchCaptivePortalApp();
3237 } catch (RemoteException e) {
3238 e.rethrowFromSystemServer();
3239 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003240 });
3241 }
3242
Hugo Benichic8e9e122016-09-14 23:23:08 +00003243 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003244 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003245 }
3246
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003247 @Override
3248 public boolean getAvoidBadWifi() {
3249 if (!checkNetworkStackPermission()) {
3250 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3251 }
3252 return avoidBadWifi();
3253 }
3254
3255
Erik Kline065ab6e2016-10-02 18:02:14 +09003256 private void rematchForAvoidBadWifiUpdate() {
3257 rematchAllNetworksAndRequests(null, 0);
3258 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3259 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3260 sendUpdatedScoreToFactories(nai);
3261 }
3262 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003263 }
3264
Erik Kline065ab6e2016-10-02 18:02:14 +09003265 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003266 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003267 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003268 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003269 if (!configRestrict) {
3270 pw.println("Bad Wi-Fi avoidance: unrestricted");
3271 return;
3272 }
3273
3274 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3275 pw.increaseIndent();
3276 pw.println("Config restrict: " + configRestrict);
3277
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003278 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003279 String description;
3280 // Can't use a switch statement because strings are legal case labels, but null is not.
3281 if ("0".equals(value)) {
3282 description = "get stuck";
3283 } else if (value == null) {
3284 description = "prompt";
3285 } else if ("1".equals(value)) {
3286 description = "avoid";
3287 } else {
3288 description = value + " (?)";
3289 }
3290 pw.println("User setting: " + description);
3291 pw.println("Network overrides:");
3292 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003293 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003294 if (nai.avoidUnvalidated) {
3295 pw.println(nai.name());
3296 }
3297 }
3298 pw.decreaseIndent();
3299 pw.decreaseIndent();
3300 }
3301
lucaslind2e045e02019-01-24 15:55:30 +08003302 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003303 final String action;
3304 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003305 case LOGGED_IN:
3306 action = Settings.ACTION_WIFI_SETTINGS;
3307 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3308 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3309 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3310 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003311 case NO_INTERNET:
3312 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3313 break;
3314 case LOST_INTERNET:
3315 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3316 break;
3317 default:
3318 Slog.wtf(TAG, "Unknown notification type " + type);
3319 return;
3320 }
3321
3322 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003323 if (type != NotificationType.LOGGED_IN) {
3324 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3325 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3326 intent.setClassName("com.android.settings",
3327 "com.android.settings.wifi.WifiNoInternetDialog");
3328 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003329
3330 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3331 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3332 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3333 }
3334
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003335 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003336 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003337 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3338
3339 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3340 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003341 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003342 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003343 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3344 return;
3345 }
lucaslind2e045e02019-01-24 15:55:30 +08003346 showNetworkNotification(nai, NotificationType.NO_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003347 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003348
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003349 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3350 NetworkCapabilities nc = nai.networkCapabilities;
3351 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003352
Erik Kline065ab6e2016-10-02 18:02:14 +09003353 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003354 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003355 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003356 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003357 }
3358
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003359 @Override
3360 public int getMultipathPreference(Network network) {
3361 enforceAccessPermission();
3362
3363 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003364 if (nai != null && nai.networkCapabilities
3365 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003366 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3367 }
3368
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003369 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3370 if (networkPreference != null) {
3371 return networkPreference;
3372 }
3373
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003374 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3375 }
3376
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003377 @Override
3378 public NetworkRequest getDefaultRequest() {
3379 return mDefaultRequest;
3380 }
3381
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003382 private class InternalHandler extends Handler {
3383 public InternalHandler(Looper looper) {
3384 super(looper);
3385 }
3386
3387 @Override
3388 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003389 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003390 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003391 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003392 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003393 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003394 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003395 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003396 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003397 break;
3398 }
Jason Monkdecd2952013-10-10 14:02:51 -04003399 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003400 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003401 break;
3402 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003403 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003404 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3405 break;
3406 }
3407 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3408 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003409 break;
3410 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003411 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003412 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3413 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3414 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003415 break;
3416 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003417 case EVENT_REGISTER_NETWORK_REQUEST:
3418 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003419 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003420 break;
3421 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003422 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3423 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003424 handleRegisterNetworkRequestWithIntent(msg);
3425 break;
3426 }
Erik Kline57faba92015-11-25 12:49:38 +09003427 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3428 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3429 handleTimedOutNetworkRequest(nri);
3430 break;
3431 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003432 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3433 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3434 break;
3435 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003436 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003437 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003438 break;
3439 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003440 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003441 Network network = (Network) msg.obj;
3442 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003443 break;
3444 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003445 case EVENT_SET_AVOID_UNVALIDATED: {
3446 handleSetAvoidUnvalidated((Network) msg.obj);
3447 break;
3448 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003449 case EVENT_PROMPT_UNVALIDATED: {
3450 handlePromptUnvalidated((Network) msg.obj);
3451 break;
3452 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003453 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3454 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003455 break;
3456 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003457 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003458 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003459 mKeepaliveTracker.handleStartKeepalive(msg);
3460 break;
3461 }
3462 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003463 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003464 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3465 int slot = msg.arg1;
3466 int reason = msg.arg2;
3467 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3468 break;
3469 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003470 case EVENT_SYSTEM_READY: {
3471 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003472 // Might have been called already in handleRegisterNetworkAgent since
3473 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3474 // this several times is fine.
3475 try {
3476 nai.networkMonitor().notifySystemReady();
3477 } catch (RemoteException e) {
3478 e.rethrowFromSystemServer();
3479 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003480 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003481 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003482 break;
3483 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003484 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003485 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003486 break;
3487 }
Erik Klinea24d4592018-01-11 21:07:29 +09003488 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3489 handlePrivateDnsSettingsChanged();
3490 break;
dalyk7301aa42018-03-05 12:42:22 -05003491 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3492 handlePrivateDnsValidationUpdate(
3493 (PrivateDnsValidationUpdate) msg.obj);
3494 break;
junyulai05986c62018-08-07 19:50:45 +08003495 case EVENT_UID_RULES_CHANGED:
3496 handleUidRulesChanged(msg.arg1, msg.arg2);
3497 break;
3498 case EVENT_DATA_SAVER_CHANGED:
3499 handleRestrictBackgroundChanged(toBool(msg.arg1));
3500 break;
lucaslind2e045e02019-01-24 15:55:30 +08003501 case EVENT_TIMEOUT_NOTIFICATION:
3502 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3503 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 }
3505 }
3506 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003507
3508 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003509 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003510 public int tether(String iface, String callerPkg) {
3511 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003512 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003513 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003514 } else {
3515 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3516 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003517 }
3518
3519 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003520 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003521 public int untether(String iface, String callerPkg) {
3522 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003523
3524 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003525 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003526 } else {
3527 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3528 }
3529 }
3530
3531 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003532 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003533 public int getLastTetherError(String iface) {
3534 enforceTetherAccessPermission();
3535
3536 if (isTetheringSupported()) {
3537 return mTethering.getLastTetherError(iface);
3538 } else {
3539 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3540 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003541 }
3542
3543 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003544 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003545 public String[] getTetherableUsbRegexs() {
3546 enforceTetherAccessPermission();
3547 if (isTetheringSupported()) {
3548 return mTethering.getTetherableUsbRegexs();
3549 } else {
3550 return new String[0];
3551 }
3552 }
3553
Lorenzo Colitti18660282016-07-04 12:55:44 +09003554 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003555 public String[] getTetherableWifiRegexs() {
3556 enforceTetherAccessPermission();
3557 if (isTetheringSupported()) {
3558 return mTethering.getTetherableWifiRegexs();
3559 } else {
3560 return new String[0];
3561 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003562 }
3563
Lorenzo Colitti18660282016-07-04 12:55:44 +09003564 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003565 public String[] getTetherableBluetoothRegexs() {
3566 enforceTetherAccessPermission();
3567 if (isTetheringSupported()) {
3568 return mTethering.getTetherableBluetoothRegexs();
3569 } else {
3570 return new String[0];
3571 }
3572 }
3573
Lorenzo Colitti18660282016-07-04 12:55:44 +09003574 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003575 public int setUsbTethering(boolean enable, String callerPkg) {
3576 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003577 if (isTetheringSupported()) {
3578 return mTethering.setUsbTethering(enable);
3579 } else {
3580 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3581 }
3582 }
3583
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003584 // TODO - move iface listing, queries, etc to new module
3585 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003586 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003587 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003588 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003589 return mTethering.getTetherableIfaces();
3590 }
3591
Lorenzo Colitti18660282016-07-04 12:55:44 +09003592 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003593 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003594 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003595 return mTethering.getTetheredIfaces();
3596 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003597
Lorenzo Colitti18660282016-07-04 12:55:44 +09003598 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003599 public String[] getTetheringErroredIfaces() {
3600 enforceTetherAccessPermission();
3601 return mTethering.getErroredIfaces();
3602 }
3603
Lorenzo Colitti18660282016-07-04 12:55:44 +09003604 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003605 public String[] getTetheredDhcpRanges() {
3606 enforceConnectivityInternalPermission();
3607 return mTethering.getTetheredDhcpRanges();
3608 }
3609
Udam Saini0e94c362017-06-07 12:06:28 -07003610 @Override
3611 public boolean isTetheringSupported(String callerPkg) {
3612 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3613 return isTetheringSupported();
3614 }
3615
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003616 // if ro.tether.denied = true we default to no tethering
3617 // gservices could set the secure setting to 1 though to enable it on a build where it
3618 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003619 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003620 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3621 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3622 Settings.Global.TETHER_SUPPORTED, defaultVal));
3623 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003624 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003625
3626 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3627 boolean adminUser = false;
3628 final long token = Binder.clearCallingIdentity();
3629 try {
3630 adminUser = mUserManager.isAdminUser();
3631 } finally {
3632 Binder.restoreCallingIdentity(token);
3633 }
3634
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003635 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003636 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003637
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003638 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003639 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3640 String callerPkg) {
3641 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003642 if (!isTetheringSupported()) {
3643 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3644 return;
3645 }
3646 mTethering.startTethering(type, receiver, showProvisioningUi);
3647 }
3648
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003649 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003650 public void stopTethering(int type, String callerPkg) {
3651 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003652 mTethering.stopTethering(type);
3653 }
3654
markchienf2731272019-01-16 17:44:13 +08003655 /**
3656 * Get the latest value of the tethering entitlement check.
3657 *
3658 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3659 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3660 * if it's really needed.
3661 */
3662 @Override
3663 public void getLatestTetheringEntitlementValue(int type, ResultReceiver receiver,
3664 boolean showEntitlementUi, String callerPkg) {
3665 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3666 mTethering.getLatestTetheringEntitlementValue(type, receiver, showEntitlementUi);
3667 }
3668
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003669 // Called when we lose the default network and have no replacement yet.
3670 // This will automatically be cleared after X seconds or a new default network
3671 // becomes CONNECTED, whichever happens first. The timer is started by the
3672 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003673 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003674 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003675 if (mNetTransitionWakeLock.isHeld()) {
3676 return;
3677 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003678 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003679 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3680 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003681 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003682 mWakelockLogs.log("ACQUIRE for " + forWhom);
3683 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3684 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003685 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003686
Hugo Benichi4c31b342017-03-30 23:18:10 +09003687 // Called when we gain a new default network to release the network transition wakelock in a
3688 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3689 // message is cancelled.
3690 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003691 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003692 if (!mNetTransitionWakeLock.isHeld()) {
3693 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003694 }
3695 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003696 // Cancel self timeout on wakelock hold.
3697 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3698 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3699 mHandler.sendMessageDelayed(msg, 1000);
3700 }
3701
3702 // Called when either message of ensureNetworkTransitionWakelock or
3703 // scheduleReleaseNetworkTransitionWakelock is processed.
3704 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3705 String event = eventName(eventId);
3706 synchronized (this) {
3707 if (!mNetTransitionWakeLock.isHeld()) {
3708 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3709 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3710 return;
3711 }
3712 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003713 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3714 mTotalWakelockDurationMs += lockDuration;
3715 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3716 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003717 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003718 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003719 }
3720
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003721 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003722 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003723 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003724 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003725 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003726 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003727 }
3728
Lorenzo Colitti18660282016-07-04 12:55:44 +09003729 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003730 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003731 enforceAccessPermission();
3732 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003733 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003734 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003735 mHandler.sendMessage(
3736 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3737 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003738
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003739 private void handleReportNetworkConnectivity(
3740 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003741 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003742 if (network == null) {
3743 nai = getDefaultNetwork();
3744 } else {
3745 nai = getNetworkAgentInfoForNetwork(network);
3746 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003747 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3748 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3749 return;
3750 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003751 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003752 if (hasConnectivity == nai.lastValidated) {
3753 return;
3754 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003755 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003756 int netid = nai.network.netId;
3757 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003758 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003759 // Validating a network that has not yet connected could result in a call to
3760 // rematchNetworkAndRequests() which is not meant to work on such networks.
3761 if (!nai.everConnected) {
3762 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003763 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003764 LinkProperties lp = getLinkProperties(nai);
3765 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3766 return;
3767 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003768 try {
3769 nai.networkMonitor().forceReevaluation(uid);
3770 } catch (RemoteException e) {
3771 e.rethrowFromSystemServer();
3772 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003773 }
3774
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003775 /**
3776 * Returns information about the proxy a certain network is using. If given a null network, it
3777 * it will return the proxy for the bound network for the caller app or the default proxy if
3778 * none.
3779 *
3780 * @param network the network we want to get the proxy information for.
3781 * @return Proxy information if a network has a proxy configured, or otherwise null.
3782 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09003783 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003784 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003785 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003786 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003787 if (network == null) {
3788 // Get the network associated with the calling UID.
3789 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
3790 true);
3791 if (activeNetwork == null) {
3792 return null;
3793 }
3794 return getLinkPropertiesProxyInfo(activeNetwork);
3795 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
3796 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3797 // caller may not have.
3798 return getLinkPropertiesProxyInfo(network);
3799 }
3800 // No proxy info available if the calling UID does not have network access.
3801 return null;
3802 }
3803
3804 @VisibleForTesting
3805 protected boolean queryUserAccess(int uid, int netId) {
3806 return NetworkUtils.queryUserAccess(uid, netId);
3807 }
3808
3809 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04003810 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3811 if (nai == null) return null;
3812 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003813 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
3814 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04003815 }
3816 }
3817
Chalard Jean3c443fc2018-06-07 18:37:59 +09003818 @Override
3819 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003820 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003821 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003822 }
3823
Chalard Jean5afbc832018-06-07 18:02:37 +09003824 @Override
3825 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003826 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003827 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003828 }
3829
Jason Monk207900c2014-04-25 15:00:09 -04003830 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003831 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003832 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003833 proxy = null;
3834 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003835 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003836 }
3837
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003838 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
3839 // when any network changes proxy.
3840 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
3841 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003842 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003843 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3844 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3845
Chalard Jean4949dd72018-06-07 17:41:29 +09003846 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09003847 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05003848 }
3849 }
3850
Robert Greenwalt434203a2010-10-11 16:00:27 -07003851 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003852 final private HashMap<Uri, Integer> mUriEventMap;
3853 final private Context mContext;
3854 final private Handler mHandler;
3855
3856 SettingsObserver(Context context, Handler handler) {
3857 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003858 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003859 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003860 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003861 }
3862
Erik Klineda4bfa82015-04-30 12:58:40 +09003863 void observe(Uri uri, int what) {
3864 mUriEventMap.put(uri, what);
3865 final ContentResolver resolver = mContext.getContentResolver();
3866 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003867 }
3868
3869 @Override
3870 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003871 Slog.wtf(TAG, "Should never be reached.");
3872 }
3873
3874 @Override
3875 public void onChange(boolean selfChange, Uri uri) {
3876 final Integer what = mUriEventMap.get(uri);
3877 if (what != null) {
3878 mHandler.obtainMessage(what.intValue()).sendToTarget();
3879 } else {
3880 loge("No matching event to send for URI=" + uri);
3881 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003882 }
3883 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003884
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003885 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003886 Slog.d(TAG, s);
3887 }
3888
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003889 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003890 Slog.e(TAG, s);
3891 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003892
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003893 private static void loge(String s, Throwable t) {
3894 Slog.e(TAG, s, t);
3895 }
3896
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003897 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003898 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003899 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3900 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3901 *
3902 * @param oldPackage Package name of the application which currently controls VPN, which will
3903 * be replaced. If there is no such application, this should should either be
3904 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3905 * @param newPackage Package name of the application which should gain control of VPN, or
3906 * {@code null} to disable.
3907 * @param userId User for whom to prepare the new VPN.
3908 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003909 * @hide
3910 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003911 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003912 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3913 int userId) {
3914 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003915
Hugo Benichi20035e02017-04-26 14:53:28 +09003916 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003917 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003918 Vpn vpn = mVpns.get(userId);
3919 if (vpn != null) {
3920 return vpn.prepare(oldPackage, newPackage);
3921 } else {
3922 return false;
3923 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003924 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003925 }
3926
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003927 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003928 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3929 * This method is used by system-privileged apps.
3930 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3931 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3932 *
3933 * @param packageName The package for which authorization state should change.
3934 * @param userId User for whom {@code packageName} is installed.
3935 * @param authorized {@code true} if this app should be able to start a VPN connection without
3936 * explicit user approval, {@code false} if not.
3937 *
Jeff Davidson05542602014-08-11 14:07:27 -07003938 * @hide
3939 */
3940 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003941 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3942 enforceCrossUserPermission(userId);
3943
Hugo Benichi20035e02017-04-26 14:53:28 +09003944 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003945 Vpn vpn = mVpns.get(userId);
3946 if (vpn != null) {
3947 vpn.setPackageAuthorization(packageName, authorized);
3948 }
Jeff Davidson05542602014-08-11 14:07:27 -07003949 }
3950 }
3951
3952 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003953 * Configure a TUN interface and return its file descriptor. Parameters
3954 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003955 * and not available in ConnectivityManager. Permissions are checked in
3956 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003957 * @hide
3958 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003959 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003960 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003961 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003962 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003963 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003964 return mVpns.get(user).establish(config);
3965 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003966 }
3967
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003968 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003969 * Start legacy VPN, controlling native daemons as needed. Creates a
3970 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003971 */
3972 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003973 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003974 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003975 final LinkProperties egress = getActiveLinkProperties();
3976 if (egress == null) {
3977 throw new IllegalStateException("Missing active network connection");
3978 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003979 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003980 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003981 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3982 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003983 }
3984
3985 /**
3986 * Return the information of the ongoing legacy VPN. This method is used
3987 * by VpnSettings and not available in ConnectivityManager. Permissions
3988 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003989 */
3990 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003991 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3992 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003993
Hugo Benichi20035e02017-04-26 14:53:28 +09003994 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003995 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003996 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003997 }
3998
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003999 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004000 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
4001 * and not available in ConnectivityManager.
4002 */
4003 @Override
4004 public VpnInfo[] getAllVpnInfo() {
4005 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09004006 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004007 if (mLockdownEnabled) {
4008 return new VpnInfo[0];
4009 }
4010
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004011 List<VpnInfo> infoList = new ArrayList<>();
4012 for (int i = 0; i < mVpns.size(); i++) {
4013 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4014 if (info != null) {
4015 infoList.add(info);
4016 }
4017 }
4018 return infoList.toArray(new VpnInfo[infoList.size()]);
4019 }
4020 }
4021
4022 /**
4023 * @return VPN information for accounting, or null if we can't retrieve all required
4024 * information, e.g primary underlying iface.
4025 */
4026 @Nullable
4027 private VpnInfo createVpnInfo(Vpn vpn) {
4028 VpnInfo info = vpn.getVpnInfo();
4029 if (info == null) {
4030 return null;
4031 }
4032 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4033 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4034 // the underlyingNetworks list.
4035 if (underlyingNetworks == null) {
4036 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4037 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4038 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4039 }
4040 } else if (underlyingNetworks.length > 0) {
4041 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4042 if (linkProperties != null) {
4043 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4044 }
4045 }
4046 return info.primaryUnderlyingIface == null ? null : info;
4047 }
4048
4049 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004050 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4051 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004052 * Permissions are checked in Vpn class.
4053 * @hide
4054 */
4055 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004056 public VpnConfig getVpnConfig(int userId) {
4057 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004058 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004059 Vpn vpn = mVpns.get(userId);
4060 if (vpn != null) {
4061 return vpn.getVpnConfig();
4062 } else {
4063 return null;
4064 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004065 }
4066 }
4067
Chalard Jean6b65ec72018-05-18 22:02:56 +09004068 /**
4069 * Ask all VPN objects to recompute and update their capabilities.
4070 *
4071 * When underlying networks change, VPNs may have to update capabilities to reflect things
4072 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4073 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4074 * handler thread through their agent, this is asynchronous. When the capabilities objects
4075 * are computed they will be up-to-date as they are computed synchronously from here and
4076 * this is running on the ConnectivityService thread.
4077 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
4078 */
4079 private void updateAllVpnsCapabilities() {
4080 synchronized (mVpns) {
4081 for (int i = 0; i < mVpns.size(); i++) {
4082 final Vpn vpn = mVpns.valueAt(i);
4083 vpn.updateCapabilities();
4084 }
4085 }
4086 }
4087
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004088 @Override
4089 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004090 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4091 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4092 return false;
4093 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004094
Hugo Benichi69744342017-11-27 10:57:16 +09004095 synchronized (mVpns) {
4096 // Tear down existing lockdown if profile was removed
4097 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4098 if (mLockdownEnabled) {
4099 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4100 if (profileTag == null) {
4101 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4102 return false;
4103 }
4104 String profileName = new String(profileTag);
4105 final VpnProfile profile = VpnProfile.decode(
4106 profileName, mKeyStore.get(Credentials.VPN + profileName));
4107 if (profile == null) {
4108 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4109 setLockdownTracker(null);
4110 return true;
4111 }
4112 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004113 Vpn vpn = mVpns.get(user);
4114 if (vpn == null) {
4115 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4116 return false;
4117 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004118 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004119 } else {
4120 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004121 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004122 }
4123
4124 return true;
4125 }
4126
4127 /**
4128 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4129 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4130 */
Hugo Benichi69744342017-11-27 10:57:16 +09004131 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004132 private void setLockdownTracker(LockdownVpnTracker tracker) {
4133 // Shutdown any existing tracker
4134 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004135 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4136 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004137 mLockdownTracker = null;
4138 if (existing != null) {
4139 existing.shutdown();
4140 }
4141
Robin Leec3736bc2017-03-10 16:19:54 +00004142 if (tracker != null) {
4143 mLockdownTracker = tracker;
4144 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004145 }
4146 }
4147
Hugo Benichi69744342017-11-27 10:57:16 +09004148 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004149 private void throwIfLockdownEnabled() {
4150 if (mLockdownEnabled) {
4151 throw new IllegalStateException("Unavailable in lockdown mode");
4152 }
4153 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004154
Robin Lee244ce8e2016-01-05 18:03:46 +00004155 /**
Robin Lee17e61832016-05-09 13:46:28 +01004156 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4157 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004158 *
Robin Lee17e61832016-05-09 13:46:28 +01004159 * @return {@code true} if the service was started, the service was already connected, or there
4160 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004161 */
Robin Lee17e61832016-05-09 13:46:28 +01004162 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004163 synchronized (mVpns) {
4164 Vpn vpn = mVpns.get(userId);
4165 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004166 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004167 // exists already.
4168 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4169 return false;
4170 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004171
Robin Lee812800c2016-05-13 15:38:08 +01004172 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004173 }
4174 }
4175
4176 @Override
Charles He36738632017-05-15 17:07:18 +01004177 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4178 enforceSettingsPermission();
4179 enforceCrossUserPermission(userId);
4180
4181 synchronized (mVpns) {
4182 Vpn vpn = mVpns.get(userId);
4183 if (vpn == null) {
4184 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4185 return false;
4186 }
4187 return vpn.isAlwaysOnPackageSupported(packageName);
4188 }
4189 }
4190
4191 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004192 public boolean setAlwaysOnVpnPackage(
4193 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4194 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004195 enforceCrossUserPermission(userId);
4196
Robin Lee244ce8e2016-01-05 18:03:46 +00004197 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004198 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4199 if (LockdownVpnTracker.isEnabled()) {
4200 return false;
4201 }
4202
Robin Lee244ce8e2016-01-05 18:03:46 +00004203 Vpn vpn = mVpns.get(userId);
4204 if (vpn == null) {
4205 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4206 return false;
4207 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004208 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004209 return false;
4210 }
Robin Lee17e61832016-05-09 13:46:28 +01004211 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004212 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004213 return false;
4214 }
4215 }
4216 return true;
4217 }
4218
4219 @Override
4220 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004221 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004222 enforceCrossUserPermission(userId);
4223
4224 synchronized (mVpns) {
4225 Vpn vpn = mVpns.get(userId);
4226 if (vpn == null) {
4227 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4228 return null;
4229 }
4230 return vpn.getAlwaysOnPackage();
4231 }
4232 }
4233
Wink Savilleab9321d2013-06-29 21:10:57 -07004234 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004235 public boolean isVpnLockdownEnabled(int userId) {
4236 enforceControlAlwaysOnVpnPermission();
4237 enforceCrossUserPermission(userId);
4238
4239 synchronized (mVpns) {
4240 Vpn vpn = mVpns.get(userId);
4241 if (vpn == null) {
4242 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4243 return false;
4244 }
4245 return vpn.getLockdown();
4246 }
4247 }
4248
4249 @Override
4250 public List<String> getVpnLockdownWhitelist(int userId) {
4251 enforceControlAlwaysOnVpnPermission();
4252 enforceCrossUserPermission(userId);
4253
4254 synchronized (mVpns) {
4255 Vpn vpn = mVpns.get(userId);
4256 if (vpn == null) {
4257 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4258 return null;
4259 }
4260 return vpn.getLockdownWhitelist();
4261 }
4262 }
4263
4264 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004265 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004266 // TODO: Remove? Any reason to trigger a provisioning check?
4267 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004268 }
4269
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004270 /** Location to an updatable file listing carrier provisioning urls.
4271 * An example:
4272 *
4273 * <?xml version="1.0" encoding="utf-8"?>
4274 * <provisioningUrls>
4275 * <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 -07004276 * </provisioningUrls>
4277 */
4278 private static final String PROVISIONING_URL_PATH =
4279 "/data/misc/radio/provisioning_urls.xml";
4280 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004281
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004282 /** XML tag for root element. */
4283 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4284 /** XML tag for individual url */
4285 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004286 /** XML attribute for mcc */
4287 private static final String ATTR_MCC = "mcc";
4288 /** XML attribute for mnc */
4289 private static final String ATTR_MNC = "mnc";
4290
Paul Jensen434dde82015-06-11 09:43:30 -04004291 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004292 FileReader fileReader = null;
4293 XmlPullParser parser = null;
4294 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004295
4296 try {
4297 fileReader = new FileReader(mProvisioningUrlFile);
4298 parser = Xml.newPullParser();
4299 parser.setInput(fileReader);
4300 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4301
4302 while (true) {
4303 XmlUtils.nextElement(parser);
4304
4305 String element = parser.getName();
4306 if (element == null) break;
4307
Paul Jensen434dde82015-06-11 09:43:30 -04004308 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004309 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4310 try {
4311 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4312 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4313 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4314 parser.next();
4315 if (parser.getEventType() == XmlPullParser.TEXT) {
4316 return parser.getText();
4317 }
4318 }
4319 }
4320 } catch (NumberFormatException e) {
4321 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4322 }
4323 }
4324 }
4325 return null;
4326 } catch (FileNotFoundException e) {
4327 loge("Carrier Provisioning Urls file not found");
4328 } catch (XmlPullParserException e) {
4329 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4330 } catch (IOException e) {
4331 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4332 } finally {
4333 if (fileReader != null) {
4334 try {
4335 fileReader.close();
4336 } catch (IOException e) {}
4337 }
4338 }
4339 return null;
4340 }
4341
Wink Saville42d4f082013-07-20 20:31:59 -07004342 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004343 public String getMobileProvisioningUrl() {
4344 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004345 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004346 if (TextUtils.isEmpty(url)) {
4347 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004348 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004349 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004350 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004351 }
Wink Saville8cf35602013-07-10 23:00:07 -07004352 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004353 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004354 String phoneNumber = mTelephonyManager.getLine1Number();
4355 if (TextUtils.isEmpty(phoneNumber)) {
4356 phoneNumber = "0000000000";
4357 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004358 url = String.format(url,
4359 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4360 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004361 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004362 }
4363
Wink Savilleab9321d2013-06-29 21:10:57 -07004364 return url;
4365 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004366
Wink Saville948282b2013-08-29 08:55:16 -07004367 @Override
4368 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004369 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004370 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004371 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4372 return;
4373 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004374 final long ident = Binder.clearCallingIdentity();
4375 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004376 // Concatenate the range of types onto the range of NetIDs.
4377 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4378 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004379 } finally {
4380 Binder.restoreCallingIdentity(ident);
4381 }
Wink Saville948282b2013-08-29 08:55:16 -07004382 }
Wink Saville7788c612013-08-29 14:57:08 -07004383
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004384 @Override
4385 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004386 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004387 final long ident = Binder.clearCallingIdentity();
4388 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004389 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004390 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004391 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4392 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004393 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004394 } finally {
4395 Binder.restoreCallingIdentity(ident);
4396 }
4397 }
4398
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004399 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004400 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004401 Vpn userVpn = mVpns.get(userId);
4402 if (userVpn != null) {
4403 loge("Starting user already has a VPN");
4404 return;
4405 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004406 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004407 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004408 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4409 updateLockdownVpn();
4410 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004411 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004412 }
4413
4414 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004415 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004416 Vpn userVpn = mVpns.get(userId);
4417 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004418 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004419 return;
4420 }
Robin Lee17e61832016-05-09 13:46:28 +01004421 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004422 mVpns.delete(userId);
4423 }
4424 }
4425
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004426 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004427 mPermissionMonitor.onUserAdded(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004428 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004429 final int vpnsSize = mVpns.size();
4430 for (int i = 0; i < vpnsSize; i++) {
4431 Vpn vpn = mVpns.valueAt(i);
4432 vpn.onUserAdded(userId);
4433 }
4434 }
4435 }
4436
4437 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004438 mPermissionMonitor.onUserRemoved(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004439 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004440 final int vpnsSize = mVpns.size();
4441 for (int i = 0; i < vpnsSize; i++) {
4442 Vpn vpn = mVpns.valueAt(i);
4443 vpn.onUserRemoved(userId);
4444 }
4445 }
4446 }
4447
junyulai2454b692018-11-01 17:16:31 +08004448 private void onPackageAdded(String packageName, int uid) {
4449 if (TextUtils.isEmpty(packageName) || uid < 0) {
4450 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4451 return;
4452 }
4453 mPermissionMonitor.onPackageAdded(packageName, uid);
4454 }
4455
junyulaiefb04d32018-11-12 22:39:30 +08004456 private void onPackageReplaced(String packageName, int uid) {
4457 if (TextUtils.isEmpty(packageName) || uid < 0) {
4458 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4459 return;
4460 }
4461 final int userId = UserHandle.getUserId(uid);
4462 synchronized (mVpns) {
4463 final Vpn vpn = mVpns.get(userId);
4464 if (vpn == null) {
4465 return;
4466 }
4467 // Legacy always-on VPN won't be affected since the package name is not set.
4468 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4469 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4470 + userId);
4471 vpn.startAlwaysOnVpn();
4472 }
4473 }
4474 }
4475
4476 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004477 if (TextUtils.isEmpty(packageName) || uid < 0) {
4478 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4479 return;
4480 }
4481 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004482
4483 final int userId = UserHandle.getUserId(uid);
4484 synchronized (mVpns) {
4485 final Vpn vpn = mVpns.get(userId);
4486 if (vpn == null) {
4487 return;
4488 }
4489 // Legacy always-on VPN won't be affected since the package name is not set.
4490 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4491 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4492 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004493 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004494 }
4495 }
junyulai2454b692018-11-01 17:16:31 +08004496 }
4497
Robin Lee89e7a692016-02-29 14:38:17 +00004498 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004499 synchronized (mVpns) {
4500 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4501 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4502 updateLockdownVpn();
4503 } else {
4504 startAlwaysOnVpn(userId);
4505 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004506 }
4507 }
4508
junyulai2454b692018-11-01 17:16:31 +08004509 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004510 @Override
4511 public void onReceive(Context context, Intent intent) {
4512 final String action = intent.getAction();
4513 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004514 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4515 final Uri packageData = intent.getData();
4516 final String packageName =
4517 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004518 if (userId == UserHandle.USER_NULL) return;
4519
Robin Lee323f29d2016-05-04 16:38:06 +01004520 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004521 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004522 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004523 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004524 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4525 onUserAdded(userId);
4526 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4527 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004528 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4529 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004530 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4531 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004532 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4533 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004534 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004535 final boolean isReplacing = intent.getBooleanExtra(
4536 Intent.EXTRA_REPLACING, false);
4537 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004538 }
4539 }
4540 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004541
Robin Lee95204e02017-01-27 11:59:22 +00004542 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4543 @Override
4544 public void onReceive(Context context, Intent intent) {
4545 // Try creating lockdown tracker, since user present usually means
4546 // unlocked keystore.
4547 updateLockdownVpn();
4548 mContext.unregisterReceiver(this);
4549 }
4550 };
4551
Chalard Jean4133a122018-06-04 13:33:12 +09004552 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4553 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004554
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004555 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4556 // Map from UID to number of NetworkRequests that UID has filed.
4557 @GuardedBy("mUidToNetworkRequestCount")
4558 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4559
Robert Greenwalta67be032014-05-16 15:49:14 -07004560 private static class NetworkFactoryInfo {
4561 public final String name;
4562 public final Messenger messenger;
4563 public final AsyncChannel asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004564 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004565
Chalard Jean08577fc2018-05-02 21:14:54 +09004566 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4567 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004568 this.name = name;
4569 this.messenger = messenger;
4570 this.asyncChannel = asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004571 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004572 }
4573 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004574
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004575 private void ensureNetworkRequestHasType(NetworkRequest request) {
4576 if (request.type == NetworkRequest.Type.NONE) {
4577 throw new IllegalArgumentException(
4578 "All NetworkRequests in ConnectivityService must have a type");
4579 }
4580 }
4581
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004582 /**
4583 * Tracks info about the requester.
4584 * Also used to notice when the calling process dies so we can self-expire
4585 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004586 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004587 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004588 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004589 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004590 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004591 final int mPid;
4592 final int mUid;
4593 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004594
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004595 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004596 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004597 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004598 mPendingIntent = pi;
4599 messenger = null;
4600 mBinder = null;
4601 mPid = getCallingPid();
4602 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004603 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004604 }
4605
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004606 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004607 super();
4608 messenger = m;
4609 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004610 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004611 mBinder = binder;
4612 mPid = getCallingPid();
4613 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004614 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004615 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004616
4617 try {
4618 mBinder.linkToDeath(this, 0);
4619 } catch (RemoteException e) {
4620 binderDied();
4621 }
4622 }
4623
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004624 private void enforceRequestCountLimit() {
4625 synchronized (mUidToNetworkRequestCount) {
4626 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4627 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004628 throw new ServiceSpecificException(
4629 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004630 }
4631 mUidToNetworkRequestCount.put(mUid, networkRequests);
4632 }
4633 }
4634
Robert Greenwalt9258c642014-03-26 16:47:06 -07004635 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004636 if (mBinder != null) {
4637 mBinder.unlinkToDeath(this, 0);
4638 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004639 }
4640
4641 public void binderDied() {
4642 log("ConnectivityService NetworkRequestInfo binderDied(" +
4643 request + ", " + mBinder + ")");
4644 releaseNetworkRequest(request);
4645 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004646
4647 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004648 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004649 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004650 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004651 }
4652
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004653 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4654 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4655 if (badCapability != null) {
4656 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004657 }
4658 }
4659
Chalard Jeanb03a6222018-04-11 21:09:10 +09004660 // This checks that the passed capabilities either do not request a specific SSID, or the
4661 // calling app has permission to do so.
4662 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4663 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004664 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004665 throw new SecurityException("Insufficient permissions to request a specific SSID");
4666 }
4667 }
4668
Erik Kline9d598e12015-07-13 16:37:51 +09004669 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004670 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004671 synchronized (nai) {
4672 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4673 if (nri.request.networkCapabilities.hasSignalStrength() &&
4674 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4675 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4676 }
4677 }
4678 }
Chalard Jean4133a122018-06-04 13:33:12 +09004679 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004680 }
4681
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004682 private void updateSignalStrengthThresholds(
4683 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4684 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004685 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004686 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4687
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004688 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004689 String detail;
4690 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4691 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4692 } else {
4693 detail = reason;
4694 }
4695 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4696 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4697 }
4698
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004699 nai.asyncChannel.sendMessage(
4700 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004701 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004702 }
4703
Etan Cohen859748f2017-04-03 17:42:34 -07004704 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4705 if (nc == null) {
4706 return;
4707 }
4708 NetworkSpecifier ns = nc.getNetworkSpecifier();
4709 if (ns == null) {
4710 return;
4711 }
4712 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4713 ns.assertValidFromUid(Binder.getCallingUid());
4714 }
4715
Robert Greenwalt9258c642014-03-26 16:47:06 -07004716 @Override
4717 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004718 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004719 final NetworkRequest.Type type = (networkCapabilities == null)
4720 ? NetworkRequest.Type.TRACK_DEFAULT
4721 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004722 // If the requested networkCapabilities is null, take them instead from
4723 // the default network request. This allows callers to keep track of
4724 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004725 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004726 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004727 enforceAccessPermission();
4728 } else {
4729 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4730 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004731 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4732 // of the app when the request is filed, but we never change the request if the app
4733 // changes network state. http://b/29964605
4734 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004735 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004736 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004737 ensureSufficientPermissionsForRequest(networkCapabilities,
4738 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004739 // Set the UID range for this request to the single UID of the requester, or to an empty
4740 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004741 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4742 // are no visible methods to set the UIDs, an app could use reflection to try and get
4743 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004744 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004745
Etan Cohenba07c8c2017-02-05 10:42:27 -08004746 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004747 throw new IllegalArgumentException("Bad timeout specified");
4748 }
Etan Cohen859748f2017-04-03 17:42:34 -07004749 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004750
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004751 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004752 nextNetworkRequestId(), type);
4753 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004754 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004755
4756 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004757 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004758 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004759 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004760 }
4761 return networkRequest;
4762 }
4763
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004764 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004765 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004766 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004767 } else {
4768 enforceChangePermission();
4769 }
4770 }
4771
fenglub15e72b2015-03-20 11:29:56 -07004772 @Override
fengludb571472015-04-21 17:12:05 -07004773 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004774 enforceAccessPermission();
4775 NetworkAgentInfo nai = null;
4776 if (network == null) {
4777 return false;
4778 }
4779 synchronized (mNetworkForNetId) {
4780 nai = mNetworkForNetId.get(network.netId);
4781 }
4782 if (nai != null) {
4783 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004784 synchronized (mBandwidthRequests) {
4785 final int uid = Binder.getCallingUid();
4786 Integer uidReqs = mBandwidthRequests.get(uid);
4787 if (uidReqs == null) {
4788 uidReqs = new Integer(0);
4789 }
4790 mBandwidthRequests.put(uid, ++uidReqs);
4791 }
fenglub15e72b2015-03-20 11:29:56 -07004792 return true;
4793 }
4794 return false;
4795 }
4796
Felipe Lemeee27cab2016-06-20 16:36:29 -07004797 private boolean isSystem(int uid) {
4798 return uid < Process.FIRST_APPLICATION_UID;
4799 }
fenglub15e72b2015-03-20 11:29:56 -07004800
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004801 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004802 final int uid = Binder.getCallingUid();
4803 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004804 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004805 return;
4806 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004807 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4808 // Policy already enforced.
4809 return;
4810 }
4811 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4812 // If UID is restricted, don't allow them to bring up metered APNs.
4813 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004814 }
4815 }
4816
Robert Greenwalt9258c642014-03-26 16:47:06 -07004817 @Override
4818 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4819 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004820 checkNotNull(operation, "PendingIntent cannot be null.");
4821 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4822 enforceNetworkRequestPermissions(networkCapabilities);
4823 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004824 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004825 ensureSufficientPermissionsForRequest(networkCapabilities,
4826 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004827 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004828 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004829
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004830 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004831 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4832 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004833 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004834 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4835 nri));
4836 return networkRequest;
4837 }
4838
Jeremy Joslin79294842014-12-03 17:15:28 -08004839 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4840 mHandler.sendMessageDelayed(
4841 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4842 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4843 }
4844
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004845 @Override
4846 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004847 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004848 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4849 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004850 }
4851
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004852 // In order to implement the compatibility measure for pre-M apps that call
4853 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4854 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4855 // This ensures it has permission to do so.
4856 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4857 if (nc == null) {
4858 return false;
4859 }
4860 int[] transportTypes = nc.getTransportTypes();
4861 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4862 return false;
4863 }
4864 try {
4865 mContext.enforceCallingOrSelfPermission(
4866 android.Manifest.permission.ACCESS_WIFI_STATE,
4867 "ConnectivityService");
4868 } catch (SecurityException e) {
4869 return false;
4870 }
4871 return true;
4872 }
4873
Robert Greenwalt9258c642014-03-26 16:47:06 -07004874 @Override
4875 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4876 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004877 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4878 enforceAccessPermission();
4879 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004880
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004881 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004882 ensureSufficientPermissionsForRequest(networkCapabilities,
4883 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004884 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004885 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4886 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4887 // onLost and onAvailable callbacks when networks move in and out of the background.
4888 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4889 // can't request networks.
4890 restrictBackgroundRequestForCaller(nc);
4891 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004892
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004893 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004894 NetworkRequest.Type.LISTEN);
4895 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004896 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004897
4898 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4899 return networkRequest;
4900 }
4901
4902 @Override
4903 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4904 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004905 checkNotNull(operation, "PendingIntent cannot be null.");
4906 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4907 enforceAccessPermission();
4908 }
Etan Cohen859748f2017-04-03 17:42:34 -07004909 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004910 ensureSufficientPermissionsForRequest(networkCapabilities,
4911 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004912
Chalard Jeandda156a2018-01-10 21:19:32 +09004913 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004914 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004915
4916 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004917 NetworkRequest.Type.LISTEN);
4918 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004919 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004920
4921 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004922 }
4923
Erik Klineacdd6392016-07-07 16:50:58 +09004924 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004925 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004926 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004927 mHandler.sendMessage(mHandler.obtainMessage(
4928 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004929 }
4930
4931 @Override
Chalard Jean08577fc2018-05-02 21:14:54 +09004932 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004933 enforceConnectivityInternalPermission();
Chalard Jean08577fc2018-05-02 21:14:54 +09004934 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
4935 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07004936 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean08577fc2018-05-02 21:14:54 +09004937 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07004938 }
4939
Robert Greenwalta67be032014-05-16 15:49:14 -07004940 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004941 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004942 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4943 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4944 }
4945
4946 @Override
4947 public void unregisterNetworkFactory(Messenger messenger) {
4948 enforceConnectivityInternalPermission();
4949 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4950 }
4951
4952 private void handleUnregisterNetworkFactory(Messenger messenger) {
4953 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4954 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004955 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004956 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004957 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004958 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004959 }
4960
Robert Greenwalt7b816022014-04-18 15:25:25 -07004961 /**
4962 * NetworkAgentInfo supporting a request by requestId.
4963 * These have already been vetted (their Capabilities satisfy the request)
4964 * and the are the highest scored network available.
4965 * the are keyed off the Requests requestId.
4966 */
Hugo Benichicd952782017-09-20 11:20:14 +09004967 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4968 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004969 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004970
Paul Jensen31a94f42015-02-13 14:18:39 -05004971 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4972 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004973 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004974 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4975 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4976 // there may not be a strict 1:1 correlation between the two.
4977 @GuardedBy("mNetworkForNetId")
4978 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004979
Robert Greenwalt7b816022014-04-18 15:25:25 -07004980 // NetworkAgentInfo keyed off its connecting messenger
4981 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004982 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004983 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004984
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004985 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004986 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004987
Paul Jensen2c311d62014-11-17 12:34:51 -05004988 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004989 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004990
Erik Klineda4bfa82015-04-30 12:58:40 +09004991 // Request used to optionally keep mobile data active even when higher
4992 // priority networks like Wi-Fi are active.
4993 private final NetworkRequest mDefaultMobileDataRequest;
4994
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004995 // Request used to optionally keep wifi data active even when higher
4996 // priority networks like ethernet are active.
4997 private final NetworkRequest mDefaultWifiRequest;
4998
Hugo Benichicd952782017-09-20 11:20:14 +09004999 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5000 synchronized (mNetworkForRequestId) {
5001 return mNetworkForRequestId.get(requestId);
5002 }
5003 }
5004
5005 private void clearNetworkForRequest(int requestId) {
5006 synchronized (mNetworkForRequestId) {
5007 mNetworkForRequestId.remove(requestId);
5008 }
5009 }
5010
5011 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5012 synchronized (mNetworkForRequestId) {
5013 mNetworkForRequestId.put(requestId, nai);
5014 }
5015 }
5016
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005017 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005018 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005019 }
5020
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005021 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005022 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005023 }
5024
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005025 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5026 return nri.request.requestId == mDefaultRequest.requestId;
5027 }
5028
Chalard Jean08577fc2018-05-02 21:14:54 +09005029 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5030 // changes that would conflict throughout the automerger graph. Having this method temporarily
5031 // helps with the process of going through with all these dependent changes across the entire
5032 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005033 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005034 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005035 int currentScore, NetworkMisc networkMisc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005036 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5037 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5038 }
5039
5040 /**
5041 * Register a new agent with ConnectivityService to handle a network.
5042 *
5043 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5044 * @param networkInfo the initial info associated with this network. It can be updated later :
5045 * see {@link #updateNetworkInfo}.
5046 * @param linkProperties the initial link properties of this network. They can be updated
5047 * later : see {@link #updateLinkProperties}.
5048 * @param networkCapabilities the initial capabilites of this network. They can be updated
5049 * later : see {@link #updateNetworkCapabilities}.
5050 * @param currentScore the initial score of the network. See
5051 * {@link NetworkAgentInfo#getCurrentScore}.
5052 * @param networkMisc metadata about the network. This is never updated.
5053 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5054 */
5055 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5056 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5057 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005058 enforceConnectivityInternalPermission();
5059
Rubin Xu1bb5c082017-09-05 18:40:49 +01005060 LinkProperties lp = new LinkProperties(linkProperties);
5061 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005062 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5063 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005064 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005065 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005066 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean08577fc2018-05-02 21:14:54 +09005067 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5068 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005069 // Make sure the network capabilities reflect what the agent info says.
5070 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005071 final String extraInfo = networkInfo.getExtraInfo();
5072 final String name = TextUtils.isEmpty(extraInfo)
5073 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005074 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005075 final long token = Binder.clearCallingIdentity();
5076 try {
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +09005077 mContext.getSystemService(NetworkStack.class).makeNetworkMonitor(
5078 toStableParcelable(nai.network), name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005079 } finally {
5080 Binder.restoreCallingIdentity(token);
5081 }
5082 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5083 // If the network disconnects or sends any other event before that, messages are deferred by
5084 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5085 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005086 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005087 }
5088
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005089 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5090 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005091 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005092 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005093 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005094 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005095 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005096 synchronized (this) {
5097 if (mSystemReady) {
5098 try {
5099 networkMonitor.notifySystemReady();
5100 } catch (RemoteException e) {
5101 e.rethrowFromSystemServer();
5102 }
5103 }
5104 }
5105
5106 try {
5107 networkMonitor.start();
5108 } catch (RemoteException e) {
5109 e.rethrowFromSystemServer();
5110 }
Erik Klinee5dac902018-03-04 21:01:01 +09005111 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5112 NetworkInfo networkInfo = nai.networkInfo;
5113 nai.networkInfo = null;
5114 updateNetworkInfo(nai, networkInfo);
5115 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005116 }
5117
lucaslin25a4ec32018-11-28 12:51:55 +08005118 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5119 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005120 int netId = networkAgent.network.netId;
5121
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005122 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
5123 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09005124 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08005125 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09005126 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005127
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005128 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005129 updateMtu(newLp, oldLp);
5130 // TODO - figure out what to do for clat
5131// for (LinkProperties lp : newLp.getStackedLinks()) {
5132// updateMtu(lp, null);
5133// }
lucaslin041a1af2018-11-28 19:27:52 +08005134 if (isDefaultNetwork(networkAgent)) {
5135 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5136 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005137
Erik Kline94887872016-04-05 13:30:49 +09005138 updateRoutes(newLp, oldLp, netId);
5139 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005140 // Make sure LinkProperties represents the latest private DNS status.
5141 // This does not need to be done before updateDnses because the
5142 // LinkProperties are not the source of the private DNS configuration.
5143 // updateDnses will fetch the private DNS configuration from DnsManager.
5144 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005145
Paul Jensene0bef712014-12-10 15:12:18 -05005146 if (isDefaultNetwork(networkAgent)) {
5147 handleApplyDefaultProxy(newLp.getHttpProxy());
5148 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005149 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005150 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005151 // TODO - move this check to cover the whole function
5152 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005153 synchronized (networkAgent) {
5154 networkAgent.linkProperties = newLp;
5155 }
lucaslin25a4ec32018-11-28 12:51:55 +08005156 // Start or stop clat accordingly to network state.
5157 networkAgent.updateClat(mNMS);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005158 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005159 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005160 try {
5161 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5162 } catch (RemoteException e) {
5163 e.rethrowFromSystemServer();
5164 }
lucaslin25a4ec32018-11-28 12:51:55 +08005165 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5166 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005167 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005168
5169 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005170 }
5171
Joel Scherpelz668370b2017-06-08 15:35:21 +09005172 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005173 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005174 // marks on unsupported interfaces is harmless.
5175 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5176 return;
5177 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005178
Joel Scherpelz668370b2017-06-08 15:35:21 +09005179 int mark = mContext.getResources().getInteger(
5180 com.android.internal.R.integer.config_networkWakeupPacketMark);
5181 int mask = mContext.getResources().getInteger(
5182 com.android.internal.R.integer.config_networkWakeupPacketMask);
5183
5184 // Mask/mark of zero will not detect anything interesting.
5185 // Don't install rules unless both values are nonzero.
5186 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005187 return;
5188 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005189
5190 final String prefix = "iface:" + iface;
5191 try {
5192 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005193 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005194 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005195 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005196 }
5197 } catch (Exception e) {
5198 loge("Exception modifying wakeup packet monitoring: " + e);
5199 }
5200
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005201 }
5202
5203 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5204 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005205 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005206 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5207 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005208 for (String iface : interfaceDiff.added) {
5209 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005210 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005211 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005212 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005213 } catch (Exception e) {
5214 loge("Exception adding interface: " + e);
5215 }
5216 }
5217 for (String iface : interfaceDiff.removed) {
5218 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005219 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005220 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005221 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005222 } catch (Exception e) {
5223 loge("Exception removing interface: " + e);
5224 }
5225 }
5226 }
5227
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005228 /**
5229 * Have netd update routes from oldLp to newLp.
5230 * @return true if routes changed between oldLp and newLp
5231 */
5232 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005233 // Compare the route diff to determine which routes should be added and removed.
5234 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5235 oldLp != null ? oldLp.getAllRoutes() : null,
5236 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005237
5238 // add routes before removing old in case it helps with continuous connectivity
5239
Chalard Jean4d660112018-06-04 16:52:49 +09005240 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005241 for (RouteInfo route : routeDiff.added) {
5242 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005243 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005244 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005245 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005246 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005247 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5248 loge("Exception in addRoute for non-gateway: " + e);
5249 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005250 }
5251 }
5252 for (RouteInfo route : routeDiff.added) {
5253 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005254 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005255 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005256 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005257 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005258 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5259 loge("Exception in addRoute for gateway: " + e);
5260 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005261 }
5262 }
5263
5264 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005265 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005266 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005267 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005268 } catch (Exception e) {
5269 loge("Exception in removeRoute: " + e);
5270 }
5271 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005272 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005273 }
Erik Kline41368502015-06-17 13:19:54 +09005274
Erik Kline94887872016-04-05 13:30:49 +09005275 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5276 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5277 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005278 }
Erik Kline94887872016-04-05 13:30:49 +09005279
Erik Kline1742fe12017-12-13 19:40:49 +09005280 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5281 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5282
Erik Klinea24d4592018-01-11 21:07:29 +09005283 if (DBG) {
5284 final Collection<InetAddress> dnses = newLp.getDnsServers();
5285 log("Setting DNS servers for network " + netId + " to " + dnses);
5286 }
Erik Kline94887872016-04-05 13:30:49 +09005287 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005288 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005289 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005290 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005291 }
Erik Kline4edba012017-04-07 15:29:29 +09005292 }
5293
Luke Huang8a462ec2018-08-24 20:33:16 +08005294 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005295 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005296 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005297 }
5298 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005299 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005300 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005301 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005302 }
5303
Paul Jensen3d194ea2015-06-16 14:27:36 -04005304 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005305 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5306 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5307 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005308 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005309 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005310 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005311 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5312 // causing a connect/teardown loop.
5313 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5314 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005315 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005316 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005317 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5318 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005319 // does not cause any request (that is not a listen) currently matching that agent to
5320 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005321 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005322 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005323 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005324 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005325 }
5326
Paul Jensen3d194ea2015-06-16 14:27:36 -04005327 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005328 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005329 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005330 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005331 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005332 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005333 }
Paul Jensene0988542015-06-25 15:30:08 -04005334 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005335 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005336 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005337 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005338 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005339 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005340 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005341 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005342 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005343 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005344 if (nai.isSuspended()) {
5345 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5346 } else {
5347 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5348 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005349
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005350 return newNc;
5351 }
5352
5353 /**
5354 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5355 *
5356 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5357 * capabilities we manage and store in {@code nai}, such as validated status and captive
5358 * portal status)
5359 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5360 * potentially triggers rematches.
5361 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5362 * change.)
5363 *
5364 * @param oldScore score of the network before any of the changes that prompted us
5365 * to call this function.
5366 * @param nai the network having its capabilities updated.
5367 * @param nc the new network capabilities.
5368 */
5369 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5370 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5371
5372 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005373
Luke Huang8a462ec2018-08-24 20:33:16 +08005374 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5375 final int newPermission = getNetworkPermission(newNc);
5376 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005377 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005378 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005379 } catch (RemoteException e) {
5380 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005381 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005382 }
5383
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005384 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005385 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005386 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005387 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005388 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005389
Chalard Jeanf213ca12018-01-16 18:43:05 +09005390 updateUids(nai, prevNc, newNc);
5391
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005392 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005393 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5394 // the change we're processing can't affect any requests, it can only affect the listens
5395 // on this network. We might have been called by rematchNetworkAndRequests when a
5396 // network changed foreground state.
5397 processListenRequests(nai, true);
5398 } else {
5399 // If the requestable capabilities have changed or the score changed, we can't have been
5400 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005401 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005402 try {
5403 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5404 } catch (RemoteException e) {
5405 e.rethrowFromSystemServer();
5406 }
Paul Jensene0988542015-06-25 15:30:08 -04005407 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005408 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005409
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005410 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005411 final boolean oldMetered = prevNc.isMetered();
5412 final boolean newMetered = newNc.isMetered();
5413 final boolean meteredChanged = oldMetered != newMetered;
5414
5415 if (meteredChanged) {
5416 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5417 mRestrictBackground);
5418 }
5419
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005420 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005421 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005422
5423 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005424 if (meteredChanged || roamingChanged) {
5425 notifyIfacesChangedForNetworkStats();
5426 }
5427 }
5428
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005429 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005430 // Tell VPNs about updated capabilities, since they may need to
5431 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005432 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005433 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005434 }
5435
Chalard Jeanf213ca12018-01-16 18:43:05 +09005436 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5437 NetworkCapabilities newNc) {
5438 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5439 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5440 if (null == prevRanges) prevRanges = new ArraySet<>();
5441 if (null == newRanges) newRanges = new ArraySet<>();
5442 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5443
5444 prevRanges.removeAll(newRanges);
5445 newRanges.removeAll(prevRangesCopy);
5446
5447 try {
5448 if (!newRanges.isEmpty()) {
5449 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5450 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005451 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005452 }
5453 if (!prevRanges.isEmpty()) {
5454 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5455 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005456 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005457 }
5458 } catch (Exception e) {
5459 // Never crash!
5460 loge("Exception in updateUids: " + e);
5461 }
5462 }
5463
Hugo Benichief502882017-09-01 01:23:32 +00005464 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07005465 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005466 // Ignore updates for disconnected networks
5467 return;
5468 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005469 // newLp is already a defensive copy.
5470 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005471 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005472 log("Update of LinkProperties for " + nai.name() +
5473 "; created=" + nai.created +
5474 "; everConnected=" + nai.everConnected);
5475 }
lucaslin25a4ec32018-11-28 12:51:55 +08005476 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005477 }
5478
Paul Jensenc8b9a742014-09-30 15:37:41 -04005479 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005480 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5481 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005482 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005483 if (nr.isListen()) continue;
Chalard Jean08577fc2018-05-02 21:14:54 +09005484 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005485 }
5486 }
5487
Chalard Jean08577fc2018-05-02 21:14:54 +09005488 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5489 int score = 0;
5490 int serial = 0;
5491 if (nai != null) {
5492 score = nai.getCurrentScore();
5493 serial = nai.factorySerialNumber;
5494 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005495 if (VDBG || DDBG){
5496 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5497 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005498 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005499 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5500 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005501 }
5502 }
5503
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005504 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5505 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005506 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005507 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005508 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5509 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005510 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005511 sendIntent(nri.mPendingIntent, intent);
5512 }
5513 // else not handled
5514 }
5515
5516 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5517 mPendingIntentWakeLock.acquire();
5518 try {
5519 if (DBG) log("Sending " + pendingIntent);
5520 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5521 } catch (PendingIntent.CanceledException e) {
5522 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5523 mPendingIntentWakeLock.release();
5524 releasePendingNetworkRequest(pendingIntent);
5525 }
5526 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5527 }
5528
5529 @Override
5530 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5531 String resultData, Bundle resultExtras) {
5532 if (DBG) log("Finished sending " + pendingIntent);
5533 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005534 // Release with a delay so the receiving client has an opportunity to put in its
5535 // own request.
5536 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005537 }
5538
Chalard Jeanf19db372018-01-26 19:24:40 +09005539 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005540 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005541 if (nri.messenger == null) {
5542 return; // Default request has no msgr
5543 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005544 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005545 // TODO: check if defensive copies of data is needed.
5546 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005547 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005548 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5549 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005550 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005551 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005552 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005553 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5554 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005555 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005556 // For this notification, arg1 contains the blocked status.
5557 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005558 break;
5559 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005560 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005561 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005562 break;
5563 }
5564 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005565 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005566 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005567 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005568 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005569 break;
5570 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005571 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005572 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005573 break;
5574 }
junyulai05986c62018-08-07 19:50:45 +08005575 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005576 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005577 msg.arg1 = arg1;
5578 break;
5579 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005580 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005581 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005582 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005583 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005584 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005585 String notification = ConnectivityManager.getCallbackName(notificationType);
5586 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005587 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005588 nri.messenger.send(msg);
5589 } catch (RemoteException e) {
5590 // may occur naturally in the race of binder death.
5591 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5592 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005593 }
5594
Hugo Benichidba33db2017-03-23 22:40:44 +09005595 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5596 bundle.putParcelable(t.getClass().getSimpleName(), t);
5597 }
5598
Paul Jensenc8b9a742014-09-30 15:37:41 -04005599 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005600 if (nai.numRequestNetworkRequests() != 0) {
5601 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5602 NetworkRequest nr = nai.requestAt(i);
5603 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005604 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005605 loge("Dead network still had at least " + nr);
5606 break;
5607 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005608 }
5609 nai.asyncChannel.disconnect();
5610 }
5611
Robert Greenwalt7b816022014-04-18 15:25:25 -07005612 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5613 if (oldNetwork == null) {
5614 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5615 return;
5616 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005617 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005618
5619 // If we get here it means that the last linger timeout for this network expired. So there
5620 // must be no other active linger timers, and we must stop lingering.
5621 oldNetwork.clearLingerState();
5622
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005623 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005624 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005625 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005626 } else {
5627 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005628 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5629 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005630 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005631 }
5632
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005633 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005634 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005635
Paul Jensen27b02b72014-07-14 12:03:33 -04005636 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005637 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005638 } catch (Exception e) {
5639 loge("Exception setting default network :" + e);
5640 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005641
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005642 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005643 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005644 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005645 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005646 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005647 }
5648
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005649 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005650 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5651 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5652 NetworkRequest nr = nri.request;
5653 if (!nr.isListen()) continue;
5654 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5655 nai.removeRequest(nri.request.requestId);
5656 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5657 }
5658 }
5659
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005660 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005661 try {
5662 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5663 } catch (RemoteException e) {
5664 e.rethrowFromSystemServer();
5665 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005666 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5667 }
5668
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005669 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5670 NetworkRequest nr = nri.request;
5671 if (!nr.isListen()) continue;
5672 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5673 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005674 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005675 }
5676 }
5677 }
5678
Paul Jensen2161a8e2014-09-11 11:00:39 -04005679 // Handles a network appearing or improving its score.
5680 //
5681 // - Evaluates all current NetworkRequests that can be
5682 // satisfied by newNetwork, and reassigns to newNetwork
5683 // any such requests for which newNetwork is the best.
5684 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005685 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005686 // needed. A network is needed if it is the best network for
5687 // one or more NetworkRequests, or if it is a VPN.
5688 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005689 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005690 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005691 //
5692 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5693 // networks that have no chance (i.e. even if validated)
5694 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005695 //
5696 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5697 // it does not remove NetworkRequests that other Networks could better satisfy.
5698 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5699 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5700 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005701 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005702 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005703 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5704 // performed to tear down unvalidated networks that have no chance (i.e. even if
5705 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005706 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005707 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005708 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005709 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005710 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005711 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005712
5713 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5714 final int score = newNetwork.getCurrentScore();
5715
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005716 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005717
Paul Jensen2161a8e2014-09-11 11:00:39 -04005718 // Find and migrate to this Network any NetworkRequests for
5719 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005720 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5721 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005722 NetworkCapabilities nc = newNetwork.networkCapabilities;
5723 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005724 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005725 // Process requests in the first pass and listens in the second pass. This allows us to
5726 // change a network's capabilities depending on which requests it has. This is only
5727 // correct if the change in capabilities doesn't affect whether the network satisfies
5728 // requests or not, and doesn't affect the network's score.
5729 if (nri.request.isListen()) continue;
5730
Hugo Benichicd952782017-09-20 11:20:14 +09005731 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005732 final boolean satisfies = newNetwork.satisfies(nri.request);
5733 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005734 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005735 log("Network " + newNetwork.name() + " was already satisfying" +
5736 " request " + nri.request.requestId + ". No change.");
5737 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005738 keep = true;
5739 continue;
5740 }
5741
5742 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005743 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005744 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005745 // next check if it's better than any current network we're using for
5746 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005747 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005748 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005749 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005750 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005751 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005752 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005753 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005754 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005755 if (VDBG || DDBG){
5756 log(" accepting network in place of " + currentNetwork.name());
5757 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005758 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005759 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005760 affectedNetworks.add(currentNetwork);
5761 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005762 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005763 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005764 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005765 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005766 if (!newNetwork.addRequest(nri.request)) {
5767 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5768 }
5769 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005770 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005771 // Tell NetworkFactories about the new score, so they can stop
5772 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005773 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005774 // network. Think about if there is a way to reduce this. Push
5775 // netid->request mapping to each factory?
Chalard Jean08577fc2018-05-02 21:14:54 +09005776 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005777 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005778 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005779 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005780 if (currentNetwork != null) {
5781 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5782 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005783 }
5784 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005785 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005786 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5787 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005788 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005789 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5790 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5791 // This means this code doesn't have to handle the case where "currentNetwork" no
5792 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5793 if (DBG) {
5794 log("Network " + newNetwork.name() + " stopped satisfying" +
5795 " request " + nri.request.requestId);
5796 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005797 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005798 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005799 clearNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09005800 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005801 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005802 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5803 newNetwork.name() +
5804 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005805 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005806 // TODO: Technically, sending CALLBACK_LOST here is
5807 // incorrect if there is a replacement network currently
5808 // connected that can satisfy nri, which is a request
5809 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005810 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5811 // so this code is only incorrect for a network that loses
5812 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005813 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005814 }
5815 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005816 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005817 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005818 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005819 makeDefault(newNetwork);
5820 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005821 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005822 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005823 // Have a new default network, release the transition wakelock in
5824 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005825 }
5826
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005827 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5828 Slog.wtf(TAG, String.format(
5829 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005830 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005831 }
5832 if (newNetwork.getCurrentScore() != score) {
5833 Slog.wtf(TAG, String.format(
5834 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005835 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005836 }
5837
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005838 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005839 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5840 // If the network went from background to foreground or vice versa, we need to update
5841 // its foreground state. It is safe to do this after rematching the requests because
5842 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5843 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005844 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005845 } else {
5846 processListenRequests(newNetwork, false);
5847 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005848
Paul Jensencf4c2c62015-07-01 14:16:32 -04005849 // do this after the default net is switched, but
5850 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005851 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005852
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005853 // Linger any networks that are no longer needed. This should be done after sending the
5854 // available callback for newNetwork.
5855 for (NetworkAgentInfo nai : affectedNetworks) {
5856 updateLingerState(nai, now);
5857 }
5858 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5859 // does not need to be done in any particular order.
5860 updateLingerState(newNetwork, now);
5861
Paul Jensencf4c2c62015-07-01 14:16:32 -04005862 if (isNewDefault) {
5863 // Maintain the illusion: since the legacy API only
5864 // understands one network at a time, we must pretend
5865 // that the current default network disconnected before
5866 // the new one connected.
5867 if (oldDefaultNetwork != null) {
5868 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5869 oldDefaultNetwork, true);
5870 }
5871 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5872 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5873 notifyLockdownVpn(newNetwork);
5874 }
5875
Robert Greenwalt7b816022014-04-18 15:25:25 -07005876 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005877 // Notify battery stats service about this network, both the normal
5878 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005879 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005880 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005881 final IBatteryStats bs = BatteryStatsService.getService();
5882 final int type = newNetwork.networkInfo.getType();
5883
5884 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5885 bs.noteNetworkInterfaceType(baseIface, type);
5886 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5887 final String stackedIface = stacked.getInterfaceName();
5888 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005889 }
5890 } catch (RemoteException ignored) {
5891 }
5892
Robert Greenwalt152ed372014-12-17 17:19:53 -08005893 // This has to happen after the notifyNetworkCallbacks as that tickles each
5894 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005895 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005896 // and will generally do a dns request so they can ensureRouteToHost and if
5897 // they do that before the callbacks happen they'll use the default network.
5898 //
5899 // TODO: Is there still a race here? We send the broadcast
5900 // after sending the callback, but if the app can receive the
5901 // broadcast before the callback, it might still break.
5902 //
5903 // This *does* introduce a race where if the user uses the new api
5904 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5905 // they may get old info. Reverse this after the old startUsing api is removed.
5906 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005907 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5908 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005909 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005910 // legacy type tracker filters out repeat adds
5911 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5912 }
5913 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005914
5915 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5916 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5917 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5918 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5919 if (newNetwork.isVPN()) {
5920 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5921 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005922 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005923 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5924 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005925 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005926 if (nai.getLingerExpiry() > 0) {
5927 // This network has active linger timers and no requests, but is not
5928 // lingering. Linger it.
5929 //
5930 // One way (the only way?) this can happen if this network is unvalidated
5931 // and became unneeded due to another network improving its score to the
5932 // point where this network will no longer be able to satisfy any requests
5933 // even if it validates.
5934 updateLingerState(nai, now);
5935 } else {
5936 if (DBG) log("Reaping " + nai.name());
5937 teardownUnneededNetwork(nai);
5938 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005939 }
5940 }
5941 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005942 }
5943
Paul Jensen1c7ba022015-06-16 14:27:36 -04005944 /**
5945 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5946 * being disconnected.
5947 * @param changed If only one Network's score or capabilities have been modified since the last
5948 * time this function was called, pass this Network in this argument, otherwise pass
5949 * null.
5950 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5951 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5952 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5953 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5954 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005955 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005956 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005957 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5958 // to avoid the slowness. It is not simply enough to process just "changed", for
5959 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005960 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005961
5962 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5963 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5964 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005965 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005966 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005967 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005968 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005969 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5970 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5971 // Rematch higher scoring networks first to prevent requests first matching a lower
5972 // scoring network and then a higher scoring network, which could produce multiple
5973 // callbacks and inadvertently unlinger networks.
5974 Arrays.sort(nais);
5975 for (NetworkAgentInfo nai : nais) {
5976 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005977 // Only reap the last time through the loop. Reaping before all rematching
5978 // is complete could incorrectly teardown a network that hasn't yet been
5979 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005980 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005981 : ReapUnvalidatedNetworks.REAP,
5982 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005983 }
5984 }
5985 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005986
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005987 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005988 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005989 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005990 // For now only update icons for default connection.
5991 // TODO: Update WiFi and cellular icons separately. b/17237507
5992 if (!isDefaultNetwork(nai)) return;
5993
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005994 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005995 // Don't repeat publish.
5996 if (newInetCondition == mDefaultInetConditionPublished) return;
5997
5998 mDefaultInetConditionPublished = newInetCondition;
5999 sendInetConditionBroadcast(nai.networkInfo);
6000 }
6001
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006002 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006003 synchronized (mVpns) {
6004 if (mLockdownTracker != null) {
6005 if (nai != null && nai.isVPN()) {
6006 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6007 } else {
6008 mLockdownTracker.onNetworkInfoChanged();
6009 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006010 }
6011 }
6012 }
6013
Robert Greenwalt7b816022014-04-18 15:25:25 -07006014 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006015 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006016 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006017 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006018 synchronized (networkAgent) {
6019 oldInfo = networkAgent.networkInfo;
6020 networkAgent.networkInfo = newInfo;
6021 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006022 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006023
Robert Greenwalt7b816022014-04-18 15:25:25 -07006024 if (DBG) {
6025 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6026 (oldInfo == null ? "null" : oldInfo.getState()) +
6027 " to " + state);
6028 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006029
Robin Lee585e2482016-05-01 23:00:00 +01006030 if (!networkAgent.created
6031 && (state == NetworkInfo.State.CONNECTED
6032 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006033
6034 // A network that has just connected has zero requests and is thus a foreground network.
6035 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6036
Robert Greenwalt7b816022014-04-18 15:25:25 -07006037 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006038 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006039 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006040 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006041 (networkAgent.networkMisc == null ||
6042 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006043 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006044 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006045 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006046 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006047 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006048 loge("Error creating network " + networkAgent.network.netId + ": "
6049 + e.getMessage());
6050 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006051 }
Paul Jenseneec75412014-08-04 12:21:19 -04006052 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006053 }
6054
6055 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6056 networkAgent.everConnected = true;
6057
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006058 if (networkAgent.linkProperties == null) {
6059 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6060 }
6061
Erik Kline736353a2018-03-21 07:18:33 -07006062 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006063 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6064 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006065
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006066 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6067 // command must be sent after updating LinkProperties to maximize chances of
6068 // NetworkMonitor seeing the correct LinkProperties when starting.
6069 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6070 try {
6071 networkAgent.networkMonitor().notifyNetworkConnected();
6072 } catch (RemoteException e) {
6073 e.rethrowFromSystemServer();
6074 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006075 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006076
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006077 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6078 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6079 // capabilities, so it only needs to be done once on initial connect, not every time the
6080 // network's capabilities change. Note that we do this before rematching the network,
6081 // so we could decide to tear it down immediately afterwards. That's fine though - on
6082 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6083 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006084 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006085
Paul Jensen2161a8e2014-09-11 11:00:39 -04006086 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006087 final long now = SystemClock.elapsedRealtime();
6088 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006089
6090 // This has to happen after matching the requests, because callbacks are just requests.
6091 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006092 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006093 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006094 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006095 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006096 }
Chalard Jean392971c2018-05-11 20:19:20 +09006097 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006098 if (networkAgent.isVPN()) {
6099 // As the active or bound network changes for apps, broadcast the default proxy, as
6100 // apps may need to update their proxy data. This is called after disconnecting from
6101 // VPN to make sure we do not broadcast the old proxy data.
6102 // TODO(b/122649188): send the broadcast only to VPN users.
6103 mProxyTracker.sendProxyBroadcast();
6104 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006105 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6106 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006107 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006108 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006109 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006110 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006111 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6112 networkAgent.networkCapabilities);
6113 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6114 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006115 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6116 ConnectivityManager.CALLBACK_SUSPENDED :
6117 ConnectivityManager.CALLBACK_RESUMED));
6118 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006119 }
6120 }
6121
Robert Greenwaltac96c522014-06-03 16:43:57 -07006122 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006123 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006124 if (score < 0) {
6125 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6126 "). Bumping score to min of 0");
6127 score = 0;
6128 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006129
Paul Jensen2161a8e2014-09-11 11:00:39 -04006130 final int oldScore = nai.getCurrentScore();
6131 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006132
Paul Jensen85cf78e2015-06-25 13:25:07 -04006133 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006134
Paul Jensenc8b9a742014-09-30 15:37:41 -04006135 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006136 }
6137
Erik Klinec75d4fa2017-02-15 19:59:17 +09006138 // Notify only this one new request of the current state. Transfer all the
6139 // current state by calling NetworkCapabilities and LinkProperties callbacks
6140 // so that callers can be guaranteed to have as close to atomicity in state
6141 // transfer as can be supported by this current API.
6142 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006143 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006144 if (nri.mPendingIntent != null) {
6145 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6146 // Attempt no subsequent state pushes where intents are involved.
6147 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006148 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006149
junyulai05986c62018-08-07 19:50:45 +08006150 final boolean metered = nai.networkCapabilities.isMetered();
6151 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6152 metered, mRestrictBackground);
6153 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6154 }
6155
6156 /**
6157 * Notify of the blocked state apps with a registered callback matching a given NAI.
6158 *
6159 * Unlike other callbacks, blocked status is different between each individual uid. So for
6160 * any given nai, all requests need to be considered according to the uid who filed it.
6161 *
6162 * @param nai The target NetworkAgentInfo.
6163 * @param oldMetered True if the previous network capabilities is metered.
6164 * @param newRestrictBackground True if data saver is enabled.
6165 */
6166 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6167 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6168
6169 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6170 NetworkRequest nr = nai.requestAt(i);
6171 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6172 final int uidRules = mUidRules.get(nri.mUid);
6173 final boolean oldBlocked, newBlocked;
6174 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6175 // between these two calls.
6176 synchronized (mVpns) {
6177 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6178 oldRestrictBackground);
6179 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6180 newRestrictBackground);
6181 }
6182 if (oldBlocked != newBlocked) {
6183 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6184 encodeBool(newBlocked));
6185 }
6186 }
6187 }
6188
6189 /**
6190 * Notify apps with a given UID of the new blocked state according to new uid rules.
6191 * @param uid The uid for which the rules changed.
6192 * @param newRules The new rules to apply.
6193 */
6194 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6195 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6196 final boolean metered = nai.networkCapabilities.isMetered();
6197 final boolean oldBlocked, newBlocked;
6198 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6199 // rules changed event. And this function actually loop through all connected nai and
6200 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6201 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6202 synchronized (mVpns) {
6203 oldBlocked = isUidNetworkingWithVpnBlocked(
6204 uid, mUidRules.get(uid), metered, mRestrictBackground);
6205 newBlocked = isUidNetworkingWithVpnBlocked(
6206 uid, newRules, metered, mRestrictBackground);
6207 }
6208 if (oldBlocked == newBlocked) {
6209 return;
6210 }
6211 final int arg = encodeBool(newBlocked);
6212 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6213 NetworkRequest nr = nai.requestAt(i);
6214 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6215 if (nri != null && nri.mUid == uid) {
6216 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6217 }
6218 }
6219 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006220 }
6221
Robert Greenwalt8d482522015-06-24 13:23:42 -07006222 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006223 // The NetworkInfo we actually send out has no bearing on the real
6224 // state of affairs. For example, if the default connection is mobile,
6225 // and a request for HIPRI has just gone away, we need to pretend that
6226 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6227 // the state to DISCONNECTED, even though the network is of type MOBILE
6228 // and is still connected.
6229 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6230 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006231 if (state != DetailedState.DISCONNECTED) {
6232 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006233 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006234 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006235 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006236 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6237 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6238 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6239 if (info.isFailover()) {
6240 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6241 nai.networkInfo.setFailover(false);
6242 }
6243 if (info.getReason() != null) {
6244 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6245 }
6246 if (info.getExtraInfo() != null) {
6247 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6248 }
6249 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006250 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006251 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006252 if (newDefaultAgent != null) {
6253 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6254 newDefaultAgent.networkInfo);
6255 } else {
6256 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6257 }
6258 }
6259 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6260 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006261 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006262 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006263 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006264 }
6265 }
6266 }
6267
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006268 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006269 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006270 String notification = ConnectivityManager.getCallbackName(notifyType);
6271 log("notifyType " + notification + " for " + networkAgent.name());
6272 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006273 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6274 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006275 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6276 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006277 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6278 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006279 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006280 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006281 } else {
6282 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6283 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006284 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006285 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006286
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006287 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6288 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6289 }
6290
Jeff Sharkey69736342014-12-08 14:50:12 -08006291 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006292 * Returns the list of all interfaces that could be used by network traffic that does not
6293 * explicitly specify a network. This includes the default network, but also all VPNs that are
6294 * currently connected.
6295 *
6296 * Must be called on the handler thread.
6297 */
6298 private Network[] getDefaultNetworks() {
6299 ArrayList<Network> defaultNetworks = new ArrayList<>();
6300 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6301 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6302 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6303 defaultNetworks.add(nai.network);
6304 }
6305 }
6306 return defaultNetworks.toArray(new Network[0]);
6307 }
6308
6309 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006310 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6311 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006312 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006313 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08006314 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006315 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08006316 } catch (Exception ignored) {
6317 }
6318 }
6319
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006320 @Override
6321 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006322 int user = UserHandle.getUserId(Binder.getCallingUid());
6323 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006324 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006325 return mVpns.get(user).addAddress(address, prefixLength);
6326 }
6327 }
6328
6329 @Override
6330 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006331 int user = UserHandle.getUserId(Binder.getCallingUid());
6332 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006333 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006334 return mVpns.get(user).removeAddress(address, prefixLength);
6335 }
6336 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006337
6338 @Override
6339 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006340 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006341 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006342 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006343 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006344 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006345 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006346 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006347 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006348 }
6349 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006350 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006351
6352 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006353 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006354 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006355 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006356 }
6357
6358 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006359 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
6360 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
6361 enforceKeepalivePermission();
6362 mKeepaliveTracker.startNattKeepalive(
6363 getNetworkAgentInfoForNetwork(network),
6364 intervalSeconds, messenger, binder,
junyulaie4135282019-01-03 18:50:15 +08006365 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006366 }
6367
6368 @Override
junyulai215b8772019-01-15 11:32:44 +08006369 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
6370 int intervalSeconds, Messenger messenger, IBinder binder, String srcAddr,
6371 String dstAddr) {
6372 enforceKeepalivePermission();
6373 mKeepaliveTracker.startNattKeepalive(
6374 getNetworkAgentInfoForNetwork(network), fd, resourceId,
6375 intervalSeconds, messenger, binder,
6376 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6377 }
6378
6379 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006380 public void stopKeepalive(Network network, int slot) {
6381 mHandler.sendMessage(mHandler.obtainMessage(
junyulaie4135282019-01-03 18:50:15 +08006382 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006383 }
6384
6385 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006386 public void factoryReset() {
6387 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006388
6389 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6390 return;
6391 }
6392
Robin Lee3b3dd942015-05-12 18:14:58 +01006393 final int userId = UserHandle.getCallingUserId();
6394
Stuart Scottf1fb3972015-04-02 18:00:02 -07006395 // Turn airplane mode off
6396 setAirplaneMode(false);
6397
Stuart Scotte3e314d2015-04-20 14:07:45 -07006398 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6399 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006400 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006401 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006402 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006403 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006404 }
6405
Stuart Scotte3e314d2015-04-20 14:07:45 -07006406 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006407 // Remove always-on package
6408 synchronized (mVpns) {
6409 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6410 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006411 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006412 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6413 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006414
Hugo Benichi69744342017-11-27 10:57:16 +09006415 // Turn Always-on VPN off
6416 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6417 final long ident = Binder.clearCallingIdentity();
6418 try {
6419 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6420 mLockdownEnabled = false;
6421 setLockdownTracker(null);
6422 } finally {
6423 Binder.restoreCallingIdentity(ident);
6424 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006425 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006426
Hugo Benichi69744342017-11-27 10:57:16 +09006427 // Turn VPN off
6428 VpnConfig vpnConfig = getVpnConfig(userId);
6429 if (vpnConfig != null) {
6430 if (vpnConfig.legacy) {
6431 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6432 } else {
6433 // Prevent this app (packagename = vpnConfig.user) from initiating
6434 // VPN connections in the future without user intervention.
6435 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006436
Hugo Benichi69744342017-11-27 10:57:16 +09006437 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6438 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006439 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006440 }
6441 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006442
6443 Settings.Global.putString(mContext.getContentResolver(),
6444 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006445 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006446
Ricky Wai44dcbde2018-01-23 04:09:45 +00006447 @Override
6448 public byte[] getNetworkWatchlistConfigHash() {
6449 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6450 if (nwm == null) {
6451 loge("Unable to get NetworkWatchlistManager");
6452 return null;
6453 }
6454 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6455 return nwm.getWatchlistConfigHash();
6456 }
6457
Paul Jensencf4c2c62015-07-01 14:16:32 -04006458 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006459 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6460 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006461 }
6462
6463 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006464 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6465 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6466 }
6467
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006468 @VisibleForTesting
6469 public boolean hasService(String name) {
6470 return ServiceManager.checkService(name) != null;
6471 }
6472
Hugo Benichi64901e52017-10-19 14:42:40 +09006473 @VisibleForTesting
6474 protected IpConnectivityMetrics.Logger metricsLogger() {
6475 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6476 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006477 }
6478
6479 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006480 int[] transports = nai.networkCapabilities.getTransportTypes();
6481 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006482 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006483
6484 private static boolean toBool(int encodedBoolean) {
6485 return encodedBoolean != 0; // Only 0 means false.
6486 }
6487
6488 private static int encodeBool(boolean b) {
6489 return b ? 1 : 0;
6490 }
mswest46386886f2018-03-12 10:34:34 -07006491
6492 @Override
6493 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6494 FileDescriptor err, String[] args, ShellCallback callback,
6495 ResultReceiver resultReceiver) {
6496 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6497 }
6498
6499 private class ShellCmd extends ShellCommand {
6500
6501 @Override
6502 public int onCommand(String cmd) {
6503 if (cmd == null) {
6504 return handleDefaultCommands(cmd);
6505 }
6506 final PrintWriter pw = getOutPrintWriter();
6507 try {
6508 switch (cmd) {
6509 case "airplane-mode":
6510 final String action = getNextArg();
6511 if ("enable".equals(action)) {
6512 setAirplaneMode(true);
6513 return 0;
6514 } else if ("disable".equals(action)) {
6515 setAirplaneMode(false);
6516 return 0;
6517 } else if (action == null) {
6518 final ContentResolver cr = mContext.getContentResolver();
6519 final int enabled = Settings.Global.getInt(cr,
6520 Settings.Global.AIRPLANE_MODE_ON);
6521 pw.println(enabled == 0 ? "disabled" : "enabled");
6522 return 0;
6523 } else {
6524 onHelp();
6525 return -1;
6526 }
6527 default:
6528 return handleDefaultCommands(cmd);
6529 }
6530 } catch (Exception e) {
6531 pw.println(e);
6532 }
6533 return -1;
6534 }
6535
6536 @Override
6537 public void onHelp() {
6538 PrintWriter pw = getOutPrintWriter();
6539 pw.println("Connectivity service commands:");
6540 pw.println(" help");
6541 pw.println(" Print this help text.");
6542 pw.println(" airplane-mode [enable|disable]");
6543 pw.println(" Turn airplane mode on or off.");
6544 pw.println(" airplane-mode");
6545 pw.println(" Get airplane mode.");
6546 }
6547 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006548
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006549 @GuardedBy("mVpns")
6550 private Vpn getVpnIfOwner() {
6551 final int uid = Binder.getCallingUid();
6552 final int user = UserHandle.getUserId(uid);
6553
6554 final Vpn vpn = mVpns.get(user);
6555 if (vpn == null) {
6556 return null;
6557 } else {
6558 final VpnInfo info = vpn.getVpnInfo();
6559 return (info == null || info.ownerUid != uid) ? null : vpn;
6560 }
6561 }
6562
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006563 /**
6564 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6565 * for testing.
6566 */
6567 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6568 if (checkNetworkStackPermission()) {
6569 return null;
6570 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006571 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006572 Vpn vpn = getVpnIfOwner();
6573 if (vpn != null) {
6574 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006575 }
6576 }
6577 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6578 + "permission");
6579 }
6580
6581 /**
6582 * @param connectionInfo the connection to resolve.
6583 * @return {@code uid} if the connection is found and the app has permission to observe it
6584 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6585 * connection is not found.
6586 */
6587 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6588 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6589 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6590 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6591 }
6592
6593 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6594 connectionInfo.local, connectionInfo.remote);
6595
6596 /* Filter out Uids not associated with the VPN. */
6597 if (vpn != null && !vpn.appliesToUid(uid)) {
6598 return INVALID_UID;
6599 }
6600
6601 return uid;
6602 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006603
6604 @Override
6605 public boolean isCallerCurrentAlwaysOnVpnApp() {
6606 synchronized (mVpns) {
6607 Vpn vpn = getVpnIfOwner();
6608 return vpn != null && vpn.getAlwaysOn();
6609 }
6610 }
6611
6612 @Override
6613 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6614 synchronized (mVpns) {
6615 Vpn vpn = getVpnIfOwner();
6616 return vpn != null && vpn.getLockdown();
6617 }
6618 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006619}