blob: de7c8cc7a6e7f100e3811080256a91d0747106ef [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;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090063import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050065import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080066import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050067import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070068import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090069import android.net.INetworkMonitor;
70import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070071import android.net.INetworkPolicyListener;
72import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070073import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080074import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070075import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010076import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080077import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070078import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070079import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070080import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070081import android.net.NetworkConfig;
Chalard Jean08577fc2018-05-02 21:14:54 +090082import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070084import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070085import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090086import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070087import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070088import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070089import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090090import android.net.NetworkStack;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070091import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070092import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000093import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090094import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -040095import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070096import android.net.RouteInfo;
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;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700149import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700150import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800151import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700152import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900153import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700154import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600155import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700156import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900157import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900158import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700159import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700160import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400161import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900162import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500163import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900164import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900165import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100166import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700167import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900168import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700169import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600170import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900171import com.android.server.connectivity.NetworkNotificationManager;
172import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700173import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900174import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800175import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700176import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100177import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500178import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700179import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700180import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900181import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700182import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600183
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700184import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700185
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700186import org.xmlpull.v1.XmlPullParser;
187import org.xmlpull.v1.XmlPullParserException;
188
189import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700191import java.io.FileNotFoundException;
192import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700193import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700195import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700196import java.net.InetAddress;
197import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700198import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700199import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700200import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900201import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800202import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700203import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700204import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700205import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700206import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700207import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900208import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600209import java.util.SortedSet;
210import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
212/**
213 * @hide
214 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800215public class ConnectivityService extends IConnectivityManager.Stub
216 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900217 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Chalard Jean4133a122018-06-04 13:33:12 +0900219 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900220 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900221 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900222 private static final String NETWORK_ARG = "networks";
223 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900224
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900225 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900226 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
227 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900229 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700230
Jeff Sharkey899223b2012-08-04 15:24:58 -0700231 // TODO: create better separation between radio types and network types
232
Robert Greenwalt42acef32009-08-12 16:08:25 -0700233 // how long to wait before switching back to a radio's default network
234 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
235 // system property that can override the above value
236 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
237 "android.telephony.apn-restore";
238
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900239 // How long to wait before putting up a "This network doesn't have an Internet connection,
240 // connect anyway?" dialog after the user selects a network that doesn't validate.
241 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
242
lucaslind2e045e02019-01-24 15:55:30 +0800243 // How long to dismiss network notification.
244 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
245
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900246 // Default to 30s linger time-out. Modifiable only for testing.
247 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
248 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
249 @VisibleForTesting
250 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
251
Jeremy Joslin79294842014-12-03 17:15:28 -0800252 // How long to delay to removal of a pending intent based request.
253 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
254 private final int mReleasePendingIntentDelayMs;
255
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900256 private MockableSystemProperties mSystemProperties;
257
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800258 private Tethering mTethering;
259
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700260 private final PermissionMonitor mPermissionMonitor;
261
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700262 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700263
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900264 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700265 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900266 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700267
Hugo Benichi69744342017-11-27 10:57:16 +0900268 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
269 // a direct call to LockdownVpnTracker.isEnabled().
270 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700271 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900272 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700273 private LockdownVpnTracker mLockdownTracker;
274
junyulai05986c62018-08-07 19:50:45 +0800275 /**
276 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
277 * handler thread, they don't need a lock.
278 */
279 private SparseIntArray mUidRules = new SparseIntArray();
280 /** Flag indicating if background data is restricted. */
281 private boolean mRestrictBackground;
282
Erik Klineda4bfa82015-04-30 12:58:40 +0900283 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700284 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700285 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286
Luke Huang4e25ec62018-09-27 16:58:23 +0800287 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800288 @VisibleForTesting
289 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800290 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700291 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900292 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700293
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700294 private String mCurrentTcpBufferSizes;
295
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900296 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900297 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
298 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900299
Paul Jensenb10e37f2014-11-25 12:33:08 -0500300 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400301 // Tear down networks that have no chance (e.g. even if validated) of becoming
302 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500303 // all networks have been rematched against all NetworkRequests.
304 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400305 // Don't reap networks. This should be passed when some networks have not yet been
306 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500307 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900308 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500309
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900310 private enum UnneededFor {
311 LINGER, // Determine whether this network is unneeded and should be lingered.
312 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
313 }
314
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700315 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700316 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700317 * from one net to another. Clear happens when we get a new
318 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
319 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700320 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700321 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700322
Robert Greenwalt434203a2010-10-11 16:00:27 -0700323 /**
324 * used internally to reload global proxy settings
325 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700326 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700327
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700328 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400329 * PAC manager has received new port.
330 */
331 private static final int EVENT_PROXY_HAS_CHANGED = 16;
332
Robert Greenwalte049c232014-04-11 15:53:27 -0700333 /**
334 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700335 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700336 */
337 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
338
Robert Greenwalt7b816022014-04-18 15:25:25 -0700339 /**
340 * used internally when registering NetworkAgents
341 * obj = Messenger
342 */
343 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
344
Robert Greenwalt9258c642014-03-26 16:47:06 -0700345 /**
346 * used to add a network request
347 * includes a NetworkRequestInfo
348 */
349 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
350
351 /**
352 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900353 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700354 * cancel it.
355 * includes a NetworkRequestInfo
356 */
357 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
358
359 /**
360 * used to add a network listener - no request
361 * includes a NetworkRequestInfo
362 */
363 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
364
365 /**
366 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400367 * arg1 = UID of caller
368 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700369 */
370 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
371
Robert Greenwalta67be032014-05-16 15:49:14 -0700372 /**
373 * used internally when registering NetworkFactories
374 * obj = Messenger
375 */
376 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
377
Robert Greenwalt27711812014-06-25 16:45:57 -0700378 /**
379 * used internally to expire a wakelock when transitioning
380 * from one net to another. Expire happens when we fail to find
381 * a new network (typically after 1 minute) -
382 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
383 * a replacement network.
384 */
385 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
386
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700387 /**
388 * Used internally to indicate the system is ready.
389 */
390 private static final int EVENT_SYSTEM_READY = 25;
391
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800392 /**
393 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400394 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800395 */
396 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
397
398 /**
399 * used to remove a pending intent and its associated network request.
400 * arg1 = UID of caller
401 * obj = PendingIntent
402 */
403 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
404
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900405 /**
406 * used to specify whether a network should be used even if unvalidated.
407 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
408 * arg2 = whether to remember this choice in the future (1 or 0)
409 * obj = network
410 */
411 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
412
413 /**
414 * used to ask the user to confirm a connection to an unvalidated network.
415 * obj = network
416 */
417 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700418
Erik Klineda4bfa82015-04-30 12:58:40 +0900419 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700420 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900421 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700422 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900423
Paul Jensen694f2b82015-06-17 14:15:39 -0400424 /**
425 * used to add a network listener with a pending intent
426 * obj = NetworkRequestInfo
427 */
428 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
429
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900430 /**
431 * used to specify whether a network should not be penalized when it becomes unvalidated.
432 */
433 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
434
435 /**
436 * used to trigger revalidation of a network.
437 */
438 private static final int EVENT_REVALIDATE_NETWORK = 36;
439
Erik Klinea24d4592018-01-11 21:07:29 +0900440 // Handle changes in Private DNS settings.
441 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
442
dalyk7301aa42018-03-05 12:42:22 -0500443 // Handle private DNS validation status updates.
444 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
445
junyulai05986c62018-08-07 19:50:45 +0800446 /**
447 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
448 */
449 private static final int EVENT_UID_RULES_CHANGED = 39;
450
451 /**
452 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
453 */
454 private static final int EVENT_DATA_SAVER_CHANGED = 40;
455
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900456 /**
457 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
458 * been tested.
459 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
460 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
461 * arg2 = NetID.
462 */
463 public static final int EVENT_NETWORK_TESTED = 41;
464
465 /**
466 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
467 * config was resolved.
468 * obj = PrivateDnsConfig
469 * arg2 = netid
470 */
471 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
472
473 /**
474 * Request ConnectivityService display provisioning notification.
475 * arg1 = Whether to make the notification visible.
476 * arg2 = NetID.
477 * obj = Intent to be launched when notification selected by user, null if !arg1.
478 */
479 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
480
481 /**
lucaslind2e045e02019-01-24 15:55:30 +0800482 * This event can handle dismissing notification by given network id.
483 */
484 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
485
486 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900487 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
488 * should be shown.
489 */
490 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
491
492 /**
493 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
494 * should be hidden.
495 */
496 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
497
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900498 private static String eventName(int what) {
499 return sMagicDecoderRing.get(what, Integer.toString(what));
500 }
501
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900502 /** Handler thread used for both of the handlers below. */
503 @VisibleForTesting
504 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700505 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700506 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700507 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700508 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900509 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700510
Mike Lockwood0f79b542009-08-14 14:18:49 -0400511 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800512 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400513
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700514 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700515 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800516 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700517
Chalard Jean52c2aa72018-06-07 16:44:04 +0900518 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
519 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000520 @VisibleForTesting
521 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400522
Erik Klineda4bfa82015-04-30 12:58:40 +0900523 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700524
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400525 private UserManager mUserManager;
526
Chalard Jean4133a122018-06-04 13:33:12 +0900527 private NetworkConfig[] mNetConfigs;
528 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700529
Robert Greenwalt50393202011-06-21 17:26:14 -0700530 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900531 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700532
Chalard Jean4133a122018-06-04 13:33:12 +0900533 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400534
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900535 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900536 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900537 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900538
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700539 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800540 private static final int MIN_NET_ID = 100; // some reserved marks
541 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700542 private int mNextNetId = MIN_NET_ID;
543
Robert Greenwalt34524f02014-05-18 16:22:10 -0700544 // sequence number of NetworkRequests
545 private int mNextNetworkRequestId = 1;
546
Erik Kline7523eb32015-07-09 18:24:03 +0900547 // NetworkRequest activity String log entries.
548 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
549 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
550
Hugo Benichic2ae2872016-07-11 11:05:12 +0900551 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900552 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900553 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
554
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900555 private static final int MAX_WAKELOCK_LOGS = 20;
556 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900557 private int mTotalWakelockAcquisitions = 0;
558 private int mTotalWakelockReleases = 0;
559 private long mTotalWakelockDurationMs = 0;
560 private long mMaxWakelockDurationMs = 0;
561 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900562
Hugo Benichif9fdf872016-07-28 17:53:06 +0900563 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900564
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700565 @GuardedBy("mBandwidthRequests")
566 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
567
Erik Kline065ab6e2016-10-02 18:02:14 +0900568 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900569 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900570
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900571 @VisibleForTesting
572 final MultipathPolicyTracker mMultipathPolicyTracker;
573
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 /**
575 * Implements support for the legacy "one network per network type" model.
576 *
577 * We used to have a static array of NetworkStateTrackers, one for each
578 * network type, but that doesn't work any more now that we can have,
579 * for example, more that one wifi network. This class stores all the
580 * NetworkAgentInfo objects that support a given type, but the legacy
581 * API will only see the first one.
582 *
583 * It serves two main purposes:
584 *
585 * 1. Provide information about "the network for a given type" (since this
586 * API only supports one).
587 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
588 * the first network for a given type changes, or if the default network
589 * changes.
590 */
591 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900593 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900595
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 /**
597 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
598 * Each list holds references to all NetworkAgentInfos that are used to
599 * satisfy requests for that network type.
600 *
601 * This array is built out at startup such that an unsupported network
602 * doesn't get an ArrayList instance, making this a tristate:
603 * unsupported, supported but not active and active.
604 *
605 * The actual lists are populated when we scan the network types that
606 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900607 *
608 * Threading model:
609 * - addSupportedType() is only called in the constructor
610 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
611 * They are therefore not thread-safe with respect to each other.
612 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
613 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
614 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700615 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900616 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617
618 public LegacyTypeTracker() {
619 mTypeLists = (ArrayList<NetworkAgentInfo>[])
620 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
621 }
622
623 public void addSupportedType(int type) {
624 if (mTypeLists[type] != null) {
625 throw new IllegalStateException(
626 "legacy list for type " + type + "already initialized");
627 }
Chalard Jean4133a122018-06-04 13:33:12 +0900628 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 }
630
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 public boolean isTypeSupported(int type) {
632 return isNetworkTypeValid(type) && mTypeLists[type] != null;
633 }
634
635 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900636 synchronized (mTypeLists) {
637 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
638 return mTypeLists[type].get(0);
639 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700640 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900641 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700642 }
643
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900645 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900646 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900648 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900649 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900650 }
651 }
652
653 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700654 public void add(int type, NetworkAgentInfo nai) {
655 if (!isTypeSupported(type)) {
656 return; // Invalid network type.
657 }
658 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
659
660 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
661 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700662 return;
663 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900664 synchronized (mTypeLists) {
665 list.add(nai);
666 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900667
668 // 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 +0900669 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900670 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700671 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
672 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700673 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700674 }
675
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900677 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900678 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
679 if (list == null || list.isEmpty()) {
680 return;
681 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900682 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900683
Hugo Benichi78caa2582016-06-21 09:48:07 +0900684 synchronized (mTypeLists) {
685 if (!list.remove(nai)) {
686 return;
687 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900688 }
689
Robert Greenwalt8d482522015-06-24 13:23:42 -0700690 final DetailedState state = DetailedState.DISCONNECTED;
691
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900692 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700693 maybeLogBroadcast(nai, state, type, wasDefault);
694 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900695 }
696
697 if (!list.isEmpty() && wasFirstNetwork) {
698 if (DBG) log("Other network available for type " + type +
699 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900700 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700701 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
702 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900703 }
704 }
705
706 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900707 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
708 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700709 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900710 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700711 }
712 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700713
Robert Greenwalt8d482522015-06-24 13:23:42 -0700714 // send out another legacy broadcast - currently only used for suspend/unsuspend
715 // toggle
716 public void update(NetworkAgentInfo nai) {
717 final boolean isDefault = isDefaultNetwork(nai);
718 final DetailedState state = nai.networkInfo.getDetailedState();
719 for (int type = 0; type < mTypeLists.length; type++) {
720 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700721 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900722 final boolean isFirst = contains && (nai == list.get(0));
723 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700724 maybeLogBroadcast(nai, state, type, isDefault);
725 sendLegacyNetworkBroadcast(nai, state, type);
726 }
727 }
728 }
729
Lorenzo Colittia793a672014-07-31 23:20:17 +0900730 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900731 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900732 String state = (nai.networkInfo != null) ?
733 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
734 "???/???";
735 return name + " " + state;
736 }
737
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700738 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900739 pw.println("mLegacyTypeTracker:");
740 pw.increaseIndent();
741 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700742 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900743 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700744 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900745 pw.println();
746 pw.println("Current state:");
747 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900748 synchronized (mTypeLists) {
749 for (int type = 0; type < mTypeLists.length; type++) {
750 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
751 for (NetworkAgentInfo nai : mTypeLists[type]) {
752 pw.println(type + " " + naiToString(nai));
753 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900754 }
755 }
756 pw.decreaseIndent();
757 pw.decreaseIndent();
758 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700759 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700760 }
761 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
762
Vishnu Nair5c010902017-10-26 10:08:50 -0700763 /**
764 * Helper class which parses out priority arguments and dumps sections according to their
765 * priority. If priority arguments are omitted, function calls the legacy dump command.
766 */
767 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
768 @Override
769 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
770 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
771 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
772 }
773
774 @Override
775 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
776 doDump(fd, pw, args, asProto);
777 }
778
779 @Override
780 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
781 doDump(fd, pw, args, asProto);
782 }
783 };
784
Jeff Sharkey899223b2012-08-04 15:24:58 -0700785 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700786 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900787 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
788 }
789
790 @VisibleForTesting
791 protected ConnectivityService(Context context, INetworkManagementService netManager,
792 INetworkStatsService statsService, INetworkPolicyManager policyManager,
793 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800794 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800795
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900796 mSystemProperties = getSystemProperties();
797
Hugo Benichif9fdf872016-07-28 17:53:06 +0900798 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900799 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900800 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900801 mNetworkRequests.put(mDefaultRequest, defaultNRI);
802 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900803
Chalard Jeandda156a2018-01-10 21:19:32 +0900804 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900805 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700806
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700807 // The default WiFi request is a background request so that apps using WiFi are
808 // migrated to a better network (typically ethernet) when one comes up, instead
809 // of staying on WiFi forever.
810 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
811 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
812
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900813 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900814 mHandlerThread.start();
815 mHandler = new InternalHandler(mHandlerThread.getLooper());
816 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700817
Jeremy Joslin79294842014-12-03 17:15:28 -0800818 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
819 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
820
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900821 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900822
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700823 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800824 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800825 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700826 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900827 mPolicyManagerInternal = checkNotNull(
828 LocalServices.getService(NetworkPolicyManagerInternal.class),
829 "missing NetworkPolicyManagerInternal");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000830 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900831
Luke Huang674660f2018-09-27 19:33:11 +0800832 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700833 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700834 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700835
junyulai05986c62018-08-07 19:50:45 +0800836 // To ensure uid rules are synchronized with Network Policy, register for
837 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
838 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700839 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900840 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700841 } catch (RemoteException e) {
842 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700843 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700844 }
845
846 final PowerManager powerManager = (PowerManager) context.getSystemService(
847 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700848 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
849 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
850 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800851 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700852
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700853 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700854
Wink Saville51f456f2013-04-23 14:26:51 -0700855 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900856 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700857 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700858 String[] naStrings = context.getResources().getStringArray(
859 com.android.internal.R.array.networkAttributes);
860 for (String naString : naStrings) {
861 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700862 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700863 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700864 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800865 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700866 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700867 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700868 }
Wink Saville51f456f2013-04-23 14:26:51 -0700869 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
870 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
871 n.type);
872 continue;
873 }
Wink Saville975c8482011-04-07 14:23:45 -0700874 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800875 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700876 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700877 continue;
878 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700879 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700880
Wink Saville975c8482011-04-07 14:23:45 -0700881 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700882 mNetworksDefined++;
883 } catch(Exception e) {
884 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700885 }
886 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700887
888 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
889 if (mNetConfigs[TYPE_VPN] == null) {
890 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
891 // don't need to add TYPE_VPN to mNetConfigs.
892 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
893 mNetworksDefined++; // used only in the log() statement below.
894 }
895
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900896 // Do the same for Ethernet, since it's often not specified in the configs, although many
897 // devices can use it via USB host adapters.
898 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
899 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
900 mNetworksDefined++;
901 }
902
Wink Saville5e56bc52013-07-29 15:00:57 -0700903 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700904
Robert Greenwalt50393202011-06-21 17:26:14 -0700905 mProtectedNetworks = new ArrayList<Integer>();
906 int[] protectedNetworks = context.getResources().getIntArray(
907 com.android.internal.R.array.config_protectedNetworks);
908 for (int p : protectedNetworks) {
909 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
910 mProtectedNetworks.add(p);
911 } else {
912 if (DBG) loge("Ignoring protectedNetwork " + p);
913 }
914 }
915
Erik Kline47222fc2017-04-30 19:36:15 +0900916 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800917
Luke Huang4e25ec62018-09-27 16:58:23 +0800918 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700919
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700920 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700921 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100922 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700923 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700924 intentFilter.addAction(Intent.ACTION_USER_ADDED);
925 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000926 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700927 mContext.registerReceiverAsUser(
junyulai2454b692018-11-01 17:16:31 +0800928 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000929 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
930 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900931
junyulai2454b692018-11-01 17:16:31 +0800932 // Listen to package add and removal events for all users.
933 intentFilter = new IntentFilter();
934 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800935 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800936 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
937 intentFilter.addDataScheme("package");
938 mContext.registerReceiverAsUser(
939 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
940
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700941 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800942 mNMS.registerObserver(mTethering);
943 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700944 } catch (RemoteException e) {
945 loge("Error registering observer :" + e);
946 }
947
Erik Klineda4bfa82015-04-30 12:58:40 +0900948 mSettingsObserver = new SettingsObserver(mContext, mHandler);
949 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800950
Chalard Jean4133a122018-06-04 13:33:12 +0900951 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
952 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400953
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400954 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900955
956 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900957 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
958 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900959
960 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
961 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
962 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
963 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
964 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
965 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
966 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900967
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900968 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900969 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900970 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900971
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900972 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
973
Luke Huang4e25ec62018-09-27 16:58:23 +0800974 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900975 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700977
Mike Yuf9729752018-08-17 15:22:05 +0800978 @VisibleForTesting
979 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +0900980 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900981 final TetheringDependencies deps = new TetheringDependencies() {
982 @Override
983 public boolean isTetheringSupported() {
984 return ConnectivityService.this.isTetheringSupported();
985 }
Erik Kline72302902018-06-14 17:36:40 +0900986 @Override
987 public NetworkRequest getDefaultNetworkRequest() {
988 return mDefaultRequest;
989 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900990 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800991 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900992 IoThread.get().getLooper(), new MockableSystemProperties(),
993 deps);
994 }
995
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000996 @VisibleForTesting
997 protected ProxyTracker makeProxyTracker() {
998 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
999 }
1000
Chalard Jean26400492018-04-18 20:18:38 +09001001 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1002 final NetworkCapabilities netCap = new NetworkCapabilities();
1003 netCap.addCapability(NET_CAPABILITY_INTERNET);
1004 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1005 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1006 netCap.setSingleUid(uid);
1007 return netCap;
1008 }
1009
Chalard Jeandda156a2018-01-10 21:19:32 +09001010 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001011 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001012 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001013 netCap.addCapability(NET_CAPABILITY_INTERNET);
1014 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001015 if (transportType > -1) {
1016 netCap.addTransportType(transportType);
1017 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001018 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001019 }
1020
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001021 // Used only for testing.
1022 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001023 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001024 // changing ContentResolver to make registerContentObserver non-final).
1025 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1026 // by subclassing SettingsObserver.
1027 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001028 void updateAlwaysOnNetworks() {
1029 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001030 }
1031
Erik Kline736353a2018-03-21 07:18:33 -07001032 // See FakeSettingsProvider comment above.
1033 @VisibleForTesting
1034 void updatePrivateDnsSettings() {
1035 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1036 }
1037
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001038 private void handleAlwaysOnNetworkRequest(
1039 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001040 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001041 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1042 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001043 if (enable == isEnabled) {
1044 return; // Nothing to do.
1045 }
1046
1047 if (enable) {
1048 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001049 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001050 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001051 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +09001052 }
1053 }
1054
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001055 private void handleConfigureAlwaysOnNetworks() {
1056 handleAlwaysOnNetworkRequest(
1057 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1058 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1059 false);
1060 }
1061
Erik Klineda4bfa82015-04-30 12:58:40 +09001062 private void registerSettingsCallbacks() {
1063 // Watch for global HTTP proxy changes.
1064 mSettingsObserver.observe(
1065 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1066 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1067
1068 // Watch for whether or not to keep mobile data always on.
1069 mSettingsObserver.observe(
1070 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001071 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1072
1073 // Watch for whether or not to keep wifi always on.
1074 mSettingsObserver.observe(
1075 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1076 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001077 }
1078
Erik Klinea24d4592018-01-11 21:07:29 +09001079 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001080 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1081 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001082 }
1083 }
1084
Robert Greenwalt34524f02014-05-18 16:22:10 -07001085 private synchronized int nextNetworkRequestId() {
1086 return mNextNetworkRequestId++;
1087 }
1088
Paul Jensen67b0b072015-06-10 11:22:17 -04001089 @VisibleForTesting
1090 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001091 synchronized (mNetworkForNetId) {
1092 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1093 int netId = mNextNetId;
1094 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1095 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001096 if (!mNetIdInUse.get(netId)) {
1097 mNetIdInUse.put(netId, true);
1098 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001099 }
1100 }
1101 }
1102 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001103 }
1104
Chalard Jeanc0982912018-06-07 16:11:34 +09001105 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001106 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1108 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001109 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001110 state = nai.getNetworkState();
1111 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001112 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001113 final NetworkInfo info = new NetworkInfo(networkType, 0,
1114 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001115 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1116 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001117 final NetworkCapabilities capabilities = new NetworkCapabilities();
1118 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1119 !info.isRoaming());
1120 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001121 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001122 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001123 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001124 return state;
1125 } else {
1126 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001127 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001128 }
1129
junyulai4a192e22018-06-13 15:00:37 +08001130 @VisibleForTesting
1131 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001132 if (network == null) {
1133 return null;
1134 }
Erik Kline736353a2018-03-21 07:18:33 -07001135 return getNetworkAgentInfoForNetId(network.netId);
1136 }
1137
1138 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001140 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001141 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001142 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001143
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001144 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001145 synchronized (mVpns) {
1146 if (!mLockdownEnabled) {
1147 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001148 Vpn vpn = mVpns.get(user);
1149 if (vpn != null && vpn.appliesToUid(uid)) {
1150 return vpn.getUnderlyingNetworks();
1151 }
1152 }
1153 }
1154 return null;
1155 }
1156
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001157 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001158 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001159
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001160 final Network[] networks = getVpnUnderlyingNetworks(uid);
1161 if (networks != null) {
1162 // getUnderlyingNetworks() returns:
1163 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1164 // empty array => the VPN explicitly said "no default network".
1165 // non-empty array => the VPN specified one or more default networks; we use the
1166 // first one.
1167 if (networks.length > 0) {
1168 nai = getNetworkAgentInfoForNetwork(networks[0]);
1169 } else {
1170 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001171 }
1172 }
1173
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001175 return nai.getNetworkState();
1176 } else {
1177 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001179 }
1180
1181 /**
1182 * Check if UID should be blocked from using the network with the given LinkProperties.
1183 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001184 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1185 boolean ignoreBlocked) {
1186 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001187 if (ignoreBlocked) {
1188 return false;
1189 }
Robin Lee17e61832016-05-09 13:46:28 +01001190 synchronized (mVpns) {
1191 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001192 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001193 return true;
1194 }
1195 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001196 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001197 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001198 }
1199
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001200 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001201 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1202 return;
1203 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001204 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001205 synchronized (mBlockedAppUids) {
1206 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001207 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001208 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001209 blocked = false;
1210 } else {
1211 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001212 }
1213 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001214 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1215 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1216 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001217 }
1218
junyulai05986c62018-08-07 19:50:45 +08001219 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1220 boolean blocked) {
1221 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1222 return;
1223 }
1224 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1225 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1226 nri.mUid, nri.request.requestId, net.netId));
1227 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1228 }
1229
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001230 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001231 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1232 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001233 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001234 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001235 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001236 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1237
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001238 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001239 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001240 }
Hugo Benichi69744342017-11-27 10:57:16 +09001241 synchronized (mVpns) {
1242 if (mLockdownTracker != null) {
1243 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1244 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001245 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001246 }
1247
1248 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 * Return NetworkInfo for the active (i.e., connected) network interface.
1250 * It is assumed that at most one network is active at a time. If more
1251 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001252 * @return the info for the active network, or {@code null} if none is
1253 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001255 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001257 enforceAccessPermission();
1258 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001259 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001260 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001261 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1262 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
1264
Paul Jensen31a94f42015-02-13 14:18:39 -05001265 @Override
1266 public Network getActiveNetwork() {
1267 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001268 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001269 }
1270
1271 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001272 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001273 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001274 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001275 }
1276
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001277 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001278 final int user = UserHandle.getUserId(uid);
1279 int vpnNetId = NETID_UNSET;
1280 synchronized (mVpns) {
1281 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001282 // TODO : now that capabilities contain the UID, the appliesToUid test should
1283 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001284 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1285 }
1286 NetworkAgentInfo nai;
1287 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001288 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001289 if (nai != null) {
1290 final NetworkCapabilities requiredCaps =
1291 createDefaultNetworkCapabilitiesForUid(uid);
1292 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1293 return nai.network;
1294 }
1295 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001296 }
1297 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001298 if (nai != null
1299 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1300 nai = null;
1301 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001302 return nai != null ? nai.network : null;
1303 }
1304
Lorenzo Colitti18660282016-07-04 12:55:44 +09001305 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001306 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1307 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001308 final int uid = Binder.getCallingUid();
1309 NetworkState state = getUnfilteredActiveNetworkState(uid);
1310 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001311 }
1312
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001313 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001314 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001315 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001316 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001317 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001318 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001319 }
1320
1321 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 public NetworkInfo getNetworkInfo(int networkType) {
1323 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001324 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001325 if (getVpnUnderlyingNetworks(uid) != null) {
1326 // A VPN is active, so we may need to return one of its underlying networks. This
1327 // information is not available in LegacyTypeTracker, so we have to get it from
1328 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001329 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001330 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001331 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001332 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001333 }
1334 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001335 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001336 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001339 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001340 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001341 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001342 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001343 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001344 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001345 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001346 return state.networkInfo;
1347 } else {
1348 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001349 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001350 }
1351
1352 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 public NetworkInfo[] getAllNetworkInfo() {
1354 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001355 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001356 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1357 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001358 NetworkInfo info = getNetworkInfo(networkType);
1359 if (info != null) {
1360 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001363 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001366 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001367 public Network getNetworkForType(int networkType) {
1368 enforceAccessPermission();
1369 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001370 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001371 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001372 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001373 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001374 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001375 }
1376
1377 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001378 public Network[] getAllNetworks() {
1379 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001380 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001381 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001382 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001383 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001384 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001385 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001386 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001387 }
1388
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001389 @Override
1390 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1391 // The basic principle is: if an app's traffic could possibly go over a
1392 // network, without the app doing anything multinetwork-specific,
1393 // (hence, by "default"), then include that network's capabilities in
1394 // the array.
1395 //
1396 // In the normal case, app traffic only goes over the system's default
1397 // network connection, so that's the only network returned.
1398 //
1399 // With a VPN in force, some app traffic may go into the VPN, and thus
1400 // over whatever underlying networks the VPN specifies, while other app
1401 // traffic may go over the system default network (e.g.: a split-tunnel
1402 // VPN, or an app disallowed by the VPN), so the set of networks
1403 // returned includes the VPN's underlying networks and the system
1404 // default.
1405 enforceAccessPermission();
1406
Chalard Jean4133a122018-06-04 13:33:12 +09001407 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001408
1409 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001410 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001411 if (nc != null) {
1412 result.put(nai.network, nc);
1413 }
1414
Hugo Benichi69744342017-11-27 10:57:16 +09001415 synchronized (mVpns) {
1416 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001417 Vpn vpn = mVpns.get(userId);
1418 if (vpn != null) {
1419 Network[] networks = vpn.getUnderlyingNetworks();
1420 if (networks != null) {
1421 for (Network network : networks) {
1422 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001423 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001424 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001425 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001426 }
1427 }
1428 }
1429 }
1430 }
1431 }
1432
1433 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1434 out = result.values().toArray(out);
1435 return out;
1436 }
1437
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001438 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001439 public boolean isNetworkSupported(int networkType) {
1440 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001441 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001442 }
1443
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001444 /**
1445 * Return LinkProperties for the active (i.e., connected) default
1446 * network interface. It is assumed that at most one default network
1447 * is active at a time. If more than one is active, it is indeterminate
1448 * which will be returned.
1449 * @return the ip properties for the active network, or {@code null} if
1450 * none is active
1451 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001452 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001453 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001454 enforceAccessPermission();
1455 final int uid = Binder.getCallingUid();
1456 NetworkState state = getUnfilteredActiveNetworkState(uid);
1457 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001458 }
1459
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001460 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001461 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001462 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001463 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1464 if (nai != null) {
1465 synchronized (nai) {
1466 return new LinkProperties(nai.linkProperties);
1467 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001468 }
1469 return null;
1470 }
1471
Robert Greenwalt12e67352014-05-13 21:41:06 -07001472 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001473 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001474 public LinkProperties getLinkProperties(Network network) {
1475 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001476 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1477 }
1478
1479 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1480 if (nai == null) {
1481 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001482 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001483 synchronized (nai) {
1484 return new LinkProperties(nai.linkProperties);
1485 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001486 }
1487
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001488 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001489 if (nai != null) {
1490 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001491 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001492 return networkCapabilitiesRestrictedForCallerPermissions(
1493 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001494 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001495 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001496 }
1497 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001498 return null;
1499 }
1500
1501 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001502 public NetworkCapabilities getNetworkCapabilities(Network network) {
1503 enforceAccessPermission();
1504 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1505 }
1506
Chalard Jeanb03a6222018-04-11 21:09:10 +09001507 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001508 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001509 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001510 if (!checkSettingsPermission(callerPid, callerUid)) {
1511 newNc.setUids(null);
1512 newNc.setSSID(null);
1513 }
Etan Cohen836ad572018-12-30 17:59:59 -08001514 if (newNc.getNetworkSpecifier() != null) {
1515 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1516 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001517 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001518 }
1519
Chalard Jeanb552c462018-02-21 18:43:54 +09001520 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1521 if (!checkSettingsPermission()) {
1522 nc.setSingleUid(Binder.getCallingUid());
1523 }
1524 }
1525
Chalard Jean26aa91a2018-03-20 19:13:57 +09001526 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1527 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1528 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1529 }
1530 }
1531
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001532 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001533 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001534 // Require internal since we're handing out IMSI details
1535 enforceConnectivityInternalPermission();
1536
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001537 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001538 for (Network network : getAllNetworks()) {
1539 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1540 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001541 // TODO (b/73321673) : NetworkState contains a copy of the
1542 // NetworkCapabilities, which may contain UIDs of apps to which the
1543 // network applies. Should the UIDs be cleared so as not to leak or
1544 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001545 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001546 }
1547 }
1548 return result.toArray(new NetworkState[result.size()]);
1549 }
1550
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001551 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001552 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001553 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001554 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1555 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1556 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001557 }
1558
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001559 @Override
1560 public boolean isActiveNetworkMetered() {
1561 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001562
Eric Enslenc81ef192018-02-07 18:03:53 -08001563 final int uid = Binder.getCallingUid();
1564 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001565 if (caps != null) {
1566 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1567 } else {
1568 // Always return the most conservative value
1569 return true;
1570 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001571 }
1572
Jeff Sharkey216c1812012-08-05 14:29:23 -07001573 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1574 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001575 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001576 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001577 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001578 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001579 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001580
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001581 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001582 * Ensures that the system cannot call a particular method.
1583 */
1584 private boolean disallowedBecauseSystemCaller() {
1585 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1586 // requestRouteToHost.
1587 if (isSystem(Binder.getCallingUid())) {
1588 log("This method exists only for app backwards compatibility"
1589 + " and must not be called by system services.");
1590 return true;
1591 }
1592 return false;
1593 }
1594
1595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 * Ensure that a network route exists to deliver traffic to the specified
1597 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001598 * @param networkType the type of the network over which traffic to the
1599 * specified host is to be routed
1600 * @param hostAddress the IP address of the host to which the route is
1601 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 * @return {@code true} on success, {@code false} on failure
1603 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001604 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001605 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001606 if (disallowedBecauseSystemCaller()) {
1607 return false;
1608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001610 if (mProtectedNetworks.contains(networkType)) {
1611 enforceConnectivityInternalPermission();
1612 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001613
Chad Brubakerc0234532014-02-14 13:24:29 -08001614 InetAddress addr;
1615 try {
1616 addr = InetAddress.getByAddress(hostAddress);
1617 } catch (UnknownHostException e) {
1618 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1619 return false;
1620 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001623 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 return false;
1625 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001626
1627 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1628 if (nai == null) {
1629 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1630 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1631 } else {
1632 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1633 }
1634 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001635 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001636
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001637 DetailedState netState;
1638 synchronized (nai) {
1639 netState = nai.networkInfo.getDetailedState();
1640 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001641
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001642 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001643 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001644 log("requestRouteToHostAddress on down network "
1645 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001646 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001647 }
1648 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001650
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001651 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001652 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001653 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001654 LinkProperties lp;
1655 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001656 synchronized (nai) {
1657 lp = nai.linkProperties;
1658 netId = nai.network.netId;
1659 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001660 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001661 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1662 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001663 } finally {
1664 Binder.restoreCallingIdentity(token);
1665 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001666 }
1667
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001668 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001669 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001670 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001671 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001672 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001673 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001674 if (bestRoute.getGateway().equals(addr)) {
1675 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001676 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001677 } else {
1678 // if we will connect to this through another route, add a direct route
1679 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001680 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001681 }
1682 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001683 if (DBG) log("Adding legacy route " + bestRoute +
1684 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001685 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001686 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001687 } catch (Exception e) {
1688 // never crash - catch them all
1689 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001690 return false;
1691 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001692 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694
dalyk7301aa42018-03-05 12:42:22 -05001695 @VisibleForTesting
1696 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1697 @Override
1698 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1699 String hostname, boolean validated) {
1700 try {
1701 mHandler.sendMessage(mHandler.obtainMessage(
1702 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1703 new PrivateDnsValidationUpdate(netId,
1704 InetAddress.parseNumericAddress(ipAddress),
1705 hostname, validated)));
1706 } catch (IllegalArgumentException e) {
1707 loge("Error parsing ip address in validation event");
1708 }
1709 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001710
1711 @Override
1712 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1713 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1714 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1715 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1716 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1717 // event callback for certain nai. e.g. cellular. Register here to pass to
1718 // NetworkMonitor instead.
1719 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1720 // registerNetworkAgent to have NetworkMonitor created with system process as design
1721 // expectation. Also, NetdEventListenerService only allow one callback from each
1722 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1723 // NetworkMonitor registrants.
1724 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001725 try {
1726 nai.networkMonitor().notifyDnsResponse(returnCode);
1727 } catch (RemoteException e) {
1728 e.rethrowFromSystemServer();
1729 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001730 }
1731 }
dalyk7301aa42018-03-05 12:42:22 -05001732 };
1733
1734 @VisibleForTesting
1735 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001736 final IIpConnectivityMetrics ipConnectivityMetrics =
1737 IIpConnectivityMetrics.Stub.asInterface(
1738 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1739 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001740 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001741 return;
dalyk7301aa42018-03-05 12:42:22 -05001742 }
1743
1744 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001745 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001746 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1747 mNetdEventCallback);
1748 } catch (Exception e) {
1749 loge("Error registering netd callback: " + e);
1750 }
1751 }
1752
Jeff Sharkey75d31892018-01-18 22:01:59 +09001753 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001754 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001755 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001756 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001757 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001758 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001759 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001760 // caller is NPMS, since we only register with them
1761 if (LOGD_BLOCKED_NETWORKINFO) {
1762 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1763 }
1764 mHandler.sendMessage(mHandler.obtainMessage(
1765 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1766
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001767 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001768 if (restrictBackground) {
1769 log("onRestrictBackgroundChanged(true): disabling tethering");
1770 mTethering.untetherAll();
1771 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001772 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001773 };
1774
junyulai05986c62018-08-07 19:50:45 +08001775 void handleUidRulesChanged(int uid, int newRules) {
1776 // skip update when we've already applied rules
1777 final int oldRules = mUidRules.get(uid, RULE_NONE);
1778 if (oldRules == newRules) return;
1779
1780 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1781
1782 if (newRules == RULE_NONE) {
1783 mUidRules.delete(uid);
1784 } else {
1785 mUidRules.put(uid, newRules);
1786 }
1787 }
1788
1789 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1790 if (mRestrictBackground == restrictBackground) return;
1791
1792 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1793 final boolean curMetered = nai.networkCapabilities.isMetered();
1794 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1795 restrictBackground);
1796 }
1797
1798 mRestrictBackground = restrictBackground;
1799 }
1800
1801 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1802 boolean isBackgroundRestricted) {
1803 synchronized (mVpns) {
1804 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1805 // Because the return value of this function depends on the list of UIDs the
1806 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1807 // list all state depending on the return value of this function has to be recomputed.
1808 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1809 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001810 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001811 return true;
1812 }
1813 }
1814
1815 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1816 isNetworkMetered, isBackgroundRestricted);
1817 }
1818
Robin Lee3b3dd942015-05-12 18:14:58 +01001819 /**
1820 * Require that the caller is either in the same user or has appropriate permission to interact
1821 * across users.
1822 *
1823 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1824 */
1825 private void enforceCrossUserPermission(int userId) {
1826 if (userId == UserHandle.getCallingUserId()) {
1827 // Not a cross-user call.
1828 return;
1829 }
1830 mContext.enforceCallingOrSelfPermission(
1831 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1832 "ConnectivityService");
1833 }
1834
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001835 private void enforceAnyPermissionOf(String... permissions) {
1836 for (String permission : permissions) {
1837 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
1838 return;
1839 }
1840 }
1841 throw new SecurityException(
1842 "Requires one of the following permissions: " + String.join(", ", permissions) + ".");
1843 }
1844
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001845 private void enforceInternetPermission() {
1846 mContext.enforceCallingOrSelfPermission(
1847 android.Manifest.permission.INTERNET,
1848 "ConnectivityService");
1849 }
1850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001852 mContext.enforceCallingOrSelfPermission(
1853 android.Manifest.permission.ACCESS_NETWORK_STATE,
1854 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856
1857 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001858 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
1860
Charles He36738632017-05-15 17:07:18 +01001861 private void enforceSettingsPermission() {
1862 mContext.enforceCallingOrSelfPermission(
1863 android.Manifest.permission.NETWORK_SETTINGS,
1864 "ConnectivityService");
1865 }
1866
Chalard Jeanb552c462018-02-21 18:43:54 +09001867 private boolean checkSettingsPermission() {
1868 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1869 android.Manifest.permission.NETWORK_SETTINGS);
1870 }
1871
1872 private boolean checkSettingsPermission(int pid, int uid) {
1873 return PERMISSION_GRANTED == mContext.checkPermission(
1874 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1875 }
1876
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001877 private void enforceTetherAccessPermission() {
1878 mContext.enforceCallingOrSelfPermission(
1879 android.Manifest.permission.ACCESS_NETWORK_STATE,
1880 "ConnectivityService");
1881 }
1882
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001883 private void enforceConnectivityInternalPermission() {
1884 mContext.enforceCallingOrSelfPermission(
1885 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1886 "ConnectivityService");
1887 }
1888
Pavel Grafova462bcb2019-01-25 08:50:06 +00001889 private void enforceControlAlwaysOnVpnPermission() {
1890 mContext.enforceCallingOrSelfPermission(
1891 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1892 "ConnectivityService");
1893 }
1894
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001895 private void enforceNetworkStackSettingsOrSetup() {
1896 enforceAnyPermissionOf(
1897 android.Manifest.permission.NETWORK_SETTINGS,
1898 android.Manifest.permission.NETWORK_SETUP_WIZARD,
1899 android.Manifest.permission.NETWORK_STACK);
1900 }
1901
Pavel Grafova462bcb2019-01-25 08:50:06 +00001902 private void enforceNetworkStackPermission() {
1903 mContext.enforceCallingOrSelfPermission(
1904 android.Manifest.permission.NETWORK_STACK,
1905 "ConnectivityService");
1906 }
1907
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001908 private boolean checkNetworkStackPermission() {
1909 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1910 android.Manifest.permission.NETWORK_STACK);
1911 }
1912
Hugo Benichi514da602016-07-19 15:59:27 +09001913 private void enforceConnectivityRestrictedNetworksPermission() {
1914 try {
1915 mContext.enforceCallingOrSelfPermission(
1916 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1917 "ConnectivityService");
1918 return;
1919 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1920 enforceConnectivityInternalPermission();
1921 }
1922
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001923 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001924 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001925 }
1926
Lorenzo Colitti18660282016-07-04 12:55:44 +09001927 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001928 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001929 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001930 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001931 }
1932
1933 private void sendInetConditionBroadcast(NetworkInfo info) {
1934 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1935 }
1936
Wink Saville628b0852011-08-04 15:01:58 -07001937 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001938 synchronized (mVpns) {
1939 if (mLockdownTracker != null) {
1940 info = new NetworkInfo(info);
1941 mLockdownTracker.augmentNetworkInfo(info);
1942 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001943 }
1944
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001945 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001946 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001947 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 if (info.isFailover()) {
1949 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1950 info.setFailover(false);
1951 }
1952 if (info.getReason() != null) {
1953 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1954 }
1955 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001956 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1957 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001959 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001960 return intent;
1961 }
1962
1963 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1964 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1965 }
1966
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001967 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001968 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1969 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1970 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001971 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001972 final long ident = Binder.clearCallingIdentity();
1973 try {
1974 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1975 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1976 } finally {
1977 Binder.restoreCallingIdentity(ident);
1978 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001979 }
1980
Mike Lockwood0f79b542009-08-14 14:18:49 -04001981 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001982 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09001983 if (!mSystemReady
1984 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001985 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001986 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001987 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001988 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001989 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001990 }
1991
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001992 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001993 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001994 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001995 final NetworkInfo ni = intent.getParcelableExtra(
1996 ConnectivityManager.EXTRA_NETWORK_INFO);
1997 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1998 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1999 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002000 } else {
2001 BroadcastOptions opts = BroadcastOptions.makeBasic();
2002 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2003 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002004 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002005 final IBatteryStats bs = BatteryStatsService.getService();
2006 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002007 bs.noteConnectivityChanged(intent.getIntExtra(
2008 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002009 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002010 } catch (RemoteException e) {
2011 }
Chad Brubakerac925012018-03-08 10:37:09 -08002012 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002013 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002014 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002015 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002016 } finally {
2017 Binder.restoreCallingIdentity(ident);
2018 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002019 }
2020 }
2021
2022 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002023 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002024 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002025 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002026
Hugo Benichi20035e02017-04-26 14:53:28 +09002027 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002028 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002029 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002030 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002031 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002032 }
2033 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002034
Robin Lee244ce8e2016-01-05 18:03:46 +00002035 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2036 // for user to unlock device too.
2037 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002038
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002039 // Create network requests for always-on networks.
2040 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002041
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002042 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002043
2044 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
2046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002048 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002049 *
2050 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002051 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002052 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002053 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2054 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002055
2056 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002057 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002058
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 if (networkAgent.networkCapabilities.hasTransport(
2060 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002061 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2062 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002063 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002064 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002065 } else if (networkAgent.networkCapabilities.hasTransport(
2066 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002067 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2068 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002069 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002071 } else {
2072 // do not track any other networks
2073 timeout = 0;
2074 }
2075
Robert Greenwalt7b816022014-04-18 15:25:25 -07002076 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002077 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002078 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002079 } catch (Exception e) {
2080 // You shall not crash!
2081 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002082 }
2083 }
2084 }
2085
2086 /**
2087 * Remove data activity tracking when network disconnects.
2088 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002089 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2090 final String iface = networkAgent.linkProperties.getInterfaceName();
2091 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002092
Robert Greenwalt7b816022014-04-18 15:25:25 -07002093 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2094 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002095 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002096 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002097 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002098 } catch (Exception e) {
2099 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002100 }
2101 }
2102 }
2103
2104 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002105 * Update data activity tracking when network state is updated.
2106 */
2107 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2108 NetworkAgentInfo oldNetwork) {
2109 if (newNetwork != null) {
2110 setupDataActivityTracking(newNetwork);
2111 }
2112 if (oldNetwork != null) {
2113 removeDataActivityTracking(oldNetwork);
2114 }
2115 }
2116 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002117 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002118 * and set it on it's iface.
2119 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2121 final String iface = newLp.getInterfaceName();
2122 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002123 if (oldLp == null && mtu == 0) {
2124 // Silently ignore unset MTU value.
2125 return;
2126 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2128 if (VDBG) log("identical MTU - not setting");
2129 return;
2130 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002131 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002132 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 return;
2134 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002135
w1997615afd812014-08-05 15:18:11 -07002136 // Cannot set MTU without interface name
2137 if (TextUtils.isEmpty(iface)) {
2138 loge("Setting MTU size with null iface.");
2139 return;
2140 }
2141
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002143 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002144 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002145 } catch (Exception e) {
2146 Slog.e(TAG, "exception in setMtu()" + e);
2147 }
2148 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002149
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002150 @VisibleForTesting
2151 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002152 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2153
2154 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002155 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002156 protected MockableSystemProperties getSystemProperties() {
2157 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002158 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002159
lucaslin041a1af2018-11-28 19:27:52 +08002160 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002161 String[] values = null;
2162 if (tcpBufferSizes != null) {
2163 values = tcpBufferSizes.split(",");
2164 }
2165
2166 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002167 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002168 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2169 values = tcpBufferSizes.split(",");
2170 }
2171
2172 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2173
2174 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002175 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002176
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002177 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2178 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2179 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002180 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002181 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002182 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002183 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002184
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002185 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002186 Settings.Global.TCP_DEFAULT_INIT_RWND,
2187 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002188 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2189 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002190 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002191 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002192 }
2193
Robert Greenwalt562cc542014-05-15 18:07:26 -07002194 @Override
2195 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002196 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002197 NETWORK_RESTORE_DELAY_PROP_NAME);
2198 if(restoreDefaultNetworkDelayStr != null &&
2199 restoreDefaultNetworkDelayStr.length() != 0) {
2200 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002201 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002202 } catch (NumberFormatException e) {
2203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002205 // if the system property isn't set, use the value for the apn type
2206 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2207
2208 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2209 (mNetConfigs[networkType] != null)) {
2210 ret = mNetConfigs[networkType].restoreTime;
2211 }
2212 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 }
2214
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002215 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2216 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2217 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002218 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002219 // Start gathering diagnostic information.
2220 netDiags.add(new NetworkDiagnostics(
2221 nai.network,
2222 new LinkProperties(nai.linkProperties), // Must be a copy.
2223 DIAG_TIME_MS));
2224 }
2225
2226 for (NetworkDiagnostics netDiag : netDiags) {
2227 pw.println();
2228 netDiag.waitForMeasurements();
2229 netDiag.dump(pw);
2230 }
2231 }
2232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002234 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002235 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2236 }
2237
2238 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002239 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002240 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002241 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002242
Erik Kline3f8306b2018-05-01 16:51:44 +09002243 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002244 dumpNetworkDiagnostics(pw);
2245 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002246 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002247 mTethering.dump(fd, pw, args);
2248 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002249 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2250 dumpNetworks(pw);
2251 return;
2252 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2253 dumpNetworkRequests(pw);
2254 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002255 }
Erik Kline379747a2015-06-05 17:47:34 +09002256
Lorenzo Colittie3805462015-06-03 11:18:24 +09002257 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002258 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002259 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002260 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002261 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002262 pw.println();
2263
Paul Jensen85cf78e2015-06-25 13:25:07 -04002264 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002265 pw.print("Active default network: ");
2266 if (defaultNai == null) {
2267 pw.println("none");
2268 } else {
2269 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002271 pw.println();
2272
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002273 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002274 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002275 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002276 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002277 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002278
junyulai05986c62018-08-07 19:50:45 +08002279 pw.print("Restrict background: ");
2280 pw.println(mRestrictBackground);
2281 pw.println();
2282
2283 pw.println("Status for known UIDs:");
2284 pw.increaseIndent();
2285 final int size = mUidRules.size();
2286 for (int i = 0; i < size; i++) {
2287 // Don't crash if the array is modified while dumping in bugreports.
2288 try {
2289 final int uid = mUidRules.keyAt(i);
2290 final int uidRules = mUidRules.get(uid, RULE_NONE);
2291 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2292 } catch (ArrayIndexOutOfBoundsException e) {
2293 pw.println(" ArrayIndexOutOfBoundsException");
2294 } catch (ConcurrentModificationException e) {
2295 pw.println(" ConcurrentModificationException");
2296 }
2297 }
2298 pw.println();
2299 pw.decreaseIndent();
2300
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002301 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002302 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002303 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002304 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002305 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002306
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002307 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002308
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002309 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002310 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002311
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002312 pw.println();
2313 mKeepaliveTracker.dump(pw);
2314
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002315 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002316 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002317
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002318 pw.println();
2319 mMultipathPolicyTracker.dump(pw);
2320
Erik Kline3f8306b2018-05-01 16:51:44 +09002321 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002322 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002323 pw.println("mNetworkRequestInfoLogs (most recent first):");
2324 pw.increaseIndent();
2325 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2326 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002327
2328 pw.println();
2329 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2330 pw.increaseIndent();
2331 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2332 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002333
2334 pw.println();
2335 pw.println("NetTransition WakeLock activity (most recent first):");
2336 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002337 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2338 pw.println("total releases: " + mTotalWakelockReleases);
2339 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2340 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2341 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2342 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2343 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2344 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002345 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002346
2347 pw.println();
2348 pw.println("bandwidth update requests (by uid):");
2349 pw.increaseIndent();
2350 synchronized (mBandwidthRequests) {
2351 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2352 pw.println("[" + mBandwidthRequests.keyAt(i)
2353 + "]: " + mBandwidthRequests.valueAt(i));
2354 }
2355 }
2356 pw.decreaseIndent();
2357
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002358 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 }
2361
Hugo Benichi14683812018-09-03 08:32:56 +09002362 private void dumpNetworks(IndentingPrintWriter pw) {
2363 for (NetworkAgentInfo nai : networksSortedById()) {
2364 pw.println(nai.toString());
2365 pw.increaseIndent();
2366 pw.println(String.format(
2367 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2368 nai.numForegroundNetworkRequests(),
2369 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2370 nai.numBackgroundNetworkRequests(),
2371 nai.numNetworkRequests()));
2372 pw.increaseIndent();
2373 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2374 pw.println(nai.requestAt(i).toString());
2375 }
2376 pw.decreaseIndent();
2377 pw.println("Lingered:");
2378 pw.increaseIndent();
2379 nai.dumpLingerTimers(pw);
2380 pw.decreaseIndent();
2381 pw.decreaseIndent();
2382 }
2383 }
2384
2385 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2386 for (NetworkRequestInfo nri : requestsSortedById()) {
2387 pw.println(nri.toString());
2388 }
2389 }
2390
Hugo Benichia2a917c2018-09-03 08:19:02 +09002391 /**
2392 * Return an array of all current NetworkAgentInfos sorted by network id.
2393 */
2394 private NetworkAgentInfo[] networksSortedById() {
2395 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2396 networks = mNetworkAgentInfos.values().toArray(networks);
2397 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2398 return networks;
2399 }
2400
2401 /**
2402 * Return an array of all current NetworkRequest sorted by request id.
2403 */
2404 private NetworkRequestInfo[] requestsSortedById() {
2405 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2406 requests = mNetworkRequests.values().toArray(requests);
2407 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2408 return requests;
2409 }
2410
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002411 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002412 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002413 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002414 if (officialNai != null && officialNai.equals(nai)) return true;
2415 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002416 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002417 " - " + nai);
2418 }
2419 return false;
2420 }
2421
Robert Greenwalt42acef32009-08-12 16:08:25 -07002422 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002423 private class NetworkStateTrackerHandler extends Handler {
2424 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002425 super(looper);
2426 }
2427
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002428 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002430 default:
2431 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002432 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002433 handleAsyncChannelHalfConnect(msg);
2434 break;
2435 }
2436 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2437 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2438 if (nai != null) nai.asyncChannel.disconnect();
2439 break;
2440 }
2441 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2442 handleAsyncChannelDisconnected(msg);
2443 break;
2444 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002445 }
2446 return true;
2447 }
2448
2449 private void maybeHandleNetworkAgentMessage(Message msg) {
2450 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2451 if (nai == null) {
2452 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002453 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002454 }
2455 return;
2456 }
2457
2458 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002459 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002460 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2461 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002462 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2463 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002464 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002465 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002466 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002467 break;
2468 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002469 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002470 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002471 break;
2472 }
2473 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002474 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002475 updateNetworkInfo(nai, info);
2476 break;
2477 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002478 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002479 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002480 break;
2481 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002482 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002483 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2484 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002485 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002486 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002487 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002488 break;
2489 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002490 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002491 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2492 break;
2493 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002494 }
2495 }
2496
2497 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2498 switch (msg.what) {
2499 default:
2500 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002501 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002502 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002503 if (nai == null) break;
2504
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002505 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002506 final boolean wasValidated = nai.lastValidated;
2507 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002508 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2509 && valid) {
2510 nai.captivePortalLoginNotified = true;
2511 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2512 }
Erik Klinea24d4592018-01-11 21:07:29 +09002513
Erik Klinea24d4592018-01-11 21:07:29 +09002514 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2515
Erik Klinea24d4592018-01-11 21:07:29 +09002516 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002517 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2518 ? " with redirect to " + redirectUrl
2519 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002520 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2521 }
Erik Klinea24d4592018-01-11 21:07:29 +09002522 if (valid != nai.lastValidated) {
2523 if (wasDefault) {
2524 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2525 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002526 }
Erik Klinea24d4592018-01-11 21:07:29 +09002527 final int oldScore = nai.getCurrentScore();
2528 nai.lastValidated = valid;
2529 nai.everValidated |= valid;
2530 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2531 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2532 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002533 if (valid) {
2534 handleFreshlyValidatedNetwork(nai);
2535 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2536 // valid.
2537 mNotifier.clearNotification(nai.network.netId,
2538 NotificationType.NO_INTERNET);
2539 mNotifier.clearNotification(nai.network.netId,
2540 NotificationType.LOST_INTERNET);
2541 }
Erik Klinea24d4592018-01-11 21:07:29 +09002542 }
2543 updateInetCondition(nai);
2544 // Let the NetworkAgent know the state of its network
2545 Bundle redirectUrlBundle = new Bundle();
2546 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2547 nai.asyncChannel.sendMessage(
2548 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2549 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2550 0, redirectUrlBundle);
2551 if (wasValidated && !nai.lastValidated) {
2552 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002553 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002554 break;
2555 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002556 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002557 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002558 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002559 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002560 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002561 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002562 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002563 nai.lastCaptivePortalDetected = visible;
2564 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002565 if (visible) {
2566 nai.captivePortalLoginNotified = false;
2567 }
Calvin Onbe96da12016-10-11 15:10:46 -07002568 if (nai.lastCaptivePortalDetected &&
2569 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2570 if (DBG) log("Avoiding captive portal network: " + nai.name());
2571 nai.asyncChannel.sendMessage(
2572 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2573 teardownUnneededNetwork(nai);
2574 break;
2575 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002576 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002577 }
2578 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002579 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
2580 // notifications belong to the same network may be cleared unexpected.
2581 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2582 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002583 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002584 if (nai == null) {
2585 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2586 break;
2587 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002588 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002589 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002590 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002591 }
Paul Jensen869868be2014-05-15 10:33:05 -04002592 }
Paul Jensen869868be2014-05-15 10:33:05 -04002593 break;
2594 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002595 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002596 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002597 if (nai == null) break;
2598
Erik Kline736353a2018-03-21 07:18:33 -07002599 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002600 break;
2601 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002602 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002603 return true;
2604 }
2605
Calvin Onbe96da12016-10-11 15:10:46 -07002606 private int getCaptivePortalMode() {
2607 return Settings.Global.getInt(mContext.getContentResolver(),
2608 Settings.Global.CAPTIVE_PORTAL_MODE,
2609 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2610 }
2611
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002612 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2613 switch (msg.what) {
2614 default:
2615 return false;
2616 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2617 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2618 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2619 handleLingerComplete(nai);
2620 }
2621 break;
2622 }
2623 }
2624 return true;
2625 }
2626
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002627 @Override
2628 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002629 if (!maybeHandleAsyncChannelMessage(msg) &&
2630 !maybeHandleNetworkMonitorMessage(msg) &&
2631 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002632 maybeHandleNetworkAgentMessage(msg);
2633 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002634 }
2635 }
2636
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002637 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2638 private final NetworkAgentInfo mNai;
2639
2640 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2641 mNai = nai;
2642 }
2643
2644 @Override
2645 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2646 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2647 new Pair<>(mNai, networkMonitor)));
2648 }
2649
2650 @Override
2651 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2652 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2653 testResult, mNai.network.netId, redirectUrl));
2654 }
2655
2656 @Override
2657 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2658 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2659 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2660 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2661 }
2662
2663 @Override
2664 public void showProvisioningNotification(String action) {
2665 final Intent intent = new Intent(action);
2666 intent.setPackage(NETWORKSTACK_PACKAGE_NAME);
2667
2668 final PendingIntent pendingIntent;
2669 // Only the system server can register notifications with package "android"
2670 final long token = Binder.clearCallingIdentity();
2671 try {
2672 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2673 } finally {
2674 Binder.restoreCallingIdentity(token);
2675 }
2676 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2677 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2678 mNai.network.netId,
2679 pendingIntent));
2680 }
2681
2682 @Override
2683 public void hideProvisioningNotification() {
2684 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2685 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2686 mNai.network.netId));
2687 }
2688 }
2689
Erik Kline736353a2018-03-21 07:18:33 -07002690 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002691 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002692 }
2693
Erik Klinec6d00222018-06-26 18:53:43 +09002694 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2695 if (nai == null) return;
2696 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2697 // in order to restart a validation pass from within netd.
2698 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2699 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2700 updateDnses(nai.linkProperties, null, nai.network.netId);
2701 }
2702 }
2703
Erik Klinea24d4592018-01-11 21:07:29 +09002704 private void handlePrivateDnsSettingsChanged() {
2705 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2706
2707 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002708 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002709 if (networkRequiresValidation(nai)) {
2710 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2711 }
Erik Klinea24d4592018-01-11 21:07:29 +09002712 }
2713 }
2714
Erik Kline736353a2018-03-21 07:18:33 -07002715 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2716 // Private DNS only ever applies to networks that might provide
2717 // Internet access and therefore also require validation.
2718 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002719
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002720 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002721 // schedule DNS resolutions. If a DNS resolution is required the
2722 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002723 try {
2724 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2725 } catch (RemoteException e) {
2726 e.rethrowFromSystemServer();
2727 }
Erik Kline736353a2018-03-21 07:18:33 -07002728
2729 // With Private DNS bypass support, we can proceed to update the
2730 // Private DNS config immediately, even if we're in strict mode
2731 // and have not yet resolved the provider name into a set of IPs.
2732 updatePrivateDns(nai, cfg);
2733 }
2734
2735 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2736 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002737 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002738 }
2739
dalyk7301aa42018-03-05 12:42:22 -05002740 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2741 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2742 if (nai == null) {
2743 return;
2744 }
2745 mDnsManager.updatePrivateDnsValidation(update);
2746 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2747 }
2748
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002749 private void updateLingerState(NetworkAgentInfo nai, long now) {
2750 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2751 // 2. If the network was lingering and there are now requests, unlinger it.
2752 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2753 // one lingered request, start lingering.
2754 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002755 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002756 if (DBG) log("Unlingering " + nai.name());
2757 nai.unlinger();
2758 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002759 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002760 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002761 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002762 nai.linger();
2763 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2764 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2765 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002766 }
2767
Robert Greenwalt7b816022014-04-18 15:25:25 -07002768 private void handleAsyncChannelHalfConnect(Message msg) {
2769 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002770 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002771 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2772 if (VDBG) log("NetworkFactory connected");
2773 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002774 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002775 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002776 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002777 final int score;
2778 final int serial;
2779 if (nai != null) {
2780 score = nai.getCurrentScore();
2781 serial = nai.factorySerialNumber;
2782 } else {
2783 score = 0;
2784 serial = NetworkFactory.SerialNumber.NONE;
2785 }
2786 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2787 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002788 }
2789 } else {
2790 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002791 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002792 }
2793 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2794 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2795 if (VDBG) log("NetworkAgent connected");
2796 // A network agent has requested a connection. Establish the connection.
2797 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2798 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2799 } else {
2800 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002801 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002802 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002803 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002804 synchronized (mNetworkForNetId) {
2805 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002806 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002807 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002808 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002809 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002810 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002811 }
2812 }
2813 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002814
Chalard Jean392971c2018-05-11 20:19:20 +09002815 // This is a no-op if it's called with a message designating a network that has
2816 // already been destroyed, because its reference will not be found in the relevant
2817 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002818 private void handleAsyncChannelDisconnected(Message msg) {
2819 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2820 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002821 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002822 } else {
2823 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2824 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002825 }
2826 }
2827
Chalard Jean392971c2018-05-11 20:19:20 +09002828 // Destroys a network, remove references to it from the internal state managed by
2829 // ConnectivityService, free its interfaces and clean up.
2830 // Must be called on the Handler thread.
2831 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2832 if (DBG) {
2833 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2834 }
2835 // A network agent has disconnected.
2836 // TODO - if we move the logic to the network agent (have them disconnect
2837 // because they lost all their requests or because their score isn't good)
2838 // then they would disconnect organically, report their new state and then
2839 // disconnect the channel.
2840 if (nai.networkInfo.isConnected()) {
2841 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2842 null, null);
2843 }
2844 final boolean wasDefault = isDefaultNetwork(nai);
2845 if (wasDefault) {
2846 mDefaultInetConditionPublished = 0;
2847 // Log default network disconnection before required book-keeping.
2848 // Let rematchAllNetworksAndRequests() below record a new default network event
2849 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2850 // whose timestamps tell how long it takes to recover a default network.
2851 long now = SystemClock.elapsedRealtime();
2852 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2853 }
2854 notifyIfacesChangedForNetworkStats();
2855 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2856 // by other networks that are already connected. Perhaps that can be done by
2857 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2858 // of rematchAllNetworksAndRequests
2859 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2860 mKeepaliveTracker.handleStopAllKeepalives(nai,
2861 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2862 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2863 // Disable wakeup packet monitoring for each interface.
2864 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2865 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002866 try {
2867 nai.networkMonitor().notifyNetworkDisconnected();
2868 } catch (RemoteException e) {
2869 e.rethrowFromSystemServer();
2870 }
Chalard Jean392971c2018-05-11 20:19:20 +09002871 mNetworkAgentInfos.remove(nai.messenger);
2872 nai.maybeStopClat();
2873 synchronized (mNetworkForNetId) {
2874 // Remove the NetworkAgent, but don't mark the netId as
2875 // available until we've told netd to delete it below.
2876 mNetworkForNetId.remove(nai.network.netId);
2877 }
2878 // Remove all previously satisfied requests.
2879 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2880 NetworkRequest request = nai.requestAt(i);
2881 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2882 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2883 clearNetworkForRequest(request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002884 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09002885 }
2886 }
2887 nai.clearLingerState();
2888 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002889 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002890 notifyLockdownVpn(nai);
2891 ensureNetworkTransitionWakelock(nai.name());
2892 }
2893 mLegacyTypeTracker.remove(nai, wasDefault);
2894 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2895 updateAllVpnsCapabilities();
2896 }
2897 rematchAllNetworksAndRequests(null, 0);
2898 mLingerMonitor.noteDisconnect(nai);
2899 if (nai.created) {
2900 // Tell netd to clean up the configuration for this network
2901 // (routing rules, DNS, etc).
2902 // This may be slow as it requires a lot of netd shelling out to ip and
2903 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2904 // after we've rematched networks with requests which should make a potential
2905 // fallback network the default or requested a new network from the
2906 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2907 // long time.
2908 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002909 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002910 } catch (Exception e) {
2911 loge("Exception removing network: " + e);
2912 }
2913 mDnsManager.removeNetwork(nai.network);
2914 }
2915 synchronized (mNetworkForNetId) {
2916 mNetIdInUse.delete(nai.network.netId);
2917 }
2918 }
2919
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002920 // If this method proves to be too slow then we can maintain a separate
2921 // pendingIntent => NetworkRequestInfo map.
2922 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2923 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2924 Intent intent = pendingIntent.getIntent();
2925 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2926 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2927 if (existingPendingIntent != null &&
2928 existingPendingIntent.getIntent().filterEquals(intent)) {
2929 return entry.getValue();
2930 }
2931 }
2932 return null;
2933 }
2934
2935 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2936 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2937
2938 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2939 if (existingRequest != null) { // remove the existing request.
2940 if (DBG) log("Replacing " + existingRequest.request + " with "
2941 + nri.request + " because their intents matched.");
2942 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2943 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002944 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002945 }
2946
Erik Klineda4bfa82015-04-30 12:58:40 +09002947 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002948 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002949 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002950 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002951 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002952 if (nri.request.networkCapabilities.hasSignalStrength() &&
2953 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2954 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002955 }
2956 }
2957 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002958 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002959 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean08577fc2018-05-02 21:14:54 +09002960 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002961 }
2962 }
2963
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002964 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2965 int callingUid) {
2966 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2967 if (nri != null) {
2968 handleReleaseNetworkRequest(nri.request, callingUid);
2969 }
2970 }
2971
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002972 // Determines whether the network is the best (or could become the best, if it validated), for
2973 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2974 // on the value of reason:
2975 //
2976 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2977 // then it should be torn down.
2978 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2979 // then it should be lingered.
2980 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2981 final int numRequests;
2982 switch (reason) {
2983 case TEARDOWN:
2984 numRequests = nai.numRequestNetworkRequests();
2985 break;
2986 case LINGER:
2987 numRequests = nai.numForegroundNetworkRequests();
2988 break;
2989 default:
2990 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2991 return true;
2992 }
2993
2994 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002995 return false;
2996 }
Paul Jensene0988542015-06-25 15:30:08 -04002997 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002998 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2999 // Background requests don't affect lingering.
3000 continue;
3001 }
3002
Paul Jensene0988542015-06-25 15:30:08 -04003003 // If this Network is already the highest scoring Network for a request, or if
3004 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003005 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003006 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003007 // Note that this catches two important cases:
3008 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3009 // is currently satisfying the request. This is desirable when
3010 // cellular ends up validating but WiFi does not.
3011 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003012 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003013 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003014 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003015 nai.getCurrentScoreAsValidated())) {
3016 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003017 }
3018 }
Paul Jensene0988542015-06-25 15:30:08 -04003019 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003020 }
3021
Erik Klineacdd6392016-07-07 16:50:58 +09003022 private NetworkRequestInfo getNriForAppRequest(
3023 NetworkRequest request, int callingUid, String requestedOperation) {
3024 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3025
Robert Greenwalt9258c642014-03-26 16:47:06 -07003026 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003027 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003028 log(String.format("UID %d attempted to %s for unowned request %s",
3029 callingUid, requestedOperation, nri));
3030 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003031 }
Erik Klineacdd6392016-07-07 16:50:58 +09003032 }
3033
3034 return nri;
3035 }
3036
Erik Kline57faba92015-11-25 12:49:38 +09003037 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003038 if (mNetworkRequests.get(nri.request) == null) {
3039 return;
Erik Kline57faba92015-11-25 12:49:38 +09003040 }
Hugo Benichicd952782017-09-20 11:20:14 +09003041 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003042 return;
3043 }
3044 if (VDBG || (DBG && nri.request.isRequest())) {
3045 log("releasing " + nri.request + " (timeout)");
3046 }
3047 handleRemoveNetworkRequest(nri);
3048 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003049 }
3050
Erik Klineacdd6392016-07-07 16:50:58 +09003051 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003052 final NetworkRequestInfo nri =
3053 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3054 if (nri == null) {
3055 return;
Erik Kline57faba92015-11-25 12:49:38 +09003056 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003057 if (VDBG || (DBG && nri.request.isRequest())) {
3058 log("releasing " + nri.request + " (release request)");
3059 }
3060 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09003061 }
Erik Klineacdd6392016-07-07 16:50:58 +09003062
Hugo Benichidba33db2017-03-23 22:40:44 +09003063 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003064 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003065 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003066
Erik Klineacdd6392016-07-07 16:50:58 +09003067 synchronized (mUidToNetworkRequestCount) {
3068 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3069 if (requests < 1) {
3070 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3071 nri.mUid);
3072 } else if (requests == 1) {
3073 mUidToNetworkRequestCount.removeAt(
3074 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3075 } else {
3076 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3077 }
3078 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003079
Erik Klineacdd6392016-07-07 16:50:58 +09003080 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3081 if (nri.request.isRequest()) {
3082 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003083 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003084 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003085 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003086 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003087 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003088 log(" Removing from current network " + nai.name() +
3089 ", leaving " + nai.numNetworkRequests() + " requests.");
3090 }
3091 // If there are still lingered requests on this network, don't tear it down,
3092 // but resume lingering instead.
3093 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003094 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003095 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3096 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003097 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003098 wasKept = true;
3099 }
Hugo Benichicd952782017-09-20 11:20:14 +09003100 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003101 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3102 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003103 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003104 }
Erik Klineacdd6392016-07-07 16:50:58 +09003105 }
3106
Erik Klineacdd6392016-07-07 16:50:58 +09003107 // Maintain the illusion. When this request arrived, we might have pretended
3108 // that a network connected to serve it, even though the network was already
3109 // connected. Now that this request has gone away, we might have to pretend
3110 // that the network disconnected. LegacyTypeTracker will generate that
3111 // phantom disconnect for this type.
3112 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3113 boolean doRemove = true;
3114 if (wasKept) {
3115 // check if any of the remaining requests for this network are for the
3116 // same legacy type - if so, don't remove the nai
3117 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3118 NetworkRequest otherRequest = nai.requestAt(i);
3119 if (otherRequest.legacyType == nri.request.legacyType &&
3120 otherRequest.isRequest()) {
3121 if (DBG) log(" still have other legacy request - leaving");
3122 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003123 }
3124 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003125 }
3126
Erik Klineacdd6392016-07-07 16:50:58 +09003127 if (doRemove) {
3128 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003129 }
3130 }
Erik Klineacdd6392016-07-07 16:50:58 +09003131
3132 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3133 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3134 nri.request);
3135 }
3136 } else {
3137 // listens don't have a singular affectedNetwork. Check all networks to see
3138 // if this listen request applies and remove it.
3139 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3140 nai.removeRequest(nri.request.requestId);
3141 if (nri.request.networkCapabilities.hasSignalStrength() &&
3142 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3143 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3144 }
3145 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003146 }
3147 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003148
Lorenzo Colitti18660282016-07-04 12:55:44 +09003149 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003150 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3151 enforceConnectivityInternalPermission();
3152 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003153 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003154 }
3155
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003156 @Override
3157 public void setAvoidUnvalidated(Network network) {
3158 enforceConnectivityInternalPermission();
3159 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3160 }
3161
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003162 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3163 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3164 " accept=" + accept + " always=" + always);
3165
3166 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3167 if (nai == null) {
3168 // Nothing to do.
3169 return;
3170 }
3171
3172 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003173 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003174 return;
3175 }
3176
3177 if (!nai.networkMisc.explicitlySelected) {
3178 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3179 }
3180
3181 if (accept != nai.networkMisc.acceptUnvalidated) {
3182 int oldScore = nai.getCurrentScore();
3183 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003184 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003185 sendUpdatedScoreToFactories(nai);
3186 }
3187
3188 if (always) {
3189 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003190 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003191 }
3192
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003193 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003194 // Tell the NetworkAgent to not automatically reconnect to the network.
3195 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003196 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003197 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003198 }
3199
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003200 }
3201
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003202 private void handleSetAvoidUnvalidated(Network network) {
3203 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3204 if (nai == null || nai.lastValidated) {
3205 // Nothing to do. The network either disconnected or revalidated.
3206 return;
3207 }
3208 if (!nai.avoidUnvalidated) {
3209 int oldScore = nai.getCurrentScore();
3210 nai.avoidUnvalidated = true;
3211 rematchAllNetworksAndRequests(nai, oldScore);
3212 sendUpdatedScoreToFactories(nai);
3213 }
3214 }
3215
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003216 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003217 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003218 mHandler.sendMessageDelayed(
3219 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3220 PROMPT_UNVALIDATED_DELAY_MS);
3221 }
3222
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003223 @Override
3224 public void startCaptivePortalApp(Network network) {
3225 enforceConnectivityInternalPermission();
3226 mHandler.post(() -> {
3227 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3228 if (nai == null) return;
3229 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003230 try {
3231 nai.networkMonitor().launchCaptivePortalApp();
3232 } catch (RemoteException e) {
3233 e.rethrowFromSystemServer();
3234 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003235 });
3236 }
3237
Hugo Benichic8e9e122016-09-14 23:23:08 +00003238 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003239 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003240 }
3241
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003242 @Override
3243 public boolean getAvoidBadWifi() {
3244 if (!checkNetworkStackPermission()) {
3245 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3246 }
3247 return avoidBadWifi();
3248 }
3249
3250
Erik Kline065ab6e2016-10-02 18:02:14 +09003251 private void rematchForAvoidBadWifiUpdate() {
3252 rematchAllNetworksAndRequests(null, 0);
3253 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3254 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3255 sendUpdatedScoreToFactories(nai);
3256 }
3257 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003258 }
3259
Erik Kline065ab6e2016-10-02 18:02:14 +09003260 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003261 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003262 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003263 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003264 if (!configRestrict) {
3265 pw.println("Bad Wi-Fi avoidance: unrestricted");
3266 return;
3267 }
3268
3269 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3270 pw.increaseIndent();
3271 pw.println("Config restrict: " + configRestrict);
3272
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003273 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003274 String description;
3275 // Can't use a switch statement because strings are legal case labels, but null is not.
3276 if ("0".equals(value)) {
3277 description = "get stuck";
3278 } else if (value == null) {
3279 description = "prompt";
3280 } else if ("1".equals(value)) {
3281 description = "avoid";
3282 } else {
3283 description = value + " (?)";
3284 }
3285 pw.println("User setting: " + description);
3286 pw.println("Network overrides:");
3287 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003288 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003289 if (nai.avoidUnvalidated) {
3290 pw.println(nai.name());
3291 }
3292 }
3293 pw.decreaseIndent();
3294 pw.decreaseIndent();
3295 }
3296
lucaslind2e045e02019-01-24 15:55:30 +08003297 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003298 final String action;
3299 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003300 case LOGGED_IN:
3301 action = Settings.ACTION_WIFI_SETTINGS;
3302 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3303 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3304 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3305 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003306 case NO_INTERNET:
3307 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3308 break;
3309 case LOST_INTERNET:
3310 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3311 break;
3312 default:
3313 Slog.wtf(TAG, "Unknown notification type " + type);
3314 return;
3315 }
3316
3317 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003318 if (type != NotificationType.LOGGED_IN) {
3319 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3320 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3321 intent.setClassName("com.android.settings",
3322 "com.android.settings.wifi.WifiNoInternetDialog");
3323 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003324
3325 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3326 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3327 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3328 }
3329
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003330 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003331 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003332 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3333
3334 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3335 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003336 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003337 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003338 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3339 return;
3340 }
lucaslind2e045e02019-01-24 15:55:30 +08003341 showNetworkNotification(nai, NotificationType.NO_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003342 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003343
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003344 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3345 NetworkCapabilities nc = nai.networkCapabilities;
3346 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003347
Erik Kline065ab6e2016-10-02 18:02:14 +09003348 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003349 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003350 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003351 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003352 }
3353
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003354 @Override
3355 public int getMultipathPreference(Network network) {
3356 enforceAccessPermission();
3357
3358 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003359 if (nai != null && nai.networkCapabilities
3360 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003361 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3362 }
3363
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003364 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3365 if (networkPreference != null) {
3366 return networkPreference;
3367 }
3368
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003369 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3370 }
3371
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003372 @Override
3373 public NetworkRequest getDefaultRequest() {
3374 return mDefaultRequest;
3375 }
3376
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003377 private class InternalHandler extends Handler {
3378 public InternalHandler(Looper looper) {
3379 super(looper);
3380 }
3381
3382 @Override
3383 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003384 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003385 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003386 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003387 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003388 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003389 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003390 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003391 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003392 break;
3393 }
Jason Monkdecd2952013-10-10 14:02:51 -04003394 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003395 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003396 break;
3397 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003398 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003399 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3400 break;
3401 }
3402 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3403 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003404 break;
3405 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003406 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003407 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3408 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3409 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003410 break;
3411 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003412 case EVENT_REGISTER_NETWORK_REQUEST:
3413 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003414 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003415 break;
3416 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003417 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3418 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003419 handleRegisterNetworkRequestWithIntent(msg);
3420 break;
3421 }
Erik Kline57faba92015-11-25 12:49:38 +09003422 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3423 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3424 handleTimedOutNetworkRequest(nri);
3425 break;
3426 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003427 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3428 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3429 break;
3430 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003431 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003432 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003433 break;
3434 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003435 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003436 Network network = (Network) msg.obj;
3437 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003438 break;
3439 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003440 case EVENT_SET_AVOID_UNVALIDATED: {
3441 handleSetAvoidUnvalidated((Network) msg.obj);
3442 break;
3443 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003444 case EVENT_PROMPT_UNVALIDATED: {
3445 handlePromptUnvalidated((Network) msg.obj);
3446 break;
3447 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003448 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3449 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003450 break;
3451 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003452 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3453 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3454 mKeepaliveTracker.handleStartKeepalive(msg);
3455 break;
3456 }
3457 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3458 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3459 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3460 int slot = msg.arg1;
3461 int reason = msg.arg2;
3462 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3463 break;
3464 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003465 case EVENT_SYSTEM_READY: {
3466 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003467 // Might have been called already in handleRegisterNetworkAgent since
3468 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3469 // this several times is fine.
3470 try {
3471 nai.networkMonitor().notifySystemReady();
3472 } catch (RemoteException e) {
3473 e.rethrowFromSystemServer();
3474 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003475 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003476 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003477 break;
3478 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003479 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003480 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003481 break;
3482 }
Erik Klinea24d4592018-01-11 21:07:29 +09003483 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3484 handlePrivateDnsSettingsChanged();
3485 break;
dalyk7301aa42018-03-05 12:42:22 -05003486 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3487 handlePrivateDnsValidationUpdate(
3488 (PrivateDnsValidationUpdate) msg.obj);
3489 break;
junyulai05986c62018-08-07 19:50:45 +08003490 case EVENT_UID_RULES_CHANGED:
3491 handleUidRulesChanged(msg.arg1, msg.arg2);
3492 break;
3493 case EVENT_DATA_SAVER_CHANGED:
3494 handleRestrictBackgroundChanged(toBool(msg.arg1));
3495 break;
lucaslind2e045e02019-01-24 15:55:30 +08003496 case EVENT_TIMEOUT_NOTIFICATION:
3497 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3498 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 }
3500 }
3501 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003502
3503 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003504 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003505 public int tether(String iface, String callerPkg) {
3506 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003507 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003508 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003509 } else {
3510 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3511 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003512 }
3513
3514 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003515 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003516 public int untether(String iface, String callerPkg) {
3517 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003518
3519 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003520 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003521 } else {
3522 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3523 }
3524 }
3525
3526 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003527 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003528 public int getLastTetherError(String iface) {
3529 enforceTetherAccessPermission();
3530
3531 if (isTetheringSupported()) {
3532 return mTethering.getLastTetherError(iface);
3533 } else {
3534 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3535 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003536 }
3537
3538 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003539 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003540 public String[] getTetherableUsbRegexs() {
3541 enforceTetherAccessPermission();
3542 if (isTetheringSupported()) {
3543 return mTethering.getTetherableUsbRegexs();
3544 } else {
3545 return new String[0];
3546 }
3547 }
3548
Lorenzo Colitti18660282016-07-04 12:55:44 +09003549 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003550 public String[] getTetherableWifiRegexs() {
3551 enforceTetherAccessPermission();
3552 if (isTetheringSupported()) {
3553 return mTethering.getTetherableWifiRegexs();
3554 } else {
3555 return new String[0];
3556 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003557 }
3558
Lorenzo Colitti18660282016-07-04 12:55:44 +09003559 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003560 public String[] getTetherableBluetoothRegexs() {
3561 enforceTetherAccessPermission();
3562 if (isTetheringSupported()) {
3563 return mTethering.getTetherableBluetoothRegexs();
3564 } else {
3565 return new String[0];
3566 }
3567 }
3568
Lorenzo Colitti18660282016-07-04 12:55:44 +09003569 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003570 public int setUsbTethering(boolean enable, String callerPkg) {
3571 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003572 if (isTetheringSupported()) {
3573 return mTethering.setUsbTethering(enable);
3574 } else {
3575 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3576 }
3577 }
3578
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003579 // TODO - move iface listing, queries, etc to new module
3580 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003581 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003582 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003583 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003584 return mTethering.getTetherableIfaces();
3585 }
3586
Lorenzo Colitti18660282016-07-04 12:55:44 +09003587 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003588 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003589 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003590 return mTethering.getTetheredIfaces();
3591 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003592
Lorenzo Colitti18660282016-07-04 12:55:44 +09003593 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003594 public String[] getTetheringErroredIfaces() {
3595 enforceTetherAccessPermission();
3596 return mTethering.getErroredIfaces();
3597 }
3598
Lorenzo Colitti18660282016-07-04 12:55:44 +09003599 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003600 public String[] getTetheredDhcpRanges() {
3601 enforceConnectivityInternalPermission();
3602 return mTethering.getTetheredDhcpRanges();
3603 }
3604
Udam Saini0e94c362017-06-07 12:06:28 -07003605 @Override
3606 public boolean isTetheringSupported(String callerPkg) {
3607 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3608 return isTetheringSupported();
3609 }
3610
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003611 // if ro.tether.denied = true we default to no tethering
3612 // gservices could set the secure setting to 1 though to enable it on a build where it
3613 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003614 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003615 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3616 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3617 Settings.Global.TETHER_SUPPORTED, defaultVal));
3618 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003619 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003620
3621 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3622 boolean adminUser = false;
3623 final long token = Binder.clearCallingIdentity();
3624 try {
3625 adminUser = mUserManager.isAdminUser();
3626 } finally {
3627 Binder.restoreCallingIdentity(token);
3628 }
3629
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003630 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003631 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003632
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003633 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003634 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3635 String callerPkg) {
3636 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003637 if (!isTetheringSupported()) {
3638 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3639 return;
3640 }
3641 mTethering.startTethering(type, receiver, showProvisioningUi);
3642 }
3643
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003644 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003645 public void stopTethering(int type, String callerPkg) {
3646 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003647 mTethering.stopTethering(type);
3648 }
3649
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003650 // Called when we lose the default network and have no replacement yet.
3651 // This will automatically be cleared after X seconds or a new default network
3652 // becomes CONNECTED, whichever happens first. The timer is started by the
3653 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003654 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003655 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003656 if (mNetTransitionWakeLock.isHeld()) {
3657 return;
3658 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003659 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003660 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3661 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003662 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003663 mWakelockLogs.log("ACQUIRE for " + forWhom);
3664 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3665 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003666 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003667
Hugo Benichi4c31b342017-03-30 23:18:10 +09003668 // Called when we gain a new default network to release the network transition wakelock in a
3669 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3670 // message is cancelled.
3671 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003672 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003673 if (!mNetTransitionWakeLock.isHeld()) {
3674 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003675 }
3676 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003677 // Cancel self timeout on wakelock hold.
3678 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3679 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3680 mHandler.sendMessageDelayed(msg, 1000);
3681 }
3682
3683 // Called when either message of ensureNetworkTransitionWakelock or
3684 // scheduleReleaseNetworkTransitionWakelock is processed.
3685 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3686 String event = eventName(eventId);
3687 synchronized (this) {
3688 if (!mNetTransitionWakeLock.isHeld()) {
3689 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3690 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3691 return;
3692 }
3693 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003694 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3695 mTotalWakelockDurationMs += lockDuration;
3696 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3697 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003698 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003699 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003700 }
3701
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003702 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003703 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003704 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003705 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003706 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003707 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003708 }
3709
Lorenzo Colitti18660282016-07-04 12:55:44 +09003710 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003711 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003712 enforceAccessPermission();
3713 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003714 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003715 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003716 mHandler.sendMessage(
3717 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3718 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003719
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003720 private void handleReportNetworkConnectivity(
3721 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003722 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003723 if (network == null) {
3724 nai = getDefaultNetwork();
3725 } else {
3726 nai = getNetworkAgentInfoForNetwork(network);
3727 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003728 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3729 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3730 return;
3731 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003732 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003733 if (hasConnectivity == nai.lastValidated) {
3734 return;
3735 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003736 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003737 int netid = nai.network.netId;
3738 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003739 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003740 // Validating a network that has not yet connected could result in a call to
3741 // rematchNetworkAndRequests() which is not meant to work on such networks.
3742 if (!nai.everConnected) {
3743 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003744 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003745 LinkProperties lp = getLinkProperties(nai);
3746 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3747 return;
3748 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003749 try {
3750 nai.networkMonitor().forceReevaluation(uid);
3751 } catch (RemoteException e) {
3752 e.rethrowFromSystemServer();
3753 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003754 }
3755
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003756 /**
3757 * Returns information about the proxy a certain network is using. If given a null network, it
3758 * it will return the proxy for the bound network for the caller app or the default proxy if
3759 * none.
3760 *
3761 * @param network the network we want to get the proxy information for.
3762 * @return Proxy information if a network has a proxy configured, or otherwise null.
3763 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09003764 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003765 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003766 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003767 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003768 if (network == null) {
3769 // Get the network associated with the calling UID.
3770 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
3771 true);
3772 if (activeNetwork == null) {
3773 return null;
3774 }
3775 return getLinkPropertiesProxyInfo(activeNetwork);
3776 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
3777 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3778 // caller may not have.
3779 return getLinkPropertiesProxyInfo(network);
3780 }
3781 // No proxy info available if the calling UID does not have network access.
3782 return null;
3783 }
3784
3785 @VisibleForTesting
3786 protected boolean queryUserAccess(int uid, int netId) {
3787 return NetworkUtils.queryUserAccess(uid, netId);
3788 }
3789
3790 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04003791 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3792 if (nai == null) return null;
3793 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003794 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
3795 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04003796 }
3797 }
3798
Chalard Jean3c443fc2018-06-07 18:37:59 +09003799 @Override
3800 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003801 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003802 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003803 }
3804
Chalard Jean5afbc832018-06-07 18:02:37 +09003805 @Override
3806 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003807 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003808 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003809 }
3810
Jason Monk207900c2014-04-25 15:00:09 -04003811 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003812 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003813 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003814 proxy = null;
3815 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003816 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003817 }
3818
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003819 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
3820 // when any network changes proxy.
3821 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
3822 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003823 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003824 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3825 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3826
Chalard Jean4949dd72018-06-07 17:41:29 +09003827 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09003828 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05003829 }
3830 }
3831
Robert Greenwalt434203a2010-10-11 16:00:27 -07003832 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003833 final private HashMap<Uri, Integer> mUriEventMap;
3834 final private Context mContext;
3835 final private Handler mHandler;
3836
3837 SettingsObserver(Context context, Handler handler) {
3838 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003839 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003840 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003841 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003842 }
3843
Erik Klineda4bfa82015-04-30 12:58:40 +09003844 void observe(Uri uri, int what) {
3845 mUriEventMap.put(uri, what);
3846 final ContentResolver resolver = mContext.getContentResolver();
3847 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003848 }
3849
3850 @Override
3851 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003852 Slog.wtf(TAG, "Should never be reached.");
3853 }
3854
3855 @Override
3856 public void onChange(boolean selfChange, Uri uri) {
3857 final Integer what = mUriEventMap.get(uri);
3858 if (what != null) {
3859 mHandler.obtainMessage(what.intValue()).sendToTarget();
3860 } else {
3861 loge("No matching event to send for URI=" + uri);
3862 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003863 }
3864 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003865
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003866 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003867 Slog.d(TAG, s);
3868 }
3869
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003870 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003871 Slog.e(TAG, s);
3872 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003873
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003874 private static void loge(String s, Throwable t) {
3875 Slog.e(TAG, s, t);
3876 }
3877
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003878 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003879 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003880 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3881 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3882 *
3883 * @param oldPackage Package name of the application which currently controls VPN, which will
3884 * be replaced. If there is no such application, this should should either be
3885 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3886 * @param newPackage Package name of the application which should gain control of VPN, or
3887 * {@code null} to disable.
3888 * @param userId User for whom to prepare the new VPN.
3889 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003890 * @hide
3891 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003892 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003893 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3894 int userId) {
3895 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003896
Hugo Benichi20035e02017-04-26 14:53:28 +09003897 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003898 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003899 Vpn vpn = mVpns.get(userId);
3900 if (vpn != null) {
3901 return vpn.prepare(oldPackage, newPackage);
3902 } else {
3903 return false;
3904 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003905 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003906 }
3907
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003908 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003909 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3910 * This method is used by system-privileged apps.
3911 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3912 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3913 *
3914 * @param packageName The package for which authorization state should change.
3915 * @param userId User for whom {@code packageName} is installed.
3916 * @param authorized {@code true} if this app should be able to start a VPN connection without
3917 * explicit user approval, {@code false} if not.
3918 *
Jeff Davidson05542602014-08-11 14:07:27 -07003919 * @hide
3920 */
3921 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003922 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3923 enforceCrossUserPermission(userId);
3924
Hugo Benichi20035e02017-04-26 14:53:28 +09003925 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003926 Vpn vpn = mVpns.get(userId);
3927 if (vpn != null) {
3928 vpn.setPackageAuthorization(packageName, authorized);
3929 }
Jeff Davidson05542602014-08-11 14:07:27 -07003930 }
3931 }
3932
3933 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003934 * Configure a TUN interface and return its file descriptor. Parameters
3935 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003936 * and not available in ConnectivityManager. Permissions are checked in
3937 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003938 * @hide
3939 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003940 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003941 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003942 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003943 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003944 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003945 return mVpns.get(user).establish(config);
3946 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003947 }
3948
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003949 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003950 * Start legacy VPN, controlling native daemons as needed. Creates a
3951 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003952 */
3953 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003954 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003955 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003956 final LinkProperties egress = getActiveLinkProperties();
3957 if (egress == null) {
3958 throw new IllegalStateException("Missing active network connection");
3959 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003960 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003961 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003962 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3963 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003964 }
3965
3966 /**
3967 * Return the information of the ongoing legacy VPN. This method is used
3968 * by VpnSettings and not available in ConnectivityManager. Permissions
3969 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003970 */
3971 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003972 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3973 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003974
Hugo Benichi20035e02017-04-26 14:53:28 +09003975 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003976 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003977 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003978 }
3979
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003980 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003981 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3982 * and not available in ConnectivityManager.
3983 */
3984 @Override
3985 public VpnInfo[] getAllVpnInfo() {
3986 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003987 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003988 if (mLockdownEnabled) {
3989 return new VpnInfo[0];
3990 }
3991
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003992 List<VpnInfo> infoList = new ArrayList<>();
3993 for (int i = 0; i < mVpns.size(); i++) {
3994 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3995 if (info != null) {
3996 infoList.add(info);
3997 }
3998 }
3999 return infoList.toArray(new VpnInfo[infoList.size()]);
4000 }
4001 }
4002
4003 /**
4004 * @return VPN information for accounting, or null if we can't retrieve all required
4005 * information, e.g primary underlying iface.
4006 */
4007 @Nullable
4008 private VpnInfo createVpnInfo(Vpn vpn) {
4009 VpnInfo info = vpn.getVpnInfo();
4010 if (info == null) {
4011 return null;
4012 }
4013 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4014 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4015 // the underlyingNetworks list.
4016 if (underlyingNetworks == null) {
4017 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4018 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4019 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4020 }
4021 } else if (underlyingNetworks.length > 0) {
4022 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4023 if (linkProperties != null) {
4024 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4025 }
4026 }
4027 return info.primaryUnderlyingIface == null ? null : info;
4028 }
4029
4030 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004031 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4032 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004033 * Permissions are checked in Vpn class.
4034 * @hide
4035 */
4036 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004037 public VpnConfig getVpnConfig(int userId) {
4038 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004039 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004040 Vpn vpn = mVpns.get(userId);
4041 if (vpn != null) {
4042 return vpn.getVpnConfig();
4043 } else {
4044 return null;
4045 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004046 }
4047 }
4048
Chalard Jean6b65ec72018-05-18 22:02:56 +09004049 /**
4050 * Ask all VPN objects to recompute and update their capabilities.
4051 *
4052 * When underlying networks change, VPNs may have to update capabilities to reflect things
4053 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4054 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4055 * handler thread through their agent, this is asynchronous. When the capabilities objects
4056 * are computed they will be up-to-date as they are computed synchronously from here and
4057 * this is running on the ConnectivityService thread.
4058 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
4059 */
4060 private void updateAllVpnsCapabilities() {
4061 synchronized (mVpns) {
4062 for (int i = 0; i < mVpns.size(); i++) {
4063 final Vpn vpn = mVpns.valueAt(i);
4064 vpn.updateCapabilities();
4065 }
4066 }
4067 }
4068
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004069 @Override
4070 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004071 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4072 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4073 return false;
4074 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004075
Hugo Benichi69744342017-11-27 10:57:16 +09004076 synchronized (mVpns) {
4077 // Tear down existing lockdown if profile was removed
4078 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4079 if (mLockdownEnabled) {
4080 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4081 if (profileTag == null) {
4082 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4083 return false;
4084 }
4085 String profileName = new String(profileTag);
4086 final VpnProfile profile = VpnProfile.decode(
4087 profileName, mKeyStore.get(Credentials.VPN + profileName));
4088 if (profile == null) {
4089 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4090 setLockdownTracker(null);
4091 return true;
4092 }
4093 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004094 Vpn vpn = mVpns.get(user);
4095 if (vpn == null) {
4096 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4097 return false;
4098 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004099 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004100 } else {
4101 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004102 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004103 }
4104
4105 return true;
4106 }
4107
4108 /**
4109 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4110 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4111 */
Hugo Benichi69744342017-11-27 10:57:16 +09004112 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004113 private void setLockdownTracker(LockdownVpnTracker tracker) {
4114 // Shutdown any existing tracker
4115 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004116 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4117 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004118 mLockdownTracker = null;
4119 if (existing != null) {
4120 existing.shutdown();
4121 }
4122
Robin Leec3736bc2017-03-10 16:19:54 +00004123 if (tracker != null) {
4124 mLockdownTracker = tracker;
4125 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004126 }
4127 }
4128
Hugo Benichi69744342017-11-27 10:57:16 +09004129 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004130 private void throwIfLockdownEnabled() {
4131 if (mLockdownEnabled) {
4132 throw new IllegalStateException("Unavailable in lockdown mode");
4133 }
4134 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004135
Robin Lee244ce8e2016-01-05 18:03:46 +00004136 /**
Robin Lee17e61832016-05-09 13:46:28 +01004137 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4138 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004139 *
Robin Lee17e61832016-05-09 13:46:28 +01004140 * @return {@code true} if the service was started, the service was already connected, or there
4141 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004142 */
Robin Lee17e61832016-05-09 13:46:28 +01004143 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004144 synchronized (mVpns) {
4145 Vpn vpn = mVpns.get(userId);
4146 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004147 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004148 // exists already.
4149 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4150 return false;
4151 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004152
Robin Lee812800c2016-05-13 15:38:08 +01004153 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004154 }
4155 }
4156
4157 @Override
Charles He36738632017-05-15 17:07:18 +01004158 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4159 enforceSettingsPermission();
4160 enforceCrossUserPermission(userId);
4161
4162 synchronized (mVpns) {
4163 Vpn vpn = mVpns.get(userId);
4164 if (vpn == null) {
4165 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4166 return false;
4167 }
4168 return vpn.isAlwaysOnPackageSupported(packageName);
4169 }
4170 }
4171
4172 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004173 public boolean setAlwaysOnVpnPackage(
4174 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4175 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004176 enforceCrossUserPermission(userId);
4177
Robin Lee244ce8e2016-01-05 18:03:46 +00004178 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004179 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4180 if (LockdownVpnTracker.isEnabled()) {
4181 return false;
4182 }
4183
Robin Lee244ce8e2016-01-05 18:03:46 +00004184 Vpn vpn = mVpns.get(userId);
4185 if (vpn == null) {
4186 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4187 return false;
4188 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004189 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004190 return false;
4191 }
Robin Lee17e61832016-05-09 13:46:28 +01004192 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004193 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004194 return false;
4195 }
4196 }
4197 return true;
4198 }
4199
4200 @Override
4201 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004202 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004203 enforceCrossUserPermission(userId);
4204
4205 synchronized (mVpns) {
4206 Vpn vpn = mVpns.get(userId);
4207 if (vpn == null) {
4208 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4209 return null;
4210 }
4211 return vpn.getAlwaysOnPackage();
4212 }
4213 }
4214
Wink Savilleab9321d2013-06-29 21:10:57 -07004215 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004216 public boolean isVpnLockdownEnabled(int userId) {
4217 enforceControlAlwaysOnVpnPermission();
4218 enforceCrossUserPermission(userId);
4219
4220 synchronized (mVpns) {
4221 Vpn vpn = mVpns.get(userId);
4222 if (vpn == null) {
4223 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4224 return false;
4225 }
4226 return vpn.getLockdown();
4227 }
4228 }
4229
4230 @Override
4231 public List<String> getVpnLockdownWhitelist(int userId) {
4232 enforceControlAlwaysOnVpnPermission();
4233 enforceCrossUserPermission(userId);
4234
4235 synchronized (mVpns) {
4236 Vpn vpn = mVpns.get(userId);
4237 if (vpn == null) {
4238 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4239 return null;
4240 }
4241 return vpn.getLockdownWhitelist();
4242 }
4243 }
4244
4245 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004246 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004247 // TODO: Remove? Any reason to trigger a provisioning check?
4248 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004249 }
4250
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004251 /** Location to an updatable file listing carrier provisioning urls.
4252 * An example:
4253 *
4254 * <?xml version="1.0" encoding="utf-8"?>
4255 * <provisioningUrls>
4256 * <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 -07004257 * </provisioningUrls>
4258 */
4259 private static final String PROVISIONING_URL_PATH =
4260 "/data/misc/radio/provisioning_urls.xml";
4261 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004262
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004263 /** XML tag for root element. */
4264 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4265 /** XML tag for individual url */
4266 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004267 /** XML attribute for mcc */
4268 private static final String ATTR_MCC = "mcc";
4269 /** XML attribute for mnc */
4270 private static final String ATTR_MNC = "mnc";
4271
Paul Jensen434dde82015-06-11 09:43:30 -04004272 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004273 FileReader fileReader = null;
4274 XmlPullParser parser = null;
4275 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004276
4277 try {
4278 fileReader = new FileReader(mProvisioningUrlFile);
4279 parser = Xml.newPullParser();
4280 parser.setInput(fileReader);
4281 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4282
4283 while (true) {
4284 XmlUtils.nextElement(parser);
4285
4286 String element = parser.getName();
4287 if (element == null) break;
4288
Paul Jensen434dde82015-06-11 09:43:30 -04004289 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004290 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4291 try {
4292 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4293 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4294 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4295 parser.next();
4296 if (parser.getEventType() == XmlPullParser.TEXT) {
4297 return parser.getText();
4298 }
4299 }
4300 }
4301 } catch (NumberFormatException e) {
4302 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4303 }
4304 }
4305 }
4306 return null;
4307 } catch (FileNotFoundException e) {
4308 loge("Carrier Provisioning Urls file not found");
4309 } catch (XmlPullParserException e) {
4310 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4311 } catch (IOException e) {
4312 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4313 } finally {
4314 if (fileReader != null) {
4315 try {
4316 fileReader.close();
4317 } catch (IOException e) {}
4318 }
4319 }
4320 return null;
4321 }
4322
Wink Saville42d4f082013-07-20 20:31:59 -07004323 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004324 public String getMobileProvisioningUrl() {
4325 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004326 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004327 if (TextUtils.isEmpty(url)) {
4328 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004329 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004330 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004331 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004332 }
Wink Saville8cf35602013-07-10 23:00:07 -07004333 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004334 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004335 String phoneNumber = mTelephonyManager.getLine1Number();
4336 if (TextUtils.isEmpty(phoneNumber)) {
4337 phoneNumber = "0000000000";
4338 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004339 url = String.format(url,
4340 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4341 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004342 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004343 }
4344
Wink Savilleab9321d2013-06-29 21:10:57 -07004345 return url;
4346 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004347
Wink Saville948282b2013-08-29 08:55:16 -07004348 @Override
4349 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004350 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004351 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004352 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4353 return;
4354 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004355 final long ident = Binder.clearCallingIdentity();
4356 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004357 // Concatenate the range of types onto the range of NetIDs.
4358 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4359 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004360 } finally {
4361 Binder.restoreCallingIdentity(ident);
4362 }
Wink Saville948282b2013-08-29 08:55:16 -07004363 }
Wink Saville7788c612013-08-29 14:57:08 -07004364
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004365 @Override
4366 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004367 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004368 final long ident = Binder.clearCallingIdentity();
4369 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004370 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004371 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004372 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4373 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004374 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004375 } finally {
4376 Binder.restoreCallingIdentity(ident);
4377 }
4378 }
4379
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004380 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004381 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004382 Vpn userVpn = mVpns.get(userId);
4383 if (userVpn != null) {
4384 loge("Starting user already has a VPN");
4385 return;
4386 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004387 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004388 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004389 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4390 updateLockdownVpn();
4391 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004392 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004393 }
4394
4395 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004396 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004397 Vpn userVpn = mVpns.get(userId);
4398 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004399 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004400 return;
4401 }
Robin Lee17e61832016-05-09 13:46:28 +01004402 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004403 mVpns.delete(userId);
4404 }
4405 }
4406
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004407 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004408 mPermissionMonitor.onUserAdded(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004409 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004410 final int vpnsSize = mVpns.size();
4411 for (int i = 0; i < vpnsSize; i++) {
4412 Vpn vpn = mVpns.valueAt(i);
4413 vpn.onUserAdded(userId);
4414 }
4415 }
4416 }
4417
4418 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004419 mPermissionMonitor.onUserRemoved(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004420 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004421 final int vpnsSize = mVpns.size();
4422 for (int i = 0; i < vpnsSize; i++) {
4423 Vpn vpn = mVpns.valueAt(i);
4424 vpn.onUserRemoved(userId);
4425 }
4426 }
4427 }
4428
junyulai2454b692018-11-01 17:16:31 +08004429 private void onPackageAdded(String packageName, int uid) {
4430 if (TextUtils.isEmpty(packageName) || uid < 0) {
4431 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4432 return;
4433 }
4434 mPermissionMonitor.onPackageAdded(packageName, uid);
4435 }
4436
junyulaiefb04d32018-11-12 22:39:30 +08004437 private void onPackageReplaced(String packageName, int uid) {
4438 if (TextUtils.isEmpty(packageName) || uid < 0) {
4439 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4440 return;
4441 }
4442 final int userId = UserHandle.getUserId(uid);
4443 synchronized (mVpns) {
4444 final Vpn vpn = mVpns.get(userId);
4445 if (vpn == null) {
4446 return;
4447 }
4448 // Legacy always-on VPN won't be affected since the package name is not set.
4449 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4450 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4451 + userId);
4452 vpn.startAlwaysOnVpn();
4453 }
4454 }
4455 }
4456
4457 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004458 if (TextUtils.isEmpty(packageName) || uid < 0) {
4459 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4460 return;
4461 }
4462 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004463
4464 final int userId = UserHandle.getUserId(uid);
4465 synchronized (mVpns) {
4466 final Vpn vpn = mVpns.get(userId);
4467 if (vpn == null) {
4468 return;
4469 }
4470 // Legacy always-on VPN won't be affected since the package name is not set.
4471 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4472 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4473 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004474 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004475 }
4476 }
junyulai2454b692018-11-01 17:16:31 +08004477 }
4478
Robin Lee89e7a692016-02-29 14:38:17 +00004479 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004480 synchronized (mVpns) {
4481 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4482 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4483 updateLockdownVpn();
4484 } else {
4485 startAlwaysOnVpn(userId);
4486 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004487 }
4488 }
4489
junyulai2454b692018-11-01 17:16:31 +08004490 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004491 @Override
4492 public void onReceive(Context context, Intent intent) {
4493 final String action = intent.getAction();
4494 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004495 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4496 final Uri packageData = intent.getData();
4497 final String packageName =
4498 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004499 if (userId == UserHandle.USER_NULL) return;
4500
Robin Lee323f29d2016-05-04 16:38:06 +01004501 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004502 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004503 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004504 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004505 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4506 onUserAdded(userId);
4507 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4508 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004509 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4510 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004511 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4512 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004513 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4514 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004515 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004516 final boolean isReplacing = intent.getBooleanExtra(
4517 Intent.EXTRA_REPLACING, false);
4518 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004519 }
4520 }
4521 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004522
Robin Lee95204e02017-01-27 11:59:22 +00004523 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4524 @Override
4525 public void onReceive(Context context, Intent intent) {
4526 // Try creating lockdown tracker, since user present usually means
4527 // unlocked keystore.
4528 updateLockdownVpn();
4529 mContext.unregisterReceiver(this);
4530 }
4531 };
4532
Chalard Jean4133a122018-06-04 13:33:12 +09004533 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4534 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004535
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004536 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4537 // Map from UID to number of NetworkRequests that UID has filed.
4538 @GuardedBy("mUidToNetworkRequestCount")
4539 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4540
Robert Greenwalta67be032014-05-16 15:49:14 -07004541 private static class NetworkFactoryInfo {
4542 public final String name;
4543 public final Messenger messenger;
4544 public final AsyncChannel asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004545 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004546
Chalard Jean08577fc2018-05-02 21:14:54 +09004547 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4548 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004549 this.name = name;
4550 this.messenger = messenger;
4551 this.asyncChannel = asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004552 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004553 }
4554 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004555
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004556 private void ensureNetworkRequestHasType(NetworkRequest request) {
4557 if (request.type == NetworkRequest.Type.NONE) {
4558 throw new IllegalArgumentException(
4559 "All NetworkRequests in ConnectivityService must have a type");
4560 }
4561 }
4562
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004563 /**
4564 * Tracks info about the requester.
4565 * Also used to notice when the calling process dies so we can self-expire
4566 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004567 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004568 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004569 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004570 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004571 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004572 final int mPid;
4573 final int mUid;
4574 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004575
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004576 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004577 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004578 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004579 mPendingIntent = pi;
4580 messenger = null;
4581 mBinder = null;
4582 mPid = getCallingPid();
4583 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004584 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004585 }
4586
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004587 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004588 super();
4589 messenger = m;
4590 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004591 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004592 mBinder = binder;
4593 mPid = getCallingPid();
4594 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004595 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004596 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004597
4598 try {
4599 mBinder.linkToDeath(this, 0);
4600 } catch (RemoteException e) {
4601 binderDied();
4602 }
4603 }
4604
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004605 private void enforceRequestCountLimit() {
4606 synchronized (mUidToNetworkRequestCount) {
4607 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4608 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004609 throw new ServiceSpecificException(
4610 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004611 }
4612 mUidToNetworkRequestCount.put(mUid, networkRequests);
4613 }
4614 }
4615
Robert Greenwalt9258c642014-03-26 16:47:06 -07004616 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004617 if (mBinder != null) {
4618 mBinder.unlinkToDeath(this, 0);
4619 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004620 }
4621
4622 public void binderDied() {
4623 log("ConnectivityService NetworkRequestInfo binderDied(" +
4624 request + ", " + mBinder + ")");
4625 releaseNetworkRequest(request);
4626 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004627
4628 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004629 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004630 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004631 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004632 }
4633
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004634 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4635 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4636 if (badCapability != null) {
4637 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004638 }
4639 }
4640
Chalard Jeanb03a6222018-04-11 21:09:10 +09004641 // This checks that the passed capabilities either do not request a specific SSID, or the
4642 // calling app has permission to do so.
4643 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4644 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004645 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004646 throw new SecurityException("Insufficient permissions to request a specific SSID");
4647 }
4648 }
4649
Erik Kline9d598e12015-07-13 16:37:51 +09004650 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004651 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004652 synchronized (nai) {
4653 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4654 if (nri.request.networkCapabilities.hasSignalStrength() &&
4655 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4656 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4657 }
4658 }
4659 }
Chalard Jean4133a122018-06-04 13:33:12 +09004660 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004661 }
4662
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004663 private void updateSignalStrengthThresholds(
4664 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4665 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004666 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004667 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4668
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004669 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004670 String detail;
4671 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4672 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4673 } else {
4674 detail = reason;
4675 }
4676 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4677 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4678 }
4679
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004680 nai.asyncChannel.sendMessage(
4681 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004682 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004683 }
4684
Etan Cohen859748f2017-04-03 17:42:34 -07004685 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4686 if (nc == null) {
4687 return;
4688 }
4689 NetworkSpecifier ns = nc.getNetworkSpecifier();
4690 if (ns == null) {
4691 return;
4692 }
4693 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4694 ns.assertValidFromUid(Binder.getCallingUid());
4695 }
4696
Robert Greenwalt9258c642014-03-26 16:47:06 -07004697 @Override
4698 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004699 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004700 final NetworkRequest.Type type = (networkCapabilities == null)
4701 ? NetworkRequest.Type.TRACK_DEFAULT
4702 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004703 // If the requested networkCapabilities is null, take them instead from
4704 // the default network request. This allows callers to keep track of
4705 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004706 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004707 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004708 enforceAccessPermission();
4709 } else {
4710 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4711 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004712 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4713 // of the app when the request is filed, but we never change the request if the app
4714 // changes network state. http://b/29964605
4715 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004716 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004717 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004718 ensureSufficientPermissionsForRequest(networkCapabilities,
4719 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004720 // Set the UID range for this request to the single UID of the requester, or to an empty
4721 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004722 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4723 // are no visible methods to set the UIDs, an app could use reflection to try and get
4724 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004725 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004726
Etan Cohenba07c8c2017-02-05 10:42:27 -08004727 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004728 throw new IllegalArgumentException("Bad timeout specified");
4729 }
Etan Cohen859748f2017-04-03 17:42:34 -07004730 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004731
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004732 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004733 nextNetworkRequestId(), type);
4734 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004735 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004736
4737 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004738 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004739 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004740 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004741 }
4742 return networkRequest;
4743 }
4744
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004745 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004746 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004747 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004748 } else {
4749 enforceChangePermission();
4750 }
4751 }
4752
fenglub15e72b2015-03-20 11:29:56 -07004753 @Override
fengludb571472015-04-21 17:12:05 -07004754 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004755 enforceAccessPermission();
4756 NetworkAgentInfo nai = null;
4757 if (network == null) {
4758 return false;
4759 }
4760 synchronized (mNetworkForNetId) {
4761 nai = mNetworkForNetId.get(network.netId);
4762 }
4763 if (nai != null) {
4764 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004765 synchronized (mBandwidthRequests) {
4766 final int uid = Binder.getCallingUid();
4767 Integer uidReqs = mBandwidthRequests.get(uid);
4768 if (uidReqs == null) {
4769 uidReqs = new Integer(0);
4770 }
4771 mBandwidthRequests.put(uid, ++uidReqs);
4772 }
fenglub15e72b2015-03-20 11:29:56 -07004773 return true;
4774 }
4775 return false;
4776 }
4777
Felipe Lemeee27cab2016-06-20 16:36:29 -07004778 private boolean isSystem(int uid) {
4779 return uid < Process.FIRST_APPLICATION_UID;
4780 }
fenglub15e72b2015-03-20 11:29:56 -07004781
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004782 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004783 final int uid = Binder.getCallingUid();
4784 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004785 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004786 return;
4787 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004788 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4789 // Policy already enforced.
4790 return;
4791 }
4792 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4793 // If UID is restricted, don't allow them to bring up metered APNs.
4794 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004795 }
4796 }
4797
Robert Greenwalt9258c642014-03-26 16:47:06 -07004798 @Override
4799 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4800 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004801 checkNotNull(operation, "PendingIntent cannot be null.");
4802 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4803 enforceNetworkRequestPermissions(networkCapabilities);
4804 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004805 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004806 ensureSufficientPermissionsForRequest(networkCapabilities,
4807 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004808 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004809 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004810
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004811 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004812 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4813 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004814 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004815 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4816 nri));
4817 return networkRequest;
4818 }
4819
Jeremy Joslin79294842014-12-03 17:15:28 -08004820 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4821 mHandler.sendMessageDelayed(
4822 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4823 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4824 }
4825
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004826 @Override
4827 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004828 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004829 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4830 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004831 }
4832
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004833 // In order to implement the compatibility measure for pre-M apps that call
4834 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4835 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4836 // This ensures it has permission to do so.
4837 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4838 if (nc == null) {
4839 return false;
4840 }
4841 int[] transportTypes = nc.getTransportTypes();
4842 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4843 return false;
4844 }
4845 try {
4846 mContext.enforceCallingOrSelfPermission(
4847 android.Manifest.permission.ACCESS_WIFI_STATE,
4848 "ConnectivityService");
4849 } catch (SecurityException e) {
4850 return false;
4851 }
4852 return true;
4853 }
4854
Robert Greenwalt9258c642014-03-26 16:47:06 -07004855 @Override
4856 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4857 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004858 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4859 enforceAccessPermission();
4860 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004861
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004862 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004863 ensureSufficientPermissionsForRequest(networkCapabilities,
4864 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004865 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004866 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4867 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4868 // onLost and onAvailable callbacks when networks move in and out of the background.
4869 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4870 // can't request networks.
4871 restrictBackgroundRequestForCaller(nc);
4872 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004873
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004874 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004875 NetworkRequest.Type.LISTEN);
4876 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004877 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004878
4879 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4880 return networkRequest;
4881 }
4882
4883 @Override
4884 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4885 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004886 checkNotNull(operation, "PendingIntent cannot be null.");
4887 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4888 enforceAccessPermission();
4889 }
Etan Cohen859748f2017-04-03 17:42:34 -07004890 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004891 ensureSufficientPermissionsForRequest(networkCapabilities,
4892 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004893
Chalard Jeandda156a2018-01-10 21:19:32 +09004894 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004895 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004896
4897 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004898 NetworkRequest.Type.LISTEN);
4899 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004900 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004901
4902 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004903 }
4904
Erik Klineacdd6392016-07-07 16:50:58 +09004905 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004906 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004907 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004908 mHandler.sendMessage(mHandler.obtainMessage(
4909 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004910 }
4911
4912 @Override
Chalard Jean08577fc2018-05-02 21:14:54 +09004913 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004914 enforceConnectivityInternalPermission();
Chalard Jean08577fc2018-05-02 21:14:54 +09004915 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
4916 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07004917 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean08577fc2018-05-02 21:14:54 +09004918 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07004919 }
4920
Robert Greenwalta67be032014-05-16 15:49:14 -07004921 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004922 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004923 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4924 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4925 }
4926
4927 @Override
4928 public void unregisterNetworkFactory(Messenger messenger) {
4929 enforceConnectivityInternalPermission();
4930 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4931 }
4932
4933 private void handleUnregisterNetworkFactory(Messenger messenger) {
4934 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4935 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004936 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004937 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004938 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004939 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004940 }
4941
Robert Greenwalt7b816022014-04-18 15:25:25 -07004942 /**
4943 * NetworkAgentInfo supporting a request by requestId.
4944 * These have already been vetted (their Capabilities satisfy the request)
4945 * and the are the highest scored network available.
4946 * the are keyed off the Requests requestId.
4947 */
Hugo Benichicd952782017-09-20 11:20:14 +09004948 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4949 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004950 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004951
Paul Jensen31a94f42015-02-13 14:18:39 -05004952 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4953 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004954 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004955 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4956 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4957 // there may not be a strict 1:1 correlation between the two.
4958 @GuardedBy("mNetworkForNetId")
4959 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004960
Robert Greenwalt7b816022014-04-18 15:25:25 -07004961 // NetworkAgentInfo keyed off its connecting messenger
4962 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004963 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004964 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004965
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004966 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004967 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004968
Paul Jensen2c311d62014-11-17 12:34:51 -05004969 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004970 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004971
Erik Klineda4bfa82015-04-30 12:58:40 +09004972 // Request used to optionally keep mobile data active even when higher
4973 // priority networks like Wi-Fi are active.
4974 private final NetworkRequest mDefaultMobileDataRequest;
4975
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004976 // Request used to optionally keep wifi data active even when higher
4977 // priority networks like ethernet are active.
4978 private final NetworkRequest mDefaultWifiRequest;
4979
Hugo Benichicd952782017-09-20 11:20:14 +09004980 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4981 synchronized (mNetworkForRequestId) {
4982 return mNetworkForRequestId.get(requestId);
4983 }
4984 }
4985
4986 private void clearNetworkForRequest(int requestId) {
4987 synchronized (mNetworkForRequestId) {
4988 mNetworkForRequestId.remove(requestId);
4989 }
4990 }
4991
4992 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4993 synchronized (mNetworkForRequestId) {
4994 mNetworkForRequestId.put(requestId, nai);
4995 }
4996 }
4997
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004998 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004999 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005000 }
5001
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005002 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005003 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005004 }
5005
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005006 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5007 return nri.request.requestId == mDefaultRequest.requestId;
5008 }
5009
Chalard Jean08577fc2018-05-02 21:14:54 +09005010 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5011 // changes that would conflict throughout the automerger graph. Having this method temporarily
5012 // helps with the process of going through with all these dependent changes across the entire
5013 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005014 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005015 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005016 int currentScore, NetworkMisc networkMisc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005017 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5018 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5019 }
5020
5021 /**
5022 * Register a new agent with ConnectivityService to handle a network.
5023 *
5024 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5025 * @param networkInfo the initial info associated with this network. It can be updated later :
5026 * see {@link #updateNetworkInfo}.
5027 * @param linkProperties the initial link properties of this network. They can be updated
5028 * later : see {@link #updateLinkProperties}.
5029 * @param networkCapabilities the initial capabilites of this network. They can be updated
5030 * later : see {@link #updateNetworkCapabilities}.
5031 * @param currentScore the initial score of the network. See
5032 * {@link NetworkAgentInfo#getCurrentScore}.
5033 * @param networkMisc metadata about the network. This is never updated.
5034 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5035 */
5036 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5037 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5038 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005039 enforceConnectivityInternalPermission();
5040
Rubin Xu1bb5c082017-09-05 18:40:49 +01005041 LinkProperties lp = new LinkProperties(linkProperties);
5042 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005043 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5044 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005045 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005046 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005047 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean08577fc2018-05-02 21:14:54 +09005048 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5049 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005050 // Make sure the network capabilities reflect what the agent info says.
5051 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005052 final String extraInfo = networkInfo.getExtraInfo();
5053 final String name = TextUtils.isEmpty(extraInfo)
5054 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005055 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005056 final long token = Binder.clearCallingIdentity();
5057 try {
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +09005058 mContext.getSystemService(NetworkStack.class).makeNetworkMonitor(
5059 toStableParcelable(nai.network), name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005060 } finally {
5061 Binder.restoreCallingIdentity(token);
5062 }
5063 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5064 // If the network disconnects or sends any other event before that, messages are deferred by
5065 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5066 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005067 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005068 }
5069
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005070 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5071 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005072 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005073 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005074 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005075 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005076 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005077 synchronized (this) {
5078 if (mSystemReady) {
5079 try {
5080 networkMonitor.notifySystemReady();
5081 } catch (RemoteException e) {
5082 e.rethrowFromSystemServer();
5083 }
5084 }
5085 }
5086
5087 try {
5088 networkMonitor.start();
5089 } catch (RemoteException e) {
5090 e.rethrowFromSystemServer();
5091 }
Erik Klinee5dac902018-03-04 21:01:01 +09005092 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5093 NetworkInfo networkInfo = nai.networkInfo;
5094 nai.networkInfo = null;
5095 updateNetworkInfo(nai, networkInfo);
5096 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005097 }
5098
lucaslin25a4ec32018-11-28 12:51:55 +08005099 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5100 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005101 int netId = networkAgent.network.netId;
5102
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005103 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
5104 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09005105 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08005106 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09005107 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005108
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005109 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005110 updateMtu(newLp, oldLp);
5111 // TODO - figure out what to do for clat
5112// for (LinkProperties lp : newLp.getStackedLinks()) {
5113// updateMtu(lp, null);
5114// }
lucaslin041a1af2018-11-28 19:27:52 +08005115 if (isDefaultNetwork(networkAgent)) {
5116 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5117 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005118
Erik Kline94887872016-04-05 13:30:49 +09005119 updateRoutes(newLp, oldLp, netId);
5120 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005121 // Make sure LinkProperties represents the latest private DNS status.
5122 // This does not need to be done before updateDnses because the
5123 // LinkProperties are not the source of the private DNS configuration.
5124 // updateDnses will fetch the private DNS configuration from DnsManager.
5125 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005126
Paul Jensene0bef712014-12-10 15:12:18 -05005127 if (isDefaultNetwork(networkAgent)) {
5128 handleApplyDefaultProxy(newLp.getHttpProxy());
5129 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005130 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005131 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005132 // TODO - move this check to cover the whole function
5133 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005134 synchronized (networkAgent) {
5135 networkAgent.linkProperties = newLp;
5136 }
lucaslin25a4ec32018-11-28 12:51:55 +08005137 // Start or stop clat accordingly to network state.
5138 networkAgent.updateClat(mNMS);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005139 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005140 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005141 try {
5142 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5143 } catch (RemoteException e) {
5144 e.rethrowFromSystemServer();
5145 }
lucaslin25a4ec32018-11-28 12:51:55 +08005146 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5147 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005148 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005149
5150 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005151 }
5152
Joel Scherpelz668370b2017-06-08 15:35:21 +09005153 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005154 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005155 // marks on unsupported interfaces is harmless.
5156 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5157 return;
5158 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005159
Joel Scherpelz668370b2017-06-08 15:35:21 +09005160 int mark = mContext.getResources().getInteger(
5161 com.android.internal.R.integer.config_networkWakeupPacketMark);
5162 int mask = mContext.getResources().getInteger(
5163 com.android.internal.R.integer.config_networkWakeupPacketMask);
5164
5165 // Mask/mark of zero will not detect anything interesting.
5166 // Don't install rules unless both values are nonzero.
5167 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005168 return;
5169 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005170
5171 final String prefix = "iface:" + iface;
5172 try {
5173 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005174 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005175 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005176 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005177 }
5178 } catch (Exception e) {
5179 loge("Exception modifying wakeup packet monitoring: " + e);
5180 }
5181
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005182 }
5183
5184 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5185 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005186 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005187 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5188 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005189 for (String iface : interfaceDiff.added) {
5190 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005191 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005192 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005193 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005194 } catch (Exception e) {
5195 loge("Exception adding interface: " + e);
5196 }
5197 }
5198 for (String iface : interfaceDiff.removed) {
5199 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005200 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005201 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005202 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005203 } catch (Exception e) {
5204 loge("Exception removing interface: " + e);
5205 }
5206 }
5207 }
5208
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005209 /**
5210 * Have netd update routes from oldLp to newLp.
5211 * @return true if routes changed between oldLp and newLp
5212 */
5213 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005214 // Compare the route diff to determine which routes should be added and removed.
5215 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5216 oldLp != null ? oldLp.getAllRoutes() : null,
5217 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005218
5219 // add routes before removing old in case it helps with continuous connectivity
5220
Chalard Jean4d660112018-06-04 16:52:49 +09005221 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 for (RouteInfo route : routeDiff.added) {
5223 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005224 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005225 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005226 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005227 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005228 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5229 loge("Exception in addRoute for non-gateway: " + e);
5230 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005231 }
5232 }
5233 for (RouteInfo route : routeDiff.added) {
5234 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005235 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005236 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005237 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005238 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005239 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5240 loge("Exception in addRoute for gateway: " + e);
5241 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005242 }
5243 }
5244
5245 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005246 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005247 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005248 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005249 } catch (Exception e) {
5250 loge("Exception in removeRoute: " + e);
5251 }
5252 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005253 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005254 }
Erik Kline41368502015-06-17 13:19:54 +09005255
Erik Kline94887872016-04-05 13:30:49 +09005256 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5257 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5258 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005259 }
Erik Kline94887872016-04-05 13:30:49 +09005260
Erik Kline1742fe12017-12-13 19:40:49 +09005261 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5262 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5263
Erik Klinea24d4592018-01-11 21:07:29 +09005264 if (DBG) {
5265 final Collection<InetAddress> dnses = newLp.getDnsServers();
5266 log("Setting DNS servers for network " + netId + " to " + dnses);
5267 }
Erik Kline94887872016-04-05 13:30:49 +09005268 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005269 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005270 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005271 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005272 }
Erik Kline4edba012017-04-07 15:29:29 +09005273 }
5274
Luke Huang8a462ec2018-08-24 20:33:16 +08005275 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005276 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005277 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005278 }
5279 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005280 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005281 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005282 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005283 }
5284
Paul Jensen3d194ea2015-06-16 14:27:36 -04005285 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005286 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5287 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5288 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005289 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005290 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005291 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005292 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5293 // causing a connect/teardown loop.
5294 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5295 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005296 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005297 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005298 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5299 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005300 // does not cause any request (that is not a listen) currently matching that agent to
5301 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005302 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005303 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005304 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005305 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005306 }
5307
Paul Jensen3d194ea2015-06-16 14:27:36 -04005308 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005309 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005310 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005311 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005312 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005313 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005314 }
Paul Jensene0988542015-06-25 15:30:08 -04005315 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005316 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005317 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005318 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005319 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005320 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005321 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005322 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005323 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005324 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005325 if (nai.isSuspended()) {
5326 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5327 } else {
5328 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5329 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005330
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005331 return newNc;
5332 }
5333
5334 /**
5335 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5336 *
5337 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5338 * capabilities we manage and store in {@code nai}, such as validated status and captive
5339 * portal status)
5340 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5341 * potentially triggers rematches.
5342 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5343 * change.)
5344 *
5345 * @param oldScore score of the network before any of the changes that prompted us
5346 * to call this function.
5347 * @param nai the network having its capabilities updated.
5348 * @param nc the new network capabilities.
5349 */
5350 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5351 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5352
5353 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005354
Luke Huang8a462ec2018-08-24 20:33:16 +08005355 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5356 final int newPermission = getNetworkPermission(newNc);
5357 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005358 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005359 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005360 } catch (RemoteException e) {
5361 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005362 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005363 }
5364
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005365 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005366 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005367 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005368 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005369 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005370
Chalard Jeanf213ca12018-01-16 18:43:05 +09005371 updateUids(nai, prevNc, newNc);
5372
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005373 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005374 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5375 // the change we're processing can't affect any requests, it can only affect the listens
5376 // on this network. We might have been called by rematchNetworkAndRequests when a
5377 // network changed foreground state.
5378 processListenRequests(nai, true);
5379 } else {
5380 // If the requestable capabilities have changed or the score changed, we can't have been
5381 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005382 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005383 try {
5384 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5385 } catch (RemoteException e) {
5386 e.rethrowFromSystemServer();
5387 }
Paul Jensene0988542015-06-25 15:30:08 -04005388 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005389 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005390
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005391 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005392 final boolean oldMetered = prevNc.isMetered();
5393 final boolean newMetered = newNc.isMetered();
5394 final boolean meteredChanged = oldMetered != newMetered;
5395
5396 if (meteredChanged) {
5397 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5398 mRestrictBackground);
5399 }
5400
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005401 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005402 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005403
5404 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005405 if (meteredChanged || roamingChanged) {
5406 notifyIfacesChangedForNetworkStats();
5407 }
5408 }
5409
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005410 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005411 // Tell VPNs about updated capabilities, since they may need to
5412 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005413 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005414 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005415 }
5416
Chalard Jeanf213ca12018-01-16 18:43:05 +09005417 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5418 NetworkCapabilities newNc) {
5419 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5420 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5421 if (null == prevRanges) prevRanges = new ArraySet<>();
5422 if (null == newRanges) newRanges = new ArraySet<>();
5423 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5424
5425 prevRanges.removeAll(newRanges);
5426 newRanges.removeAll(prevRangesCopy);
5427
5428 try {
5429 if (!newRanges.isEmpty()) {
5430 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5431 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005432 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005433 }
5434 if (!prevRanges.isEmpty()) {
5435 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5436 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005437 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005438 }
5439 } catch (Exception e) {
5440 // Never crash!
5441 loge("Exception in updateUids: " + e);
5442 }
5443 }
5444
Hugo Benichief502882017-09-01 01:23:32 +00005445 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07005446 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005447 // Ignore updates for disconnected networks
5448 return;
5449 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005450 // newLp is already a defensive copy.
5451 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005452 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005453 log("Update of LinkProperties for " + nai.name() +
5454 "; created=" + nai.created +
5455 "; everConnected=" + nai.everConnected);
5456 }
lucaslin25a4ec32018-11-28 12:51:55 +08005457 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005458 }
5459
Paul Jensenc8b9a742014-09-30 15:37:41 -04005460 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005461 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5462 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005463 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005464 if (nr.isListen()) continue;
Chalard Jean08577fc2018-05-02 21:14:54 +09005465 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005466 }
5467 }
5468
Chalard Jean08577fc2018-05-02 21:14:54 +09005469 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5470 int score = 0;
5471 int serial = 0;
5472 if (nai != null) {
5473 score = nai.getCurrentScore();
5474 serial = nai.factorySerialNumber;
5475 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005476 if (VDBG || DDBG){
5477 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5478 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005479 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005480 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5481 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005482 }
5483 }
5484
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005485 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5486 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005487 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005488 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005489 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5490 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005491 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005492 sendIntent(nri.mPendingIntent, intent);
5493 }
5494 // else not handled
5495 }
5496
5497 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5498 mPendingIntentWakeLock.acquire();
5499 try {
5500 if (DBG) log("Sending " + pendingIntent);
5501 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5502 } catch (PendingIntent.CanceledException e) {
5503 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5504 mPendingIntentWakeLock.release();
5505 releasePendingNetworkRequest(pendingIntent);
5506 }
5507 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5508 }
5509
5510 @Override
5511 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5512 String resultData, Bundle resultExtras) {
5513 if (DBG) log("Finished sending " + pendingIntent);
5514 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005515 // Release with a delay so the receiving client has an opportunity to put in its
5516 // own request.
5517 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005518 }
5519
Chalard Jeanf19db372018-01-26 19:24:40 +09005520 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005521 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005522 if (nri.messenger == null) {
5523 return; // Default request has no msgr
5524 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005525 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005526 // TODO: check if defensive copies of data is needed.
5527 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005528 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005529 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5530 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005531 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005532 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005533 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005534 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5535 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005536 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005537 // For this notification, arg1 contains the blocked status.
5538 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005539 break;
5540 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005541 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005542 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005543 break;
5544 }
5545 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005546 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005547 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005548 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005549 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005550 break;
5551 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005552 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005553 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005554 break;
5555 }
junyulai05986c62018-08-07 19:50:45 +08005556 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005557 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005558 msg.arg1 = arg1;
5559 break;
5560 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005561 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005562 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005563 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005564 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005565 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005566 String notification = ConnectivityManager.getCallbackName(notificationType);
5567 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005568 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005569 nri.messenger.send(msg);
5570 } catch (RemoteException e) {
5571 // may occur naturally in the race of binder death.
5572 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5573 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005574 }
5575
Hugo Benichidba33db2017-03-23 22:40:44 +09005576 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5577 bundle.putParcelable(t.getClass().getSimpleName(), t);
5578 }
5579
Paul Jensenc8b9a742014-09-30 15:37:41 -04005580 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005581 if (nai.numRequestNetworkRequests() != 0) {
5582 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5583 NetworkRequest nr = nai.requestAt(i);
5584 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005585 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005586 loge("Dead network still had at least " + nr);
5587 break;
5588 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005589 }
5590 nai.asyncChannel.disconnect();
5591 }
5592
Robert Greenwalt7b816022014-04-18 15:25:25 -07005593 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5594 if (oldNetwork == null) {
5595 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5596 return;
5597 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005598 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005599
5600 // If we get here it means that the last linger timeout for this network expired. So there
5601 // must be no other active linger timers, and we must stop lingering.
5602 oldNetwork.clearLingerState();
5603
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005604 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005605 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005606 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005607 } else {
5608 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005609 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5610 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005611 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005612 }
5613
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005614 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005615 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005616
Paul Jensen27b02b72014-07-14 12:03:33 -04005617 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005618 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005619 } catch (Exception e) {
5620 loge("Exception setting default network :" + e);
5621 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005622
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005623 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005624 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005625 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005626 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005627 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005628 }
5629
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005630 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005631 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5632 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5633 NetworkRequest nr = nri.request;
5634 if (!nr.isListen()) continue;
5635 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5636 nai.removeRequest(nri.request.requestId);
5637 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5638 }
5639 }
5640
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005641 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005642 try {
5643 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5644 } catch (RemoteException e) {
5645 e.rethrowFromSystemServer();
5646 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005647 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5648 }
5649
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005650 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5651 NetworkRequest nr = nri.request;
5652 if (!nr.isListen()) continue;
5653 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5654 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005655 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005656 }
5657 }
5658 }
5659
Paul Jensen2161a8e2014-09-11 11:00:39 -04005660 // Handles a network appearing or improving its score.
5661 //
5662 // - Evaluates all current NetworkRequests that can be
5663 // satisfied by newNetwork, and reassigns to newNetwork
5664 // any such requests for which newNetwork is the best.
5665 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005666 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005667 // needed. A network is needed if it is the best network for
5668 // one or more NetworkRequests, or if it is a VPN.
5669 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005670 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005671 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005672 //
5673 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5674 // networks that have no chance (i.e. even if validated)
5675 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005676 //
5677 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5678 // it does not remove NetworkRequests that other Networks could better satisfy.
5679 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5680 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5681 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005682 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005683 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005684 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5685 // performed to tear down unvalidated networks that have no chance (i.e. even if
5686 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005687 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005688 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005689 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005690 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005691 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005692 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005693
5694 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5695 final int score = newNetwork.getCurrentScore();
5696
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005697 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005698
Paul Jensen2161a8e2014-09-11 11:00:39 -04005699 // Find and migrate to this Network any NetworkRequests for
5700 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005701 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5702 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005703 NetworkCapabilities nc = newNetwork.networkCapabilities;
5704 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005705 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005706 // Process requests in the first pass and listens in the second pass. This allows us to
5707 // change a network's capabilities depending on which requests it has. This is only
5708 // correct if the change in capabilities doesn't affect whether the network satisfies
5709 // requests or not, and doesn't affect the network's score.
5710 if (nri.request.isListen()) continue;
5711
Hugo Benichicd952782017-09-20 11:20:14 +09005712 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005713 final boolean satisfies = newNetwork.satisfies(nri.request);
5714 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005715 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005716 log("Network " + newNetwork.name() + " was already satisfying" +
5717 " request " + nri.request.requestId + ". No change.");
5718 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005719 keep = true;
5720 continue;
5721 }
5722
5723 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005724 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005725 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005726 // next check if it's better than any current network we're using for
5727 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005728 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005729 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005730 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005731 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005732 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005733 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005734 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005735 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005736 if (VDBG || DDBG){
5737 log(" accepting network in place of " + currentNetwork.name());
5738 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005739 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005740 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005741 affectedNetworks.add(currentNetwork);
5742 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005743 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005744 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005745 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005746 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005747 if (!newNetwork.addRequest(nri.request)) {
5748 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5749 }
5750 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005751 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005752 // Tell NetworkFactories about the new score, so they can stop
5753 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005754 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005755 // network. Think about if there is a way to reduce this. Push
5756 // netid->request mapping to each factory?
Chalard Jean08577fc2018-05-02 21:14:54 +09005757 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005758 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005759 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005760 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005761 if (currentNetwork != null) {
5762 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5763 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005764 }
5765 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005766 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005767 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5768 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005769 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005770 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5771 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5772 // This means this code doesn't have to handle the case where "currentNetwork" no
5773 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5774 if (DBG) {
5775 log("Network " + newNetwork.name() + " stopped satisfying" +
5776 " request " + nri.request.requestId);
5777 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005778 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005779 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005780 clearNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09005781 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005782 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005783 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5784 newNetwork.name() +
5785 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005786 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005787 // TODO: Technically, sending CALLBACK_LOST here is
5788 // incorrect if there is a replacement network currently
5789 // connected that can satisfy nri, which is a request
5790 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005791 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5792 // so this code is only incorrect for a network that loses
5793 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005794 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005795 }
5796 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005797 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005798 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005799 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005800 makeDefault(newNetwork);
5801 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005802 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005803 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005804 // Have a new default network, release the transition wakelock in
5805 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005806 }
5807
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005808 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5809 Slog.wtf(TAG, String.format(
5810 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005811 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005812 }
5813 if (newNetwork.getCurrentScore() != score) {
5814 Slog.wtf(TAG, String.format(
5815 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005816 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005817 }
5818
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005819 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005820 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5821 // If the network went from background to foreground or vice versa, we need to update
5822 // its foreground state. It is safe to do this after rematching the requests because
5823 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5824 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005825 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005826 } else {
5827 processListenRequests(newNetwork, false);
5828 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005829
Paul Jensencf4c2c62015-07-01 14:16:32 -04005830 // do this after the default net is switched, but
5831 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005832 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005833
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005834 // Linger any networks that are no longer needed. This should be done after sending the
5835 // available callback for newNetwork.
5836 for (NetworkAgentInfo nai : affectedNetworks) {
5837 updateLingerState(nai, now);
5838 }
5839 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5840 // does not need to be done in any particular order.
5841 updateLingerState(newNetwork, now);
5842
Paul Jensencf4c2c62015-07-01 14:16:32 -04005843 if (isNewDefault) {
5844 // Maintain the illusion: since the legacy API only
5845 // understands one network at a time, we must pretend
5846 // that the current default network disconnected before
5847 // the new one connected.
5848 if (oldDefaultNetwork != null) {
5849 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5850 oldDefaultNetwork, true);
5851 }
5852 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5853 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5854 notifyLockdownVpn(newNetwork);
5855 }
5856
Robert Greenwalt7b816022014-04-18 15:25:25 -07005857 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005858 // Notify battery stats service about this network, both the normal
5859 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005860 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005861 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005862 final IBatteryStats bs = BatteryStatsService.getService();
5863 final int type = newNetwork.networkInfo.getType();
5864
5865 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5866 bs.noteNetworkInterfaceType(baseIface, type);
5867 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5868 final String stackedIface = stacked.getInterfaceName();
5869 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005870 }
5871 } catch (RemoteException ignored) {
5872 }
5873
Robert Greenwalt152ed372014-12-17 17:19:53 -08005874 // This has to happen after the notifyNetworkCallbacks as that tickles each
5875 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005876 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005877 // and will generally do a dns request so they can ensureRouteToHost and if
5878 // they do that before the callbacks happen they'll use the default network.
5879 //
5880 // TODO: Is there still a race here? We send the broadcast
5881 // after sending the callback, but if the app can receive the
5882 // broadcast before the callback, it might still break.
5883 //
5884 // This *does* introduce a race where if the user uses the new api
5885 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5886 // they may get old info. Reverse this after the old startUsing api is removed.
5887 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005888 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5889 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005890 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005891 // legacy type tracker filters out repeat adds
5892 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5893 }
5894 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005895
5896 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5897 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5898 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5899 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5900 if (newNetwork.isVPN()) {
5901 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5902 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005903 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005904 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5905 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005906 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005907 if (nai.getLingerExpiry() > 0) {
5908 // This network has active linger timers and no requests, but is not
5909 // lingering. Linger it.
5910 //
5911 // One way (the only way?) this can happen if this network is unvalidated
5912 // and became unneeded due to another network improving its score to the
5913 // point where this network will no longer be able to satisfy any requests
5914 // even if it validates.
5915 updateLingerState(nai, now);
5916 } else {
5917 if (DBG) log("Reaping " + nai.name());
5918 teardownUnneededNetwork(nai);
5919 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005920 }
5921 }
5922 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005923 }
5924
Paul Jensen1c7ba022015-06-16 14:27:36 -04005925 /**
5926 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5927 * being disconnected.
5928 * @param changed If only one Network's score or capabilities have been modified since the last
5929 * time this function was called, pass this Network in this argument, otherwise pass
5930 * null.
5931 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5932 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5933 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5934 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5935 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005936 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005937 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005938 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5939 // to avoid the slowness. It is not simply enough to process just "changed", for
5940 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005941 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005942
5943 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5944 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5945 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005946 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005947 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005948 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005949 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005950 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5951 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5952 // Rematch higher scoring networks first to prevent requests first matching a lower
5953 // scoring network and then a higher scoring network, which could produce multiple
5954 // callbacks and inadvertently unlinger networks.
5955 Arrays.sort(nais);
5956 for (NetworkAgentInfo nai : nais) {
5957 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005958 // Only reap the last time through the loop. Reaping before all rematching
5959 // is complete could incorrectly teardown a network that hasn't yet been
5960 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005961 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005962 : ReapUnvalidatedNetworks.REAP,
5963 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005964 }
5965 }
5966 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005967
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005968 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005969 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005970 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005971 // For now only update icons for default connection.
5972 // TODO: Update WiFi and cellular icons separately. b/17237507
5973 if (!isDefaultNetwork(nai)) return;
5974
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005975 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005976 // Don't repeat publish.
5977 if (newInetCondition == mDefaultInetConditionPublished) return;
5978
5979 mDefaultInetConditionPublished = newInetCondition;
5980 sendInetConditionBroadcast(nai.networkInfo);
5981 }
5982
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005983 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005984 synchronized (mVpns) {
5985 if (mLockdownTracker != null) {
5986 if (nai != null && nai.isVPN()) {
5987 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5988 } else {
5989 mLockdownTracker.onNetworkInfoChanged();
5990 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005991 }
5992 }
5993 }
5994
Robert Greenwalt7b816022014-04-18 15:25:25 -07005995 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005996 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005997 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005998 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005999 synchronized (networkAgent) {
6000 oldInfo = networkAgent.networkInfo;
6001 networkAgent.networkInfo = newInfo;
6002 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006003 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006004
Robert Greenwalt7b816022014-04-18 15:25:25 -07006005 if (DBG) {
6006 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6007 (oldInfo == null ? "null" : oldInfo.getState()) +
6008 " to " + state);
6009 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006010
Robin Lee585e2482016-05-01 23:00:00 +01006011 if (!networkAgent.created
6012 && (state == NetworkInfo.State.CONNECTED
6013 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006014
6015 // A network that has just connected has zero requests and is thus a foreground network.
6016 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6017
Robert Greenwalt7b816022014-04-18 15:25:25 -07006018 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006019 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006020 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006021 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006022 (networkAgent.networkMisc == null ||
6023 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006024 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006025 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006026 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006027 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006028 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006029 loge("Error creating network " + networkAgent.network.netId + ": "
6030 + e.getMessage());
6031 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006032 }
Paul Jenseneec75412014-08-04 12:21:19 -04006033 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006034 }
6035
6036 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6037 networkAgent.everConnected = true;
6038
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006039 if (networkAgent.linkProperties == null) {
6040 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6041 }
6042
Erik Kline736353a2018-03-21 07:18:33 -07006043 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006044 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6045 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006046
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006047 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6048 // command must be sent after updating LinkProperties to maximize chances of
6049 // NetworkMonitor seeing the correct LinkProperties when starting.
6050 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6051 try {
6052 networkAgent.networkMonitor().notifyNetworkConnected();
6053 } catch (RemoteException e) {
6054 e.rethrowFromSystemServer();
6055 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006056 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006057
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006058 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6059 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6060 // capabilities, so it only needs to be done once on initial connect, not every time the
6061 // network's capabilities change. Note that we do this before rematching the network,
6062 // so we could decide to tear it down immediately afterwards. That's fine though - on
6063 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6064 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006065 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006066
Paul Jensen2161a8e2014-09-11 11:00:39 -04006067 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006068 final long now = SystemClock.elapsedRealtime();
6069 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006070
6071 // This has to happen after matching the requests, because callbacks are just requests.
6072 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006073 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006074 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006075 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006076 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006077 }
Chalard Jean392971c2018-05-11 20:19:20 +09006078 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006079 if (networkAgent.isVPN()) {
6080 // As the active or bound network changes for apps, broadcast the default proxy, as
6081 // apps may need to update their proxy data. This is called after disconnecting from
6082 // VPN to make sure we do not broadcast the old proxy data.
6083 // TODO(b/122649188): send the broadcast only to VPN users.
6084 mProxyTracker.sendProxyBroadcast();
6085 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006086 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6087 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006088 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006089 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006090 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006091 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006092 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6093 networkAgent.networkCapabilities);
6094 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6095 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006096 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6097 ConnectivityManager.CALLBACK_SUSPENDED :
6098 ConnectivityManager.CALLBACK_RESUMED));
6099 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006100 }
6101 }
6102
Robert Greenwaltac96c522014-06-03 16:43:57 -07006103 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006104 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006105 if (score < 0) {
6106 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6107 "). Bumping score to min of 0");
6108 score = 0;
6109 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006110
Paul Jensen2161a8e2014-09-11 11:00:39 -04006111 final int oldScore = nai.getCurrentScore();
6112 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006113
Paul Jensen85cf78e2015-06-25 13:25:07 -04006114 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006115
Paul Jensenc8b9a742014-09-30 15:37:41 -04006116 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006117 }
6118
Erik Klinec75d4fa2017-02-15 19:59:17 +09006119 // Notify only this one new request of the current state. Transfer all the
6120 // current state by calling NetworkCapabilities and LinkProperties callbacks
6121 // so that callers can be guaranteed to have as close to atomicity in state
6122 // transfer as can be supported by this current API.
6123 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006124 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006125 if (nri.mPendingIntent != null) {
6126 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6127 // Attempt no subsequent state pushes where intents are involved.
6128 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006129 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006130
junyulai05986c62018-08-07 19:50:45 +08006131 final boolean metered = nai.networkCapabilities.isMetered();
6132 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6133 metered, mRestrictBackground);
6134 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6135 }
6136
6137 /**
6138 * Notify of the blocked state apps with a registered callback matching a given NAI.
6139 *
6140 * Unlike other callbacks, blocked status is different between each individual uid. So for
6141 * any given nai, all requests need to be considered according to the uid who filed it.
6142 *
6143 * @param nai The target NetworkAgentInfo.
6144 * @param oldMetered True if the previous network capabilities is metered.
6145 * @param newRestrictBackground True if data saver is enabled.
6146 */
6147 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6148 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6149
6150 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6151 NetworkRequest nr = nai.requestAt(i);
6152 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6153 final int uidRules = mUidRules.get(nri.mUid);
6154 final boolean oldBlocked, newBlocked;
6155 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6156 // between these two calls.
6157 synchronized (mVpns) {
6158 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6159 oldRestrictBackground);
6160 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6161 newRestrictBackground);
6162 }
6163 if (oldBlocked != newBlocked) {
6164 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6165 encodeBool(newBlocked));
6166 }
6167 }
6168 }
6169
6170 /**
6171 * Notify apps with a given UID of the new blocked state according to new uid rules.
6172 * @param uid The uid for which the rules changed.
6173 * @param newRules The new rules to apply.
6174 */
6175 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6176 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6177 final boolean metered = nai.networkCapabilities.isMetered();
6178 final boolean oldBlocked, newBlocked;
6179 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6180 // rules changed event. And this function actually loop through all connected nai and
6181 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6182 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6183 synchronized (mVpns) {
6184 oldBlocked = isUidNetworkingWithVpnBlocked(
6185 uid, mUidRules.get(uid), metered, mRestrictBackground);
6186 newBlocked = isUidNetworkingWithVpnBlocked(
6187 uid, newRules, metered, mRestrictBackground);
6188 }
6189 if (oldBlocked == newBlocked) {
6190 return;
6191 }
6192 final int arg = encodeBool(newBlocked);
6193 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6194 NetworkRequest nr = nai.requestAt(i);
6195 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6196 if (nri != null && nri.mUid == uid) {
6197 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6198 }
6199 }
6200 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006201 }
6202
Robert Greenwalt8d482522015-06-24 13:23:42 -07006203 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006204 // The NetworkInfo we actually send out has no bearing on the real
6205 // state of affairs. For example, if the default connection is mobile,
6206 // and a request for HIPRI has just gone away, we need to pretend that
6207 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6208 // the state to DISCONNECTED, even though the network is of type MOBILE
6209 // and is still connected.
6210 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6211 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006212 if (state != DetailedState.DISCONNECTED) {
6213 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006214 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006215 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006216 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006217 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6218 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6219 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6220 if (info.isFailover()) {
6221 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6222 nai.networkInfo.setFailover(false);
6223 }
6224 if (info.getReason() != null) {
6225 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6226 }
6227 if (info.getExtraInfo() != null) {
6228 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6229 }
6230 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006231 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006232 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006233 if (newDefaultAgent != null) {
6234 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6235 newDefaultAgent.networkInfo);
6236 } else {
6237 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6238 }
6239 }
6240 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6241 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006242 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006243 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006244 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006245 }
6246 }
6247 }
6248
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006249 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006250 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006251 String notification = ConnectivityManager.getCallbackName(notifyType);
6252 log("notifyType " + notification + " for " + networkAgent.name());
6253 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006254 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6255 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006256 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6257 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006258 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6259 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006260 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006261 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006262 } else {
6263 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6264 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006265 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006266 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006267
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006268 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6269 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6270 }
6271
Jeff Sharkey69736342014-12-08 14:50:12 -08006272 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006273 * Returns the list of all interfaces that could be used by network traffic that does not
6274 * explicitly specify a network. This includes the default network, but also all VPNs that are
6275 * currently connected.
6276 *
6277 * Must be called on the handler thread.
6278 */
6279 private Network[] getDefaultNetworks() {
6280 ArrayList<Network> defaultNetworks = new ArrayList<>();
6281 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6282 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6283 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6284 defaultNetworks.add(nai.network);
6285 }
6286 }
6287 return defaultNetworks.toArray(new Network[0]);
6288 }
6289
6290 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006291 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6292 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006293 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006294 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08006295 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006296 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08006297 } catch (Exception ignored) {
6298 }
6299 }
6300
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006301 @Override
6302 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006303 int user = UserHandle.getUserId(Binder.getCallingUid());
6304 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006305 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006306 return mVpns.get(user).addAddress(address, prefixLength);
6307 }
6308 }
6309
6310 @Override
6311 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006312 int user = UserHandle.getUserId(Binder.getCallingUid());
6313 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006314 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006315 return mVpns.get(user).removeAddress(address, prefixLength);
6316 }
6317 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006318
6319 @Override
6320 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006321 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006322 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006323 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006324 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006325 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006326 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006327 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006328 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006329 }
6330 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006331 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006332
6333 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006334 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006335 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006336 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006337 }
6338
6339 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006340 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
6341 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
6342 enforceKeepalivePermission();
6343 mKeepaliveTracker.startNattKeepalive(
6344 getNetworkAgentInfoForNetwork(network),
6345 intervalSeconds, messenger, binder,
6346 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
6347 }
6348
6349 @Override
junyulai215b8772019-01-15 11:32:44 +08006350 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
6351 int intervalSeconds, Messenger messenger, IBinder binder, String srcAddr,
6352 String dstAddr) {
6353 enforceKeepalivePermission();
6354 mKeepaliveTracker.startNattKeepalive(
6355 getNetworkAgentInfoForNetwork(network), fd, resourceId,
6356 intervalSeconds, messenger, binder,
6357 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6358 }
6359
6360 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006361 public void stopKeepalive(Network network, int slot) {
6362 mHandler.sendMessage(mHandler.obtainMessage(
6363 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
6364 }
6365
6366 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006367 public void factoryReset() {
6368 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006369
6370 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6371 return;
6372 }
6373
Robin Lee3b3dd942015-05-12 18:14:58 +01006374 final int userId = UserHandle.getCallingUserId();
6375
Stuart Scottf1fb3972015-04-02 18:00:02 -07006376 // Turn airplane mode off
6377 setAirplaneMode(false);
6378
Stuart Scotte3e314d2015-04-20 14:07:45 -07006379 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6380 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006381 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006382 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006383 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006384 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006385 }
6386
Stuart Scotte3e314d2015-04-20 14:07:45 -07006387 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006388 // Remove always-on package
6389 synchronized (mVpns) {
6390 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6391 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006392 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006393 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6394 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006395
Hugo Benichi69744342017-11-27 10:57:16 +09006396 // Turn Always-on VPN off
6397 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6398 final long ident = Binder.clearCallingIdentity();
6399 try {
6400 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6401 mLockdownEnabled = false;
6402 setLockdownTracker(null);
6403 } finally {
6404 Binder.restoreCallingIdentity(ident);
6405 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006406 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006407
Hugo Benichi69744342017-11-27 10:57:16 +09006408 // Turn VPN off
6409 VpnConfig vpnConfig = getVpnConfig(userId);
6410 if (vpnConfig != null) {
6411 if (vpnConfig.legacy) {
6412 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6413 } else {
6414 // Prevent this app (packagename = vpnConfig.user) from initiating
6415 // VPN connections in the future without user intervention.
6416 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006417
Hugo Benichi69744342017-11-27 10:57:16 +09006418 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6419 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006420 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006421 }
6422 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006423
6424 Settings.Global.putString(mContext.getContentResolver(),
6425 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006426 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006427
Ricky Wai44dcbde2018-01-23 04:09:45 +00006428 @Override
6429 public byte[] getNetworkWatchlistConfigHash() {
6430 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6431 if (nwm == null) {
6432 loge("Unable to get NetworkWatchlistManager");
6433 return null;
6434 }
6435 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6436 return nwm.getWatchlistConfigHash();
6437 }
6438
Paul Jensencf4c2c62015-07-01 14:16:32 -04006439 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006440 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6441 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006442 }
6443
6444 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006445 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6446 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6447 }
6448
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006449 @VisibleForTesting
6450 public boolean hasService(String name) {
6451 return ServiceManager.checkService(name) != null;
6452 }
6453
Hugo Benichi64901e52017-10-19 14:42:40 +09006454 @VisibleForTesting
6455 protected IpConnectivityMetrics.Logger metricsLogger() {
6456 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6457 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006458 }
6459
6460 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006461 int[] transports = nai.networkCapabilities.getTransportTypes();
6462 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006463 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006464
6465 private static boolean toBool(int encodedBoolean) {
6466 return encodedBoolean != 0; // Only 0 means false.
6467 }
6468
6469 private static int encodeBool(boolean b) {
6470 return b ? 1 : 0;
6471 }
mswest46386886f2018-03-12 10:34:34 -07006472
6473 @Override
6474 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6475 FileDescriptor err, String[] args, ShellCallback callback,
6476 ResultReceiver resultReceiver) {
6477 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6478 }
6479
6480 private class ShellCmd extends ShellCommand {
6481
6482 @Override
6483 public int onCommand(String cmd) {
6484 if (cmd == null) {
6485 return handleDefaultCommands(cmd);
6486 }
6487 final PrintWriter pw = getOutPrintWriter();
6488 try {
6489 switch (cmd) {
6490 case "airplane-mode":
6491 final String action = getNextArg();
6492 if ("enable".equals(action)) {
6493 setAirplaneMode(true);
6494 return 0;
6495 } else if ("disable".equals(action)) {
6496 setAirplaneMode(false);
6497 return 0;
6498 } else if (action == null) {
6499 final ContentResolver cr = mContext.getContentResolver();
6500 final int enabled = Settings.Global.getInt(cr,
6501 Settings.Global.AIRPLANE_MODE_ON);
6502 pw.println(enabled == 0 ? "disabled" : "enabled");
6503 return 0;
6504 } else {
6505 onHelp();
6506 return -1;
6507 }
6508 default:
6509 return handleDefaultCommands(cmd);
6510 }
6511 } catch (Exception e) {
6512 pw.println(e);
6513 }
6514 return -1;
6515 }
6516
6517 @Override
6518 public void onHelp() {
6519 PrintWriter pw = getOutPrintWriter();
6520 pw.println("Connectivity service commands:");
6521 pw.println(" help");
6522 pw.println(" Print this help text.");
6523 pw.println(" airplane-mode [enable|disable]");
6524 pw.println(" Turn airplane mode on or off.");
6525 pw.println(" airplane-mode");
6526 pw.println(" Get airplane mode.");
6527 }
6528 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006529
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006530 @GuardedBy("mVpns")
6531 private Vpn getVpnIfOwner() {
6532 final int uid = Binder.getCallingUid();
6533 final int user = UserHandle.getUserId(uid);
6534
6535 final Vpn vpn = mVpns.get(user);
6536 if (vpn == null) {
6537 return null;
6538 } else {
6539 final VpnInfo info = vpn.getVpnInfo();
6540 return (info == null || info.ownerUid != uid) ? null : vpn;
6541 }
6542 }
6543
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006544 /**
6545 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6546 * for testing.
6547 */
6548 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6549 if (checkNetworkStackPermission()) {
6550 return null;
6551 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006552 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006553 Vpn vpn = getVpnIfOwner();
6554 if (vpn != null) {
6555 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006556 }
6557 }
6558 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6559 + "permission");
6560 }
6561
6562 /**
6563 * @param connectionInfo the connection to resolve.
6564 * @return {@code uid} if the connection is found and the app has permission to observe it
6565 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6566 * connection is not found.
6567 */
6568 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6569 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6570 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6571 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6572 }
6573
6574 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6575 connectionInfo.local, connectionInfo.remote);
6576
6577 /* Filter out Uids not associated with the VPN. */
6578 if (vpn != null && !vpn.appliesToUid(uid)) {
6579 return INVALID_UID;
6580 }
6581
6582 return uid;
6583 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006584
6585 @Override
6586 public boolean isCallerCurrentAlwaysOnVpnApp() {
6587 synchronized (mVpns) {
6588 Vpn vpn = getVpnIfOwner();
6589 return vpn != null && vpn.getAlwaysOn();
6590 }
6591 }
6592
6593 @Override
6594 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6595 synchronized (mVpns) {
6596 Vpn vpn = getVpnIfOwner();
6597 return vpn != null && vpn.getLockdown();
6598 }
6599 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006600}