blob: 7ba6ac9cdc73f111f1380944d0ab71b561ca6d07 [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;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070043import static android.os.Process.INVALID_UID;
44import static android.system.OsConstants.IPPROTO_TCP;
45import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060046
Hugo Benichia0385682017-03-22 17:07:57 +090047import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060048
Wenchao Tongf5ea3402015-03-04 13:26:38 -080049import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080050import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090051import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070052import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070053import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.ContentResolver;
55import android.content.Context;
56import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070057import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070058import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070059import android.database.ContentObserver;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070060import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090062import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050064import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080065import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050066import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070067import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090068import android.net.INetworkMonitor;
69import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070070import android.net.INetworkPolicyListener;
71import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070072import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080073import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070074import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010075import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070076import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070077import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070078import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070079import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070081import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070082import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090083import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070084import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070085import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070086import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090087import android.net.NetworkStack;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070088import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070089import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000090import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090091import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -040092import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070093import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040094import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040095import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060096import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090097import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090098import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070099import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900100import android.net.shared.NetworkMonitorUtils;
101import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900102import android.net.util.MultinetworkPolicyTracker;
Luke Huang674660f2018-09-27 19:33:11 +0800103import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800105import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700106import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700108import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700109import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700110import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.os.Looper;
112import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700113import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700114import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900115import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700116import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700117import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700118import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800119import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900120import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900121import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700122import android.os.ShellCallback;
123import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900124import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700125import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400126import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700128import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700129import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700130import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700131import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900132import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700133import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600134import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900135import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800136import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700137import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500138import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700139import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Wink Savilleab9321d2013-06-29 21:10:57 -0700142import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400143import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400144import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700145import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700146import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700147import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800148import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700149import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900150import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700151import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600152import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700153import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900154import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900155import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700156import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700157import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400158import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900159import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500160import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900161import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900162import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100163import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700164import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900165import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700166import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600167import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900168import com.android.server.connectivity.NetworkNotificationManager;
169import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700170import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900171import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800172import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700173import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100174import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500175import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700176import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700177import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900178import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700179import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600180
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700181import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700182
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700183import org.xmlpull.v1.XmlPullParser;
184import org.xmlpull.v1.XmlPullParserException;
185
186import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700188import java.io.FileNotFoundException;
189import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700190import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700192import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700193import java.net.InetAddress;
194import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700195import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700196import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700197import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900198import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800199import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700200import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700202import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700203import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700204import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900205import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600206import java.util.SortedSet;
207import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
209/**
210 * @hide
211 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800212public class ConnectivityService extends IConnectivityManager.Stub
213 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900214 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
Chalard Jean4133a122018-06-04 13:33:12 +0900216 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900217 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900218 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900219 private static final String NETWORK_ARG = "networks";
220 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900221
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900222 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900223 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
224 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900226 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700227
Jeff Sharkey899223b2012-08-04 15:24:58 -0700228 // TODO: create better separation between radio types and network types
229
Robert Greenwalt42acef32009-08-12 16:08:25 -0700230 // how long to wait before switching back to a radio's default network
231 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
232 // system property that can override the above value
233 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
234 "android.telephony.apn-restore";
235
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900236 // How long to wait before putting up a "This network doesn't have an Internet connection,
237 // connect anyway?" dialog after the user selects a network that doesn't validate.
238 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
239
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900240 // Default to 30s linger time-out. Modifiable only for testing.
241 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
242 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
243 @VisibleForTesting
244 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
245
Jeremy Joslin79294842014-12-03 17:15:28 -0800246 // How long to delay to removal of a pending intent based request.
247 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
248 private final int mReleasePendingIntentDelayMs;
249
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900250 private MockableSystemProperties mSystemProperties;
251
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800252 private Tethering mTethering;
253
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700254 private final PermissionMonitor mPermissionMonitor;
255
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700256 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700257
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900258 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700259 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900260 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700261
Hugo Benichi69744342017-11-27 10:57:16 +0900262 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
263 // a direct call to LockdownVpnTracker.isEnabled().
264 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700265 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900266 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700267 private LockdownVpnTracker mLockdownTracker;
268
junyulai05986c62018-08-07 19:50:45 +0800269 /**
270 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
271 * handler thread, they don't need a lock.
272 */
273 private SparseIntArray mUidRules = new SparseIntArray();
274 /** Flag indicating if background data is restricted. */
275 private boolean mRestrictBackground;
276
Erik Klineda4bfa82015-04-30 12:58:40 +0900277 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700278 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700279 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280
Luke Huang4e25ec62018-09-27 16:58:23 +0800281 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800282 @VisibleForTesting
283 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800284 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700285 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900286 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700287
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700288 private String mCurrentTcpBufferSizes;
289
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900290 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900291 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
292 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900293
Paul Jensenb10e37f2014-11-25 12:33:08 -0500294 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400295 // Tear down networks that have no chance (e.g. even if validated) of becoming
296 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500297 // all networks have been rematched against all NetworkRequests.
298 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400299 // Don't reap networks. This should be passed when some networks have not yet been
300 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500301 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900302 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500303
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900304 private enum UnneededFor {
305 LINGER, // Determine whether this network is unneeded and should be lingered.
306 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
307 }
308
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700309 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700310 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700311 * from one net to another. Clear happens when we get a new
312 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
313 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700314 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700315 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700316
Robert Greenwalt434203a2010-10-11 16:00:27 -0700317 /**
318 * used internally to reload global proxy settings
319 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700320 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700321
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700322 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400323 * PAC manager has received new port.
324 */
325 private static final int EVENT_PROXY_HAS_CHANGED = 16;
326
Robert Greenwalte049c232014-04-11 15:53:27 -0700327 /**
328 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700329 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700330 */
331 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
332
Robert Greenwalt7b816022014-04-18 15:25:25 -0700333 /**
334 * used internally when registering NetworkAgents
335 * obj = Messenger
336 */
337 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
338
Robert Greenwalt9258c642014-03-26 16:47:06 -0700339 /**
340 * used to add a network request
341 * includes a NetworkRequestInfo
342 */
343 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
344
345 /**
346 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900347 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700348 * cancel it.
349 * includes a NetworkRequestInfo
350 */
351 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
352
353 /**
354 * used to add a network listener - no request
355 * includes a NetworkRequestInfo
356 */
357 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
358
359 /**
360 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400361 * arg1 = UID of caller
362 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700363 */
364 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
365
Robert Greenwalta67be032014-05-16 15:49:14 -0700366 /**
367 * used internally when registering NetworkFactories
368 * obj = Messenger
369 */
370 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
371
Robert Greenwalt27711812014-06-25 16:45:57 -0700372 /**
373 * used internally to expire a wakelock when transitioning
374 * from one net to another. Expire happens when we fail to find
375 * a new network (typically after 1 minute) -
376 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
377 * a replacement network.
378 */
379 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
380
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700381 /**
382 * Used internally to indicate the system is ready.
383 */
384 private static final int EVENT_SYSTEM_READY = 25;
385
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800386 /**
387 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400388 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800389 */
390 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
391
392 /**
393 * used to remove a pending intent and its associated network request.
394 * arg1 = UID of caller
395 * obj = PendingIntent
396 */
397 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
398
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900399 /**
400 * used to specify whether a network should be used even if unvalidated.
401 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
402 * arg2 = whether to remember this choice in the future (1 or 0)
403 * obj = network
404 */
405 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
406
407 /**
408 * used to ask the user to confirm a connection to an unvalidated network.
409 * obj = network
410 */
411 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700412
Erik Klineda4bfa82015-04-30 12:58:40 +0900413 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700414 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900415 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700416 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900417
Paul Jensen694f2b82015-06-17 14:15:39 -0400418 /**
419 * used to add a network listener with a pending intent
420 * obj = NetworkRequestInfo
421 */
422 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
423
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900424 /**
425 * used to specify whether a network should not be penalized when it becomes unvalidated.
426 */
427 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
428
429 /**
430 * used to trigger revalidation of a network.
431 */
432 private static final int EVENT_REVALIDATE_NETWORK = 36;
433
Erik Klinea24d4592018-01-11 21:07:29 +0900434 // Handle changes in Private DNS settings.
435 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
436
dalyk7301aa42018-03-05 12:42:22 -0500437 // Handle private DNS validation status updates.
438 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
439
junyulai05986c62018-08-07 19:50:45 +0800440 /**
441 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
442 */
443 private static final int EVENT_UID_RULES_CHANGED = 39;
444
445 /**
446 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
447 */
448 private static final int EVENT_DATA_SAVER_CHANGED = 40;
449
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900450 /**
451 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
452 * been tested.
453 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
454 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
455 * arg2 = NetID.
456 */
457 public static final int EVENT_NETWORK_TESTED = 41;
458
459 /**
460 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
461 * config was resolved.
462 * obj = PrivateDnsConfig
463 * arg2 = netid
464 */
465 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
466
467 /**
468 * Request ConnectivityService display provisioning notification.
469 * arg1 = Whether to make the notification visible.
470 * arg2 = NetID.
471 * obj = Intent to be launched when notification selected by user, null if !arg1.
472 */
473 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
474
475 /**
476 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
477 * should be shown.
478 */
479 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
480
481 /**
482 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
483 * should be hidden.
484 */
485 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
486
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900487 private static String eventName(int what) {
488 return sMagicDecoderRing.get(what, Integer.toString(what));
489 }
490
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900491 /** Handler thread used for both of the handlers below. */
492 @VisibleForTesting
493 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700494 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700495 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700496 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700497 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900498 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700499
Mike Lockwood0f79b542009-08-14 14:18:49 -0400500 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800501 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400502
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700503 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700504 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800505 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700506
Chalard Jean52c2aa72018-06-07 16:44:04 +0900507 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
508 // the world when it changes.
Chalard Jeanff5d0052018-06-07 19:20:08 +0900509 private final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400510
Erik Klineda4bfa82015-04-30 12:58:40 +0900511 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700512
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400513 private UserManager mUserManager;
514
Chalard Jean4133a122018-06-04 13:33:12 +0900515 private NetworkConfig[] mNetConfigs;
516 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700517
Robert Greenwalt50393202011-06-21 17:26:14 -0700518 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900519 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700520
Chalard Jean4133a122018-06-04 13:33:12 +0900521 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400522
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900523 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900524 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900525 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900526
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700527 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800528 private static final int MIN_NET_ID = 100; // some reserved marks
529 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700530 private int mNextNetId = MIN_NET_ID;
531
Robert Greenwalt34524f02014-05-18 16:22:10 -0700532 // sequence number of NetworkRequests
533 private int mNextNetworkRequestId = 1;
534
Erik Kline7523eb32015-07-09 18:24:03 +0900535 // NetworkRequest activity String log entries.
536 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
537 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
538
Hugo Benichic2ae2872016-07-11 11:05:12 +0900539 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900540 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900541 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
542
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900543 private static final int MAX_WAKELOCK_LOGS = 20;
544 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900545 private int mTotalWakelockAcquisitions = 0;
546 private int mTotalWakelockReleases = 0;
547 private long mTotalWakelockDurationMs = 0;
548 private long mMaxWakelockDurationMs = 0;
549 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900550
Hugo Benichif9fdf872016-07-28 17:53:06 +0900551 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900552
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700553 @GuardedBy("mBandwidthRequests")
554 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
555
Erik Kline065ab6e2016-10-02 18:02:14 +0900556 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900557 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900558
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900559 @VisibleForTesting
560 final MultipathPolicyTracker mMultipathPolicyTracker;
561
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 /**
563 * Implements support for the legacy "one network per network type" model.
564 *
565 * We used to have a static array of NetworkStateTrackers, one for each
566 * network type, but that doesn't work any more now that we can have,
567 * for example, more that one wifi network. This class stores all the
568 * NetworkAgentInfo objects that support a given type, but the legacy
569 * API will only see the first one.
570 *
571 * It serves two main purposes:
572 *
573 * 1. Provide information about "the network for a given type" (since this
574 * API only supports one).
575 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
576 * the first network for a given type changes, or if the default network
577 * changes.
578 */
579 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900581 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900582 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900583
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 /**
585 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
586 * Each list holds references to all NetworkAgentInfos that are used to
587 * satisfy requests for that network type.
588 *
589 * This array is built out at startup such that an unsupported network
590 * doesn't get an ArrayList instance, making this a tristate:
591 * unsupported, supported but not active and active.
592 *
593 * The actual lists are populated when we scan the network types that
594 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900595 *
596 * Threading model:
597 * - addSupportedType() is only called in the constructor
598 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
599 * They are therefore not thread-safe with respect to each other.
600 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
601 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
602 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700603 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700605
606 public LegacyTypeTracker() {
607 mTypeLists = (ArrayList<NetworkAgentInfo>[])
608 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
609 }
610
611 public void addSupportedType(int type) {
612 if (mTypeLists[type] != null) {
613 throw new IllegalStateException(
614 "legacy list for type " + type + "already initialized");
615 }
Chalard Jean4133a122018-06-04 13:33:12 +0900616 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617 }
618
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 public boolean isTypeSupported(int type) {
620 return isNetworkTypeValid(type) && mTypeLists[type] != null;
621 }
622
623 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900624 synchronized (mTypeLists) {
625 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
626 return mTypeLists[type].get(0);
627 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700628 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900629 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
631
Robert Greenwalt8d482522015-06-24 13:23:42 -0700632 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900636 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900637 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900638 }
639 }
640
641 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700642 public void add(int type, NetworkAgentInfo nai) {
643 if (!isTypeSupported(type)) {
644 return; // Invalid network type.
645 }
646 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
647
648 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
649 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700650 return;
651 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900652 synchronized (mTypeLists) {
653 list.add(nai);
654 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900655
656 // 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 +0900657 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900658 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700659 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
660 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700661 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700662 }
663
Lorenzo Colittia793a672014-07-31 23:20:17 +0900664 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900665 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900666 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
667 if (list == null || list.isEmpty()) {
668 return;
669 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900670 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900671
Hugo Benichi78caa2582016-06-21 09:48:07 +0900672 synchronized (mTypeLists) {
673 if (!list.remove(nai)) {
674 return;
675 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 }
677
Robert Greenwalt8d482522015-06-24 13:23:42 -0700678 final DetailedState state = DetailedState.DISCONNECTED;
679
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900680 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700681 maybeLogBroadcast(nai, state, type, wasDefault);
682 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900683 }
684
685 if (!list.isEmpty() && wasFirstNetwork) {
686 if (DBG) log("Other network available for type " + type +
687 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900688 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700689 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
690 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900691 }
692 }
693
694 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900695 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
696 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700697 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900698 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700699 }
700 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700701
Robert Greenwalt8d482522015-06-24 13:23:42 -0700702 // send out another legacy broadcast - currently only used for suspend/unsuspend
703 // toggle
704 public void update(NetworkAgentInfo nai) {
705 final boolean isDefault = isDefaultNetwork(nai);
706 final DetailedState state = nai.networkInfo.getDetailedState();
707 for (int type = 0; type < mTypeLists.length; type++) {
708 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700709 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900710 final boolean isFirst = contains && (nai == list.get(0));
711 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700712 maybeLogBroadcast(nai, state, type, isDefault);
713 sendLegacyNetworkBroadcast(nai, state, type);
714 }
715 }
716 }
717
Lorenzo Colittia793a672014-07-31 23:20:17 +0900718 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900719 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900720 String state = (nai.networkInfo != null) ?
721 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
722 "???/???";
723 return name + " " + state;
724 }
725
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700726 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900727 pw.println("mLegacyTypeTracker:");
728 pw.increaseIndent();
729 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700730 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900731 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700732 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900733 pw.println();
734 pw.println("Current state:");
735 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900736 synchronized (mTypeLists) {
737 for (int type = 0; type < mTypeLists.length; type++) {
738 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
739 for (NetworkAgentInfo nai : mTypeLists[type]) {
740 pw.println(type + " " + naiToString(nai));
741 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900742 }
743 }
744 pw.decreaseIndent();
745 pw.decreaseIndent();
746 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700747 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700748 }
749 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
750
Vishnu Nair5c010902017-10-26 10:08:50 -0700751 /**
752 * Helper class which parses out priority arguments and dumps sections according to their
753 * priority. If priority arguments are omitted, function calls the legacy dump command.
754 */
755 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
756 @Override
757 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
758 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
759 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
760 }
761
762 @Override
763 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
764 doDump(fd, pw, args, asProto);
765 }
766
767 @Override
768 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
769 doDump(fd, pw, args, asProto);
770 }
771 };
772
Jeff Sharkey899223b2012-08-04 15:24:58 -0700773 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700774 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900775 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
776 }
777
778 @VisibleForTesting
779 protected ConnectivityService(Context context, INetworkManagementService netManager,
780 INetworkStatsService statsService, INetworkPolicyManager policyManager,
781 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800782 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800783
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900784 mSystemProperties = getSystemProperties();
785
Hugo Benichif9fdf872016-07-28 17:53:06 +0900786 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900787 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900788 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900789 mNetworkRequests.put(mDefaultRequest, defaultNRI);
790 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900791
Chalard Jeandda156a2018-01-10 21:19:32 +0900792 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900793 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700794
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700795 // The default WiFi request is a background request so that apps using WiFi are
796 // migrated to a better network (typically ethernet) when one comes up, instead
797 // of staying on WiFi forever.
798 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
799 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
800
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900801 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900802 mHandlerThread.start();
803 mHandler = new InternalHandler(mHandlerThread.getLooper());
804 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700805
Jeremy Joslin79294842014-12-03 17:15:28 -0800806 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
807 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
808
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900809 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900810
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700811 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800812 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800813 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700814 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900815 mPolicyManagerInternal = checkNotNull(
816 LocalServices.getService(NetworkPolicyManagerInternal.class),
817 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900818 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900819
Luke Huang674660f2018-09-27 19:33:11 +0800820 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700821 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700822 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700823
junyulai05986c62018-08-07 19:50:45 +0800824 // To ensure uid rules are synchronized with Network Policy, register for
825 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
826 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700827 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900828 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700829 } catch (RemoteException e) {
830 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700831 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700832 }
833
834 final PowerManager powerManager = (PowerManager) context.getSystemService(
835 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700836 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
837 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
838 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800839 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700840
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700841 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700842
Wink Saville51f456f2013-04-23 14:26:51 -0700843 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900844 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700845 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700846 String[] naStrings = context.getResources().getStringArray(
847 com.android.internal.R.array.networkAttributes);
848 for (String naString : naStrings) {
849 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700850 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700851 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700852 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800853 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700854 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700855 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700856 }
Wink Saville51f456f2013-04-23 14:26:51 -0700857 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
858 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
859 n.type);
860 continue;
861 }
Wink Saville975c8482011-04-07 14:23:45 -0700862 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800863 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700864 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700865 continue;
866 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700867 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700868
Wink Saville975c8482011-04-07 14:23:45 -0700869 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700870 mNetworksDefined++;
871 } catch(Exception e) {
872 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700873 }
874 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700875
876 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
877 if (mNetConfigs[TYPE_VPN] == null) {
878 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
879 // don't need to add TYPE_VPN to mNetConfigs.
880 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
881 mNetworksDefined++; // used only in the log() statement below.
882 }
883
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900884 // Do the same for Ethernet, since it's often not specified in the configs, although many
885 // devices can use it via USB host adapters.
886 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
887 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
888 mNetworksDefined++;
889 }
890
Wink Saville5e56bc52013-07-29 15:00:57 -0700891 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892
Robert Greenwalt50393202011-06-21 17:26:14 -0700893 mProtectedNetworks = new ArrayList<Integer>();
894 int[] protectedNetworks = context.getResources().getIntArray(
895 com.android.internal.R.array.config_protectedNetworks);
896 for (int p : protectedNetworks) {
897 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
898 mProtectedNetworks.add(p);
899 } else {
900 if (DBG) loge("Ignoring protectedNetwork " + p);
901 }
902 }
903
Erik Kline47222fc2017-04-30 19:36:15 +0900904 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800905
Luke Huang4e25ec62018-09-27 16:58:23 +0800906 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700907
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700908 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700909 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100910 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700911 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700912 intentFilter.addAction(Intent.ACTION_USER_ADDED);
913 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000914 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700915 mContext.registerReceiverAsUser(
junyulai2454b692018-11-01 17:16:31 +0800916 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000917 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
918 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900919
junyulai2454b692018-11-01 17:16:31 +0800920 // Listen to package add and removal events for all users.
921 intentFilter = new IntentFilter();
922 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800923 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800924 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
925 intentFilter.addDataScheme("package");
926 mContext.registerReceiverAsUser(
927 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
928
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700929 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800930 mNMS.registerObserver(mTethering);
931 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700932 } catch (RemoteException e) {
933 loge("Error registering observer :" + e);
934 }
935
Erik Klineda4bfa82015-04-30 12:58:40 +0900936 mSettingsObserver = new SettingsObserver(mContext, mHandler);
937 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800938
Chalard Jean4133a122018-06-04 13:33:12 +0900939 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
940 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400941
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400942 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900943
944 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900945 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
946 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900947
948 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
949 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
950 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
951 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
952 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
953 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
954 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900955
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900956 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900957 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900958 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900959
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900960 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
961
Luke Huang4e25ec62018-09-27 16:58:23 +0800962 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900963 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700965
Mike Yuf9729752018-08-17 15:22:05 +0800966 @VisibleForTesting
967 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +0900968 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900969 final TetheringDependencies deps = new TetheringDependencies() {
970 @Override
971 public boolean isTetheringSupported() {
972 return ConnectivityService.this.isTetheringSupported();
973 }
Erik Kline72302902018-06-14 17:36:40 +0900974 @Override
975 public NetworkRequest getDefaultNetworkRequest() {
976 return mDefaultRequest;
977 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900978 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800979 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900980 IoThread.get().getLooper(), new MockableSystemProperties(),
981 deps);
982 }
983
Chalard Jean26400492018-04-18 20:18:38 +0900984 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
985 final NetworkCapabilities netCap = new NetworkCapabilities();
986 netCap.addCapability(NET_CAPABILITY_INTERNET);
987 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
988 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
989 netCap.setSingleUid(uid);
990 return netCap;
991 }
992
Chalard Jeandda156a2018-01-10 21:19:32 +0900993 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900994 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +0900995 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900996 netCap.addCapability(NET_CAPABILITY_INTERNET);
997 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900998 if (transportType > -1) {
999 netCap.addTransportType(transportType);
1000 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001001 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001002 }
1003
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001004 // Used only for testing.
1005 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001006 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001007 // changing ContentResolver to make registerContentObserver non-final).
1008 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1009 // by subclassing SettingsObserver.
1010 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001011 void updateAlwaysOnNetworks() {
1012 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001013 }
1014
Erik Kline736353a2018-03-21 07:18:33 -07001015 // See FakeSettingsProvider comment above.
1016 @VisibleForTesting
1017 void updatePrivateDnsSettings() {
1018 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1019 }
1020
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001021 private void handleAlwaysOnNetworkRequest(
1022 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001023 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001024 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1025 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001026 if (enable == isEnabled) {
1027 return; // Nothing to do.
1028 }
1029
1030 if (enable) {
1031 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001032 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001033 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001034 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +09001035 }
1036 }
1037
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001038 private void handleConfigureAlwaysOnNetworks() {
1039 handleAlwaysOnNetworkRequest(
1040 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1041 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1042 false);
1043 }
1044
Erik Klineda4bfa82015-04-30 12:58:40 +09001045 private void registerSettingsCallbacks() {
1046 // Watch for global HTTP proxy changes.
1047 mSettingsObserver.observe(
1048 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1049 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1050
1051 // Watch for whether or not to keep mobile data always on.
1052 mSettingsObserver.observe(
1053 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001054 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1055
1056 // Watch for whether or not to keep wifi always on.
1057 mSettingsObserver.observe(
1058 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1059 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001060 }
1061
Erik Klinea24d4592018-01-11 21:07:29 +09001062 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001063 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1064 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001065 }
1066 }
1067
Robert Greenwalt34524f02014-05-18 16:22:10 -07001068 private synchronized int nextNetworkRequestId() {
1069 return mNextNetworkRequestId++;
1070 }
1071
Paul Jensen67b0b072015-06-10 11:22:17 -04001072 @VisibleForTesting
1073 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001074 synchronized (mNetworkForNetId) {
1075 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1076 int netId = mNextNetId;
1077 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1078 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001079 if (!mNetIdInUse.get(netId)) {
1080 mNetIdInUse.put(netId, true);
1081 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001082 }
1083 }
1084 }
1085 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001086 }
1087
Chalard Jeanc0982912018-06-07 16:11:34 +09001088 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001089 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001090 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1091 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001092 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001093 state = nai.getNetworkState();
1094 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001095 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001096 final NetworkInfo info = new NetworkInfo(networkType, 0,
1097 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001098 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1099 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001100 final NetworkCapabilities capabilities = new NetworkCapabilities();
1101 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1102 !info.isRoaming());
1103 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001104 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001105 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001106 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 return state;
1108 } else {
1109 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001110 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001111 }
1112
junyulai4a192e22018-06-13 15:00:37 +08001113 @VisibleForTesting
1114 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001115 if (network == null) {
1116 return null;
1117 }
Erik Kline736353a2018-03-21 07:18:33 -07001118 return getNetworkAgentInfoForNetId(network.netId);
1119 }
1120
1121 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001122 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001123 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001124 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001125 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001126
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001127 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001128 synchronized (mVpns) {
1129 if (!mLockdownEnabled) {
1130 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001131 Vpn vpn = mVpns.get(user);
1132 if (vpn != null && vpn.appliesToUid(uid)) {
1133 return vpn.getUnderlyingNetworks();
1134 }
1135 }
1136 }
1137 return null;
1138 }
1139
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001141 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001142
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001143 final Network[] networks = getVpnUnderlyingNetworks(uid);
1144 if (networks != null) {
1145 // getUnderlyingNetworks() returns:
1146 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1147 // empty array => the VPN explicitly said "no default network".
1148 // non-empty array => the VPN specified one or more default networks; we use the
1149 // first one.
1150 if (networks.length > 0) {
1151 nai = getNetworkAgentInfoForNetwork(networks[0]);
1152 } else {
1153 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001154 }
1155 }
1156
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001157 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 return nai.getNetworkState();
1159 } else {
1160 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001162 }
1163
1164 /**
1165 * Check if UID should be blocked from using the network with the given LinkProperties.
1166 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1168 boolean ignoreBlocked) {
1169 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001170 if (ignoreBlocked) {
1171 return false;
1172 }
Robin Lee17e61832016-05-09 13:46:28 +01001173 synchronized (mVpns) {
1174 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001175 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001176 return true;
1177 }
1178 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001179 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001180 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001181 }
1182
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001183 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001184 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1185 return;
1186 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001187 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001188 synchronized (mBlockedAppUids) {
1189 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001190 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001191 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001192 blocked = false;
1193 } else {
1194 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001195 }
1196 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001197 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1198 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1199 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001200 }
1201
junyulai05986c62018-08-07 19:50:45 +08001202 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1203 boolean blocked) {
1204 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1205 return;
1206 }
1207 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1208 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1209 nri.mUid, nri.request.requestId, net.netId));
1210 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1211 }
1212
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001213 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001214 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1215 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001216 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001217 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001218 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001219 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1220
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001221 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001222 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001223 }
Hugo Benichi69744342017-11-27 10:57:16 +09001224 synchronized (mVpns) {
1225 if (mLockdownTracker != null) {
1226 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1227 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001228 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001229 }
1230
1231 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 * Return NetworkInfo for the active (i.e., connected) network interface.
1233 * It is assumed that at most one network is active at a time. If more
1234 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001235 * @return the info for the active network, or {@code null} if none is
1236 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001238 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001240 enforceAccessPermission();
1241 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001242 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001243 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001244 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1245 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247
Paul Jensen31a94f42015-02-13 14:18:39 -05001248 @Override
1249 public Network getActiveNetwork() {
1250 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001251 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001252 }
1253
1254 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001255 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001256 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001257 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001258 }
1259
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001260 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001261 final int user = UserHandle.getUserId(uid);
1262 int vpnNetId = NETID_UNSET;
1263 synchronized (mVpns) {
1264 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001265 // TODO : now that capabilities contain the UID, the appliesToUid test should
1266 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001267 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1268 }
1269 NetworkAgentInfo nai;
1270 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001271 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001272 if (nai != null) {
1273 final NetworkCapabilities requiredCaps =
1274 createDefaultNetworkCapabilitiesForUid(uid);
1275 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1276 return nai.network;
1277 }
1278 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001279 }
1280 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001281 if (nai != null
1282 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1283 nai = null;
1284 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001285 return nai != null ? nai.network : null;
1286 }
1287
Lorenzo Colitti18660282016-07-04 12:55:44 +09001288 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001289 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1290 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001291 final int uid = Binder.getCallingUid();
1292 NetworkState state = getUnfilteredActiveNetworkState(uid);
1293 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001294 }
1295
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001296 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001297 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001298 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001299 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001300 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001301 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001302 }
1303
1304 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 public NetworkInfo getNetworkInfo(int networkType) {
1306 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001307 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001308 if (getVpnUnderlyingNetworks(uid) != null) {
1309 // A VPN is active, so we may need to return one of its underlying networks. This
1310 // information is not available in LegacyTypeTracker, so we have to get it from
1311 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001312 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001313 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001314 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001315 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001316 }
1317 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001318 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001319 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 }
1321
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001322 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001323 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001324 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001325 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001326 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001327 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001328 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001329 return state.networkInfo;
1330 } else {
1331 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001332 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001333 }
1334
1335 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 public NetworkInfo[] getAllNetworkInfo() {
1337 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001338 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001339 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1340 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001341 NetworkInfo info = getNetworkInfo(networkType);
1342 if (info != null) {
1343 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001346 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001349 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001350 public Network getNetworkForType(int networkType) {
1351 enforceAccessPermission();
1352 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001353 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001354 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001355 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001356 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001357 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001358 }
1359
1360 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001361 public Network[] getAllNetworks() {
1362 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001363 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001364 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001365 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001366 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001367 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001368 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001369 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001370 }
1371
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001372 @Override
1373 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1374 // The basic principle is: if an app's traffic could possibly go over a
1375 // network, without the app doing anything multinetwork-specific,
1376 // (hence, by "default"), then include that network's capabilities in
1377 // the array.
1378 //
1379 // In the normal case, app traffic only goes over the system's default
1380 // network connection, so that's the only network returned.
1381 //
1382 // With a VPN in force, some app traffic may go into the VPN, and thus
1383 // over whatever underlying networks the VPN specifies, while other app
1384 // traffic may go over the system default network (e.g.: a split-tunnel
1385 // VPN, or an app disallowed by the VPN), so the set of networks
1386 // returned includes the VPN's underlying networks and the system
1387 // default.
1388 enforceAccessPermission();
1389
Chalard Jean4133a122018-06-04 13:33:12 +09001390 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001391
1392 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001393 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001394 if (nc != null) {
1395 result.put(nai.network, nc);
1396 }
1397
Hugo Benichi69744342017-11-27 10:57:16 +09001398 synchronized (mVpns) {
1399 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001400 Vpn vpn = mVpns.get(userId);
1401 if (vpn != null) {
1402 Network[] networks = vpn.getUnderlyingNetworks();
1403 if (networks != null) {
1404 for (Network network : networks) {
1405 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001406 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001407 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001408 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001409 }
1410 }
1411 }
1412 }
1413 }
1414 }
1415
1416 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1417 out = result.values().toArray(out);
1418 return out;
1419 }
1420
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001421 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001422 public boolean isNetworkSupported(int networkType) {
1423 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001424 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001425 }
1426
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001427 /**
1428 * Return LinkProperties for the active (i.e., connected) default
1429 * network interface. It is assumed that at most one default network
1430 * is active at a time. If more than one is active, it is indeterminate
1431 * which will be returned.
1432 * @return the ip properties for the active network, or {@code null} if
1433 * none is active
1434 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001435 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001436 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001437 enforceAccessPermission();
1438 final int uid = Binder.getCallingUid();
1439 NetworkState state = getUnfilteredActiveNetworkState(uid);
1440 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001441 }
1442
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001443 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001444 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001445 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001446 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1447 if (nai != null) {
1448 synchronized (nai) {
1449 return new LinkProperties(nai.linkProperties);
1450 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001451 }
1452 return null;
1453 }
1454
Robert Greenwalt12e67352014-05-13 21:41:06 -07001455 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001456 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001457 public LinkProperties getLinkProperties(Network network) {
1458 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001459 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1460 }
1461
1462 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1463 if (nai == null) {
1464 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001465 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001466 synchronized (nai) {
1467 return new LinkProperties(nai.linkProperties);
1468 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001469 }
1470
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001471 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001472 if (nai != null) {
1473 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001474 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001475 return networkCapabilitiesRestrictedForCallerPermissions(
1476 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001477 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001478 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001479 }
1480 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001481 return null;
1482 }
1483
1484 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001485 public NetworkCapabilities getNetworkCapabilities(Network network) {
1486 enforceAccessPermission();
1487 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1488 }
1489
Chalard Jeanb03a6222018-04-11 21:09:10 +09001490 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001491 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001492 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001493 if (!checkSettingsPermission(callerPid, callerUid)) {
1494 newNc.setUids(null);
1495 newNc.setSSID(null);
1496 }
Etan Cohen836ad572018-12-30 17:59:59 -08001497 if (newNc.getNetworkSpecifier() != null) {
1498 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1499 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001500 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001501 }
1502
Chalard Jeanb552c462018-02-21 18:43:54 +09001503 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1504 if (!checkSettingsPermission()) {
1505 nc.setSingleUid(Binder.getCallingUid());
1506 }
1507 }
1508
Chalard Jean26aa91a2018-03-20 19:13:57 +09001509 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1510 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1511 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1512 }
1513 }
1514
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001515 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001516 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001517 // Require internal since we're handing out IMSI details
1518 enforceConnectivityInternalPermission();
1519
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001520 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001521 for (Network network : getAllNetworks()) {
1522 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1523 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001524 // TODO (b/73321673) : NetworkState contains a copy of the
1525 // NetworkCapabilities, which may contain UIDs of apps to which the
1526 // network applies. Should the UIDs be cleared so as not to leak or
1527 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001528 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001529 }
1530 }
1531 return result.toArray(new NetworkState[result.size()]);
1532 }
1533
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001534 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001535 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001536 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001537 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1538 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1539 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001540 }
1541
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001542 @Override
1543 public boolean isActiveNetworkMetered() {
1544 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001545
Eric Enslenc81ef192018-02-07 18:03:53 -08001546 final int uid = Binder.getCallingUid();
1547 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001548 if (caps != null) {
1549 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1550 } else {
1551 // Always return the most conservative value
1552 return true;
1553 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001554 }
1555
Jeff Sharkey216c1812012-08-05 14:29:23 -07001556 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1557 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001558 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001559 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001560 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001561 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001562 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001563
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001564 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001565 * Ensures that the system cannot call a particular method.
1566 */
1567 private boolean disallowedBecauseSystemCaller() {
1568 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1569 // requestRouteToHost.
1570 if (isSystem(Binder.getCallingUid())) {
1571 log("This method exists only for app backwards compatibility"
1572 + " and must not be called by system services.");
1573 return true;
1574 }
1575 return false;
1576 }
1577
1578 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 * Ensure that a network route exists to deliver traffic to the specified
1580 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001581 * @param networkType the type of the network over which traffic to the
1582 * specified host is to be routed
1583 * @param hostAddress the IP address of the host to which the route is
1584 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 * @return {@code true} on success, {@code false} on failure
1586 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001587 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001588 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001589 if (disallowedBecauseSystemCaller()) {
1590 return false;
1591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001593 if (mProtectedNetworks.contains(networkType)) {
1594 enforceConnectivityInternalPermission();
1595 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001596
Chad Brubakerc0234532014-02-14 13:24:29 -08001597 InetAddress addr;
1598 try {
1599 addr = InetAddress.getByAddress(hostAddress);
1600 } catch (UnknownHostException e) {
1601 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1602 return false;
1603 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001606 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 return false;
1608 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001609
1610 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1611 if (nai == null) {
1612 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1613 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1614 } else {
1615 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1616 }
1617 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001618 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001619
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001620 DetailedState netState;
1621 synchronized (nai) {
1622 netState = nai.networkInfo.getDetailedState();
1623 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001624
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001625 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001626 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001627 log("requestRouteToHostAddress on down network "
1628 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001629 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001630 }
1631 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001633
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001634 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001635 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001636 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001637 LinkProperties lp;
1638 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001639 synchronized (nai) {
1640 lp = nai.linkProperties;
1641 netId = nai.network.netId;
1642 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001643 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001644 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1645 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001646 } finally {
1647 Binder.restoreCallingIdentity(token);
1648 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001649 }
1650
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001651 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001652 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001653 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001654 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001655 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001656 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001657 if (bestRoute.getGateway().equals(addr)) {
1658 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001659 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001660 } else {
1661 // if we will connect to this through another route, add a direct route
1662 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001663 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001664 }
1665 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001666 if (DBG) log("Adding legacy route " + bestRoute +
1667 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001668 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001669 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001670 } catch (Exception e) {
1671 // never crash - catch them all
1672 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001673 return false;
1674 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001675 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677
dalyk7301aa42018-03-05 12:42:22 -05001678 @VisibleForTesting
1679 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1680 @Override
1681 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1682 String hostname, boolean validated) {
1683 try {
1684 mHandler.sendMessage(mHandler.obtainMessage(
1685 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1686 new PrivateDnsValidationUpdate(netId,
1687 InetAddress.parseNumericAddress(ipAddress),
1688 hostname, validated)));
1689 } catch (IllegalArgumentException e) {
1690 loge("Error parsing ip address in validation event");
1691 }
1692 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001693
1694 @Override
1695 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1696 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1697 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1698 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1699 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1700 // event callback for certain nai. e.g. cellular. Register here to pass to
1701 // NetworkMonitor instead.
1702 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1703 // registerNetworkAgent to have NetworkMonitor created with system process as design
1704 // expectation. Also, NetdEventListenerService only allow one callback from each
1705 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1706 // NetworkMonitor registrants.
1707 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001708 try {
1709 nai.networkMonitor().notifyDnsResponse(returnCode);
1710 } catch (RemoteException e) {
1711 e.rethrowFromSystemServer();
1712 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001713 }
1714 }
dalyk7301aa42018-03-05 12:42:22 -05001715 };
1716
1717 @VisibleForTesting
1718 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001719 final IIpConnectivityMetrics ipConnectivityMetrics =
1720 IIpConnectivityMetrics.Stub.asInterface(
1721 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1722 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001723 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001724 return;
dalyk7301aa42018-03-05 12:42:22 -05001725 }
1726
1727 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001728 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001729 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1730 mNetdEventCallback);
1731 } catch (Exception e) {
1732 loge("Error registering netd callback: " + e);
1733 }
1734 }
1735
Jeff Sharkey75d31892018-01-18 22:01:59 +09001736 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001737 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001738 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001739 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001740 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001741 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001742 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001743 // caller is NPMS, since we only register with them
1744 if (LOGD_BLOCKED_NETWORKINFO) {
1745 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1746 }
1747 mHandler.sendMessage(mHandler.obtainMessage(
1748 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1749
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001750 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001751 if (restrictBackground) {
1752 log("onRestrictBackgroundChanged(true): disabling tethering");
1753 mTethering.untetherAll();
1754 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001755 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001756 };
1757
junyulai05986c62018-08-07 19:50:45 +08001758 void handleUidRulesChanged(int uid, int newRules) {
1759 // skip update when we've already applied rules
1760 final int oldRules = mUidRules.get(uid, RULE_NONE);
1761 if (oldRules == newRules) return;
1762
1763 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1764
1765 if (newRules == RULE_NONE) {
1766 mUidRules.delete(uid);
1767 } else {
1768 mUidRules.put(uid, newRules);
1769 }
1770 }
1771
1772 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1773 if (mRestrictBackground == restrictBackground) return;
1774
1775 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1776 final boolean curMetered = nai.networkCapabilities.isMetered();
1777 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1778 restrictBackground);
1779 }
1780
1781 mRestrictBackground = restrictBackground;
1782 }
1783
1784 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1785 boolean isBackgroundRestricted) {
1786 synchronized (mVpns) {
1787 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1788 // Because the return value of this function depends on the list of UIDs the
1789 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1790 // list all state depending on the return value of this function has to be recomputed.
1791 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1792 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001793 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001794 return true;
1795 }
1796 }
1797
1798 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1799 isNetworkMetered, isBackgroundRestricted);
1800 }
1801
Robin Lee3b3dd942015-05-12 18:14:58 +01001802 /**
1803 * Require that the caller is either in the same user or has appropriate permission to interact
1804 * across users.
1805 *
1806 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1807 */
1808 private void enforceCrossUserPermission(int userId) {
1809 if (userId == UserHandle.getCallingUserId()) {
1810 // Not a cross-user call.
1811 return;
1812 }
1813 mContext.enforceCallingOrSelfPermission(
1814 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1815 "ConnectivityService");
1816 }
1817
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001818 private void enforceAnyPermissionOf(String... permissions) {
1819 for (String permission : permissions) {
1820 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
1821 return;
1822 }
1823 }
1824 throw new SecurityException(
1825 "Requires one of the following permissions: " + String.join(", ", permissions) + ".");
1826 }
1827
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001828 private void enforceInternetPermission() {
1829 mContext.enforceCallingOrSelfPermission(
1830 android.Manifest.permission.INTERNET,
1831 "ConnectivityService");
1832 }
1833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001835 mContext.enforceCallingOrSelfPermission(
1836 android.Manifest.permission.ACCESS_NETWORK_STATE,
1837 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839
1840 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001841 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843
Charles He36738632017-05-15 17:07:18 +01001844 private void enforceSettingsPermission() {
1845 mContext.enforceCallingOrSelfPermission(
1846 android.Manifest.permission.NETWORK_SETTINGS,
1847 "ConnectivityService");
1848 }
1849
Chalard Jeanb552c462018-02-21 18:43:54 +09001850 private boolean checkSettingsPermission() {
1851 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1852 android.Manifest.permission.NETWORK_SETTINGS);
1853 }
1854
1855 private boolean checkSettingsPermission(int pid, int uid) {
1856 return PERMISSION_GRANTED == mContext.checkPermission(
1857 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1858 }
1859
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001860 private void enforceTetherAccessPermission() {
1861 mContext.enforceCallingOrSelfPermission(
1862 android.Manifest.permission.ACCESS_NETWORK_STATE,
1863 "ConnectivityService");
1864 }
1865
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001866 private void enforceConnectivityInternalPermission() {
1867 mContext.enforceCallingOrSelfPermission(
1868 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1869 "ConnectivityService");
1870 }
1871
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001872 private void enforceNetworkStackSettingsOrSetup() {
1873 enforceAnyPermissionOf(
1874 android.Manifest.permission.NETWORK_SETTINGS,
1875 android.Manifest.permission.NETWORK_SETUP_WIZARD,
1876 android.Manifest.permission.NETWORK_STACK);
1877 }
1878
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001879 private boolean checkNetworkStackPermission() {
1880 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1881 android.Manifest.permission.NETWORK_STACK);
1882 }
1883
Hugo Benichi514da602016-07-19 15:59:27 +09001884 private void enforceConnectivityRestrictedNetworksPermission() {
1885 try {
1886 mContext.enforceCallingOrSelfPermission(
1887 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1888 "ConnectivityService");
1889 return;
1890 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1891 enforceConnectivityInternalPermission();
1892 }
1893
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001894 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001895 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001896 }
1897
Lorenzo Colitti18660282016-07-04 12:55:44 +09001898 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001899 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001900 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001901 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001902 }
1903
1904 private void sendInetConditionBroadcast(NetworkInfo info) {
1905 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1906 }
1907
Wink Saville628b0852011-08-04 15:01:58 -07001908 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001909 synchronized (mVpns) {
1910 if (mLockdownTracker != null) {
1911 info = new NetworkInfo(info);
1912 mLockdownTracker.augmentNetworkInfo(info);
1913 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001914 }
1915
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001916 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001917 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001918 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 if (info.isFailover()) {
1920 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1921 info.setFailover(false);
1922 }
1923 if (info.getReason() != null) {
1924 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1925 }
1926 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001927 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1928 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001930 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001931 return intent;
1932 }
1933
1934 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1935 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1936 }
1937
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001938 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001939 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1940 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1941 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001942 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001943 final long ident = Binder.clearCallingIdentity();
1944 try {
1945 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1946 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1947 } finally {
1948 Binder.restoreCallingIdentity(ident);
1949 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001950 }
1951
Mike Lockwood0f79b542009-08-14 14:18:49 -04001952 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001953 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09001954 if (!mSystemReady
1955 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001956 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001957 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001958 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001959 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001960 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001961 }
1962
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001963 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001964 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001965 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001966 final NetworkInfo ni = intent.getParcelableExtra(
1967 ConnectivityManager.EXTRA_NETWORK_INFO);
1968 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1969 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1970 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001971 } else {
1972 BroadcastOptions opts = BroadcastOptions.makeBasic();
1973 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1974 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001975 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001976 final IBatteryStats bs = BatteryStatsService.getService();
1977 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001978 bs.noteConnectivityChanged(intent.getIntExtra(
1979 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001980 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001981 } catch (RemoteException e) {
1982 }
Chad Brubakerac925012018-03-08 10:37:09 -08001983 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001984 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001985 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001986 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001987 } finally {
1988 Binder.restoreCallingIdentity(ident);
1989 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001990 }
1991 }
1992
1993 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09001994 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001995 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09001996 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07001997
Hugo Benichi20035e02017-04-26 14:53:28 +09001998 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001999 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002000 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002001 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002002 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002003 }
2004 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002005
Robin Lee244ce8e2016-01-05 18:03:46 +00002006 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2007 // for user to unlock device too.
2008 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002009
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002010 // Create network requests for always-on networks.
2011 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002012
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002013 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002014
2015 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002019 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002020 *
2021 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002022 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002023 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002024 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2025 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002026
2027 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002029
Robert Greenwalt7b816022014-04-18 15:25:25 -07002030 if (networkAgent.networkCapabilities.hasTransport(
2031 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002032 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2033 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002034 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002035 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 } else if (networkAgent.networkCapabilities.hasTransport(
2037 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002038 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2039 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002040 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002041 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002042 } else {
2043 // do not track any other networks
2044 timeout = 0;
2045 }
2046
Robert Greenwalt7b816022014-04-18 15:25:25 -07002047 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002048 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002049 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002050 } catch (Exception e) {
2051 // You shall not crash!
2052 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002053 }
2054 }
2055 }
2056
2057 /**
2058 * Remove data activity tracking when network disconnects.
2059 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002060 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2061 final String iface = networkAgent.linkProperties.getInterfaceName();
2062 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002063
Robert Greenwalt7b816022014-04-18 15:25:25 -07002064 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2065 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002066 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002067 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002068 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002069 } catch (Exception e) {
2070 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002071 }
2072 }
2073 }
2074
2075 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002076 * Update data activity tracking when network state is updated.
2077 */
2078 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2079 NetworkAgentInfo oldNetwork) {
2080 if (newNetwork != null) {
2081 setupDataActivityTracking(newNetwork);
2082 }
2083 if (oldNetwork != null) {
2084 removeDataActivityTracking(oldNetwork);
2085 }
2086 }
2087 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002088 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002089 * and set it on it's iface.
2090 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002091 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2092 final String iface = newLp.getInterfaceName();
2093 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002094 if (oldLp == null && mtu == 0) {
2095 // Silently ignore unset MTU value.
2096 return;
2097 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002098 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2099 if (VDBG) log("identical MTU - not setting");
2100 return;
2101 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002102 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002103 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002104 return;
2105 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002106
w1997615afd812014-08-05 15:18:11 -07002107 // Cannot set MTU without interface name
2108 if (TextUtils.isEmpty(iface)) {
2109 loge("Setting MTU size with null iface.");
2110 return;
2111 }
2112
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002114 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002115 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 } catch (Exception e) {
2117 Slog.e(TAG, "exception in setMtu()" + e);
2118 }
2119 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002120
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002121 @VisibleForTesting
2122 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002123 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2124
2125 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002126 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002127 protected MockableSystemProperties getSystemProperties() {
2128 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002129 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002130
lucaslin041a1af2018-11-28 19:27:52 +08002131 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002132 String[] values = null;
2133 if (tcpBufferSizes != null) {
2134 values = tcpBufferSizes.split(",");
2135 }
2136
2137 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002138 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002139 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2140 values = tcpBufferSizes.split(",");
2141 }
2142
2143 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2144
2145 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002146 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002147
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002148 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2149 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2150 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002151 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002152 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002153 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002154 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002155
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002156 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002157 Settings.Global.TCP_DEFAULT_INIT_RWND,
2158 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002159 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2160 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002161 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002162 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002163 }
2164
Robert Greenwalt562cc542014-05-15 18:07:26 -07002165 @Override
2166 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002167 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002168 NETWORK_RESTORE_DELAY_PROP_NAME);
2169 if(restoreDefaultNetworkDelayStr != null &&
2170 restoreDefaultNetworkDelayStr.length() != 0) {
2171 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002172 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002173 } catch (NumberFormatException e) {
2174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002176 // if the system property isn't set, use the value for the apn type
2177 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2178
2179 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2180 (mNetConfigs[networkType] != null)) {
2181 ret = mNetConfigs[networkType].restoreTime;
2182 }
2183 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
2185
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002186 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2187 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2188 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002189 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002190 // Start gathering diagnostic information.
2191 netDiags.add(new NetworkDiagnostics(
2192 nai.network,
2193 new LinkProperties(nai.linkProperties), // Must be a copy.
2194 DIAG_TIME_MS));
2195 }
2196
2197 for (NetworkDiagnostics netDiag : netDiags) {
2198 pw.println();
2199 netDiag.waitForMeasurements();
2200 netDiag.dump(pw);
2201 }
2202 }
2203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002205 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002206 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2207 }
2208
2209 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002210 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002211 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002212 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002213
Erik Kline3f8306b2018-05-01 16:51:44 +09002214 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002215 dumpNetworkDiagnostics(pw);
2216 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002217 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002218 mTethering.dump(fd, pw, args);
2219 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002220 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2221 dumpNetworks(pw);
2222 return;
2223 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2224 dumpNetworkRequests(pw);
2225 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002226 }
Erik Kline379747a2015-06-05 17:47:34 +09002227
Lorenzo Colittie3805462015-06-03 11:18:24 +09002228 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002229 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002230 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002231 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002232 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002233 pw.println();
2234
Paul Jensen85cf78e2015-06-25 13:25:07 -04002235 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002236 pw.print("Active default network: ");
2237 if (defaultNai == null) {
2238 pw.println("none");
2239 } else {
2240 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002242 pw.println();
2243
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002244 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002245 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002246 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002247 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002248 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002249
junyulai05986c62018-08-07 19:50:45 +08002250 pw.print("Restrict background: ");
2251 pw.println(mRestrictBackground);
2252 pw.println();
2253
2254 pw.println("Status for known UIDs:");
2255 pw.increaseIndent();
2256 final int size = mUidRules.size();
2257 for (int i = 0; i < size; i++) {
2258 // Don't crash if the array is modified while dumping in bugreports.
2259 try {
2260 final int uid = mUidRules.keyAt(i);
2261 final int uidRules = mUidRules.get(uid, RULE_NONE);
2262 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2263 } catch (ArrayIndexOutOfBoundsException e) {
2264 pw.println(" ArrayIndexOutOfBoundsException");
2265 } catch (ConcurrentModificationException e) {
2266 pw.println(" ConcurrentModificationException");
2267 }
2268 }
2269 pw.println();
2270 pw.decreaseIndent();
2271
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002272 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002273 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002274 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002275 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002276 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002277
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002278 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002279
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002280 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002281 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002282
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002283 pw.println();
2284 mKeepaliveTracker.dump(pw);
2285
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002286 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002287 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002288
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002289 pw.println();
2290 mMultipathPolicyTracker.dump(pw);
2291
Erik Kline3f8306b2018-05-01 16:51:44 +09002292 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002293 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002294 pw.println("mNetworkRequestInfoLogs (most recent first):");
2295 pw.increaseIndent();
2296 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2297 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002298
2299 pw.println();
2300 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2301 pw.increaseIndent();
2302 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2303 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002304
2305 pw.println();
2306 pw.println("NetTransition WakeLock activity (most recent first):");
2307 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002308 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2309 pw.println("total releases: " + mTotalWakelockReleases);
2310 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2311 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2312 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2313 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2314 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2315 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002316 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002317
2318 pw.println();
2319 pw.println("bandwidth update requests (by uid):");
2320 pw.increaseIndent();
2321 synchronized (mBandwidthRequests) {
2322 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2323 pw.println("[" + mBandwidthRequests.keyAt(i)
2324 + "]: " + mBandwidthRequests.valueAt(i));
2325 }
2326 }
2327 pw.decreaseIndent();
2328
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002329 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
2332
Hugo Benichi14683812018-09-03 08:32:56 +09002333 private void dumpNetworks(IndentingPrintWriter pw) {
2334 for (NetworkAgentInfo nai : networksSortedById()) {
2335 pw.println(nai.toString());
2336 pw.increaseIndent();
2337 pw.println(String.format(
2338 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2339 nai.numForegroundNetworkRequests(),
2340 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2341 nai.numBackgroundNetworkRequests(),
2342 nai.numNetworkRequests()));
2343 pw.increaseIndent();
2344 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2345 pw.println(nai.requestAt(i).toString());
2346 }
2347 pw.decreaseIndent();
2348 pw.println("Lingered:");
2349 pw.increaseIndent();
2350 nai.dumpLingerTimers(pw);
2351 pw.decreaseIndent();
2352 pw.decreaseIndent();
2353 }
2354 }
2355
2356 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2357 for (NetworkRequestInfo nri : requestsSortedById()) {
2358 pw.println(nri.toString());
2359 }
2360 }
2361
Hugo Benichia2a917c2018-09-03 08:19:02 +09002362 /**
2363 * Return an array of all current NetworkAgentInfos sorted by network id.
2364 */
2365 private NetworkAgentInfo[] networksSortedById() {
2366 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2367 networks = mNetworkAgentInfos.values().toArray(networks);
2368 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2369 return networks;
2370 }
2371
2372 /**
2373 * Return an array of all current NetworkRequest sorted by request id.
2374 */
2375 private NetworkRequestInfo[] requestsSortedById() {
2376 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2377 requests = mNetworkRequests.values().toArray(requests);
2378 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2379 return requests;
2380 }
2381
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002382 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002383 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002384 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002385 if (officialNai != null && officialNai.equals(nai)) return true;
2386 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002387 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002388 " - " + nai);
2389 }
2390 return false;
2391 }
2392
Robert Greenwalt42acef32009-08-12 16:08:25 -07002393 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002394 private class NetworkStateTrackerHandler extends Handler {
2395 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002396 super(looper);
2397 }
2398
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002399 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002401 default:
2402 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002403 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002404 handleAsyncChannelHalfConnect(msg);
2405 break;
2406 }
2407 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2408 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2409 if (nai != null) nai.asyncChannel.disconnect();
2410 break;
2411 }
2412 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2413 handleAsyncChannelDisconnected(msg);
2414 break;
2415 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002416 }
2417 return true;
2418 }
2419
2420 private void maybeHandleNetworkAgentMessage(Message msg) {
2421 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2422 if (nai == null) {
2423 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002424 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002425 }
2426 return;
2427 }
2428
2429 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002430 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002431 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2432 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002433 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2434 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002435 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002436 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002437 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002438 break;
2439 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002440 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002441 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002442 break;
2443 }
2444 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002445 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002446 updateNetworkInfo(nai, info);
2447 break;
2448 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002449 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002450 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002451 break;
2452 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002453 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002454 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2455 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002456 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002457 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002458 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002459 break;
2460 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002461 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002462 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2463 break;
2464 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002465 }
2466 }
2467
2468 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2469 switch (msg.what) {
2470 default:
2471 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002472 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002473 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002474 if (nai == null) break;
2475
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002476 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002477 final boolean wasValidated = nai.lastValidated;
2478 final boolean wasDefault = isDefaultNetwork(nai);
2479
Erik Klinea24d4592018-01-11 21:07:29 +09002480 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2481
Erik Klinea24d4592018-01-11 21:07:29 +09002482 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002483 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2484 ? " with redirect to " + redirectUrl
2485 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002486 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2487 }
Erik Klinea24d4592018-01-11 21:07:29 +09002488 if (valid != nai.lastValidated) {
2489 if (wasDefault) {
2490 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2491 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002492 }
Erik Klinea24d4592018-01-11 21:07:29 +09002493 final int oldScore = nai.getCurrentScore();
2494 nai.lastValidated = valid;
2495 nai.everValidated |= valid;
2496 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2497 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2498 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Erik Klinec6d00222018-06-26 18:53:43 +09002499 if (valid) handleFreshlyValidatedNetwork(nai);
Erik Klinea24d4592018-01-11 21:07:29 +09002500 }
2501 updateInetCondition(nai);
2502 // Let the NetworkAgent know the state of its network
2503 Bundle redirectUrlBundle = new Bundle();
2504 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2505 nai.asyncChannel.sendMessage(
2506 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2507 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2508 0, redirectUrlBundle);
2509 if (wasValidated && !nai.lastValidated) {
2510 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002511 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002512 break;
2513 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002514 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002515 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002516 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002517 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002518 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002519 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002520 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002521 nai.lastCaptivePortalDetected = visible;
2522 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002523 if (nai.lastCaptivePortalDetected &&
2524 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2525 if (DBG) log("Avoiding captive portal network: " + nai.name());
2526 nai.asyncChannel.sendMessage(
2527 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2528 teardownUnneededNetwork(nai);
2529 break;
2530 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002531 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002532 }
2533 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002534 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002535 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002536 if (nai == null) {
2537 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2538 break;
2539 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002540 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002541 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002542 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002543 }
Paul Jensen869868be2014-05-15 10:33:05 -04002544 }
Paul Jensen869868be2014-05-15 10:33:05 -04002545 break;
2546 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002547 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002548 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002549 if (nai == null) break;
2550
Erik Kline736353a2018-03-21 07:18:33 -07002551 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002552 break;
2553 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002554 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002555 return true;
2556 }
2557
Calvin Onbe96da12016-10-11 15:10:46 -07002558 private int getCaptivePortalMode() {
2559 return Settings.Global.getInt(mContext.getContentResolver(),
2560 Settings.Global.CAPTIVE_PORTAL_MODE,
2561 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2562 }
2563
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002564 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2565 switch (msg.what) {
2566 default:
2567 return false;
2568 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2569 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2570 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2571 handleLingerComplete(nai);
2572 }
2573 break;
2574 }
2575 }
2576 return true;
2577 }
2578
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002579 @Override
2580 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002581 if (!maybeHandleAsyncChannelMessage(msg) &&
2582 !maybeHandleNetworkMonitorMessage(msg) &&
2583 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002584 maybeHandleNetworkAgentMessage(msg);
2585 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002586 }
2587 }
2588
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002589 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2590 private final NetworkAgentInfo mNai;
2591
2592 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2593 mNai = nai;
2594 }
2595
2596 @Override
2597 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2598 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2599 new Pair<>(mNai, networkMonitor)));
2600 }
2601
2602 @Override
2603 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2604 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2605 testResult, mNai.network.netId, redirectUrl));
2606 }
2607
2608 @Override
2609 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2610 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2611 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2612 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2613 }
2614
2615 @Override
2616 public void showProvisioningNotification(String action) {
2617 final Intent intent = new Intent(action);
2618 intent.setPackage(NETWORKSTACK_PACKAGE_NAME);
2619
2620 final PendingIntent pendingIntent;
2621 // Only the system server can register notifications with package "android"
2622 final long token = Binder.clearCallingIdentity();
2623 try {
2624 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2625 } finally {
2626 Binder.restoreCallingIdentity(token);
2627 }
2628 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2629 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2630 mNai.network.netId,
2631 pendingIntent));
2632 }
2633
2634 @Override
2635 public void hideProvisioningNotification() {
2636 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2637 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2638 mNai.network.netId));
2639 }
2640 }
2641
Erik Kline736353a2018-03-21 07:18:33 -07002642 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002643 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002644 }
2645
Erik Klinec6d00222018-06-26 18:53:43 +09002646 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2647 if (nai == null) return;
2648 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2649 // in order to restart a validation pass from within netd.
2650 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2651 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2652 updateDnses(nai.linkProperties, null, nai.network.netId);
2653 }
2654 }
2655
Erik Klinea24d4592018-01-11 21:07:29 +09002656 private void handlePrivateDnsSettingsChanged() {
2657 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2658
2659 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002660 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002661 if (networkRequiresValidation(nai)) {
2662 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2663 }
Erik Klinea24d4592018-01-11 21:07:29 +09002664 }
2665 }
2666
Erik Kline736353a2018-03-21 07:18:33 -07002667 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2668 // Private DNS only ever applies to networks that might provide
2669 // Internet access and therefore also require validation.
2670 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002671
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002672 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002673 // schedule DNS resolutions. If a DNS resolution is required the
2674 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002675 try {
2676 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2677 } catch (RemoteException e) {
2678 e.rethrowFromSystemServer();
2679 }
Erik Kline736353a2018-03-21 07:18:33 -07002680
2681 // With Private DNS bypass support, we can proceed to update the
2682 // Private DNS config immediately, even if we're in strict mode
2683 // and have not yet resolved the provider name into a set of IPs.
2684 updatePrivateDns(nai, cfg);
2685 }
2686
2687 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2688 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002689 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002690 }
2691
dalyk7301aa42018-03-05 12:42:22 -05002692 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2693 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2694 if (nai == null) {
2695 return;
2696 }
2697 mDnsManager.updatePrivateDnsValidation(update);
2698 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2699 }
2700
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002701 private void updateLingerState(NetworkAgentInfo nai, long now) {
2702 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2703 // 2. If the network was lingering and there are now requests, unlinger it.
2704 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2705 // one lingered request, start lingering.
2706 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002707 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002708 if (DBG) log("Unlingering " + nai.name());
2709 nai.unlinger();
2710 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002711 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002712 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002713 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002714 nai.linger();
2715 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2716 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2717 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002718 }
2719
Robert Greenwalt7b816022014-04-18 15:25:25 -07002720 private void handleAsyncChannelHalfConnect(Message msg) {
2721 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002722 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002723 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2724 if (VDBG) log("NetworkFactory connected");
2725 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002726 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002727 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002728 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002729 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002730 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002731 }
2732 } else {
2733 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002734 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002735 }
2736 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2737 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2738 if (VDBG) log("NetworkAgent connected");
2739 // A network agent has requested a connection. Establish the connection.
2740 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2741 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2742 } else {
2743 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002744 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002745 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002746 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002747 synchronized (mNetworkForNetId) {
2748 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002749 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002750 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002751 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002752 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002753 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002754 }
2755 }
2756 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002757
Chalard Jean392971c2018-05-11 20:19:20 +09002758 // This is a no-op if it's called with a message designating a network that has
2759 // already been destroyed, because its reference will not be found in the relevant
2760 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002761 private void handleAsyncChannelDisconnected(Message msg) {
2762 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2763 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002764 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002765 } else {
2766 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2767 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002768 }
2769 }
2770
Chalard Jean392971c2018-05-11 20:19:20 +09002771 // Destroys a network, remove references to it from the internal state managed by
2772 // ConnectivityService, free its interfaces and clean up.
2773 // Must be called on the Handler thread.
2774 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2775 if (DBG) {
2776 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2777 }
2778 // A network agent has disconnected.
2779 // TODO - if we move the logic to the network agent (have them disconnect
2780 // because they lost all their requests or because their score isn't good)
2781 // then they would disconnect organically, report their new state and then
2782 // disconnect the channel.
2783 if (nai.networkInfo.isConnected()) {
2784 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2785 null, null);
2786 }
2787 final boolean wasDefault = isDefaultNetwork(nai);
2788 if (wasDefault) {
2789 mDefaultInetConditionPublished = 0;
2790 // Log default network disconnection before required book-keeping.
2791 // Let rematchAllNetworksAndRequests() below record a new default network event
2792 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2793 // whose timestamps tell how long it takes to recover a default network.
2794 long now = SystemClock.elapsedRealtime();
2795 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2796 }
2797 notifyIfacesChangedForNetworkStats();
2798 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2799 // by other networks that are already connected. Perhaps that can be done by
2800 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2801 // of rematchAllNetworksAndRequests
2802 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2803 mKeepaliveTracker.handleStopAllKeepalives(nai,
2804 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2805 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2806 // Disable wakeup packet monitoring for each interface.
2807 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2808 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002809 try {
2810 nai.networkMonitor().notifyNetworkDisconnected();
2811 } catch (RemoteException e) {
2812 e.rethrowFromSystemServer();
2813 }
Chalard Jean392971c2018-05-11 20:19:20 +09002814 mNetworkAgentInfos.remove(nai.messenger);
2815 nai.maybeStopClat();
2816 synchronized (mNetworkForNetId) {
2817 // Remove the NetworkAgent, but don't mark the netId as
2818 // available until we've told netd to delete it below.
2819 mNetworkForNetId.remove(nai.network.netId);
2820 }
2821 // Remove all previously satisfied requests.
2822 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2823 NetworkRequest request = nai.requestAt(i);
2824 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2825 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2826 clearNetworkForRequest(request.requestId);
2827 sendUpdatedScoreToFactories(request, 0);
2828 }
2829 }
2830 nai.clearLingerState();
2831 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002832 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002833 notifyLockdownVpn(nai);
2834 ensureNetworkTransitionWakelock(nai.name());
2835 }
2836 mLegacyTypeTracker.remove(nai, wasDefault);
2837 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2838 updateAllVpnsCapabilities();
2839 }
2840 rematchAllNetworksAndRequests(null, 0);
2841 mLingerMonitor.noteDisconnect(nai);
2842 if (nai.created) {
2843 // Tell netd to clean up the configuration for this network
2844 // (routing rules, DNS, etc).
2845 // This may be slow as it requires a lot of netd shelling out to ip and
2846 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2847 // after we've rematched networks with requests which should make a potential
2848 // fallback network the default or requested a new network from the
2849 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2850 // long time.
2851 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002852 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002853 } catch (Exception e) {
2854 loge("Exception removing network: " + e);
2855 }
2856 mDnsManager.removeNetwork(nai.network);
2857 }
2858 synchronized (mNetworkForNetId) {
2859 mNetIdInUse.delete(nai.network.netId);
2860 }
2861 }
2862
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002863 // If this method proves to be too slow then we can maintain a separate
2864 // pendingIntent => NetworkRequestInfo map.
2865 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2866 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2867 Intent intent = pendingIntent.getIntent();
2868 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2869 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2870 if (existingPendingIntent != null &&
2871 existingPendingIntent.getIntent().filterEquals(intent)) {
2872 return entry.getValue();
2873 }
2874 }
2875 return null;
2876 }
2877
2878 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2879 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2880
2881 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2882 if (existingRequest != null) { // remove the existing request.
2883 if (DBG) log("Replacing " + existingRequest.request + " with "
2884 + nri.request + " because their intents matched.");
2885 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2886 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002887 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002888 }
2889
Erik Klineda4bfa82015-04-30 12:58:40 +09002890 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002891 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002892 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002893 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002894 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002895 if (nri.request.networkCapabilities.hasSignalStrength() &&
2896 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2897 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002898 }
2899 }
2900 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002901 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002902 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002903 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002904 }
2905 }
2906
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002907 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2908 int callingUid) {
2909 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2910 if (nri != null) {
2911 handleReleaseNetworkRequest(nri.request, callingUid);
2912 }
2913 }
2914
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002915 // Determines whether the network is the best (or could become the best, if it validated), for
2916 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2917 // on the value of reason:
2918 //
2919 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2920 // then it should be torn down.
2921 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2922 // then it should be lingered.
2923 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2924 final int numRequests;
2925 switch (reason) {
2926 case TEARDOWN:
2927 numRequests = nai.numRequestNetworkRequests();
2928 break;
2929 case LINGER:
2930 numRequests = nai.numForegroundNetworkRequests();
2931 break;
2932 default:
2933 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2934 return true;
2935 }
2936
2937 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002938 return false;
2939 }
Paul Jensene0988542015-06-25 15:30:08 -04002940 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002941 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2942 // Background requests don't affect lingering.
2943 continue;
2944 }
2945
Paul Jensene0988542015-06-25 15:30:08 -04002946 // If this Network is already the highest scoring Network for a request, or if
2947 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002948 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002949 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002950 // Note that this catches two important cases:
2951 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2952 // is currently satisfying the request. This is desirable when
2953 // cellular ends up validating but WiFi does not.
2954 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002955 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002956 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002957 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002958 nai.getCurrentScoreAsValidated())) {
2959 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002960 }
2961 }
Paul Jensene0988542015-06-25 15:30:08 -04002962 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002963 }
2964
Erik Klineacdd6392016-07-07 16:50:58 +09002965 private NetworkRequestInfo getNriForAppRequest(
2966 NetworkRequest request, int callingUid, String requestedOperation) {
2967 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2968
Robert Greenwalt9258c642014-03-26 16:47:06 -07002969 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002970 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002971 log(String.format("UID %d attempted to %s for unowned request %s",
2972 callingUid, requestedOperation, nri));
2973 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002974 }
Erik Klineacdd6392016-07-07 16:50:58 +09002975 }
2976
2977 return nri;
2978 }
2979
Erik Kline57faba92015-11-25 12:49:38 +09002980 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002981 if (mNetworkRequests.get(nri.request) == null) {
2982 return;
Erik Kline57faba92015-11-25 12:49:38 +09002983 }
Hugo Benichicd952782017-09-20 11:20:14 +09002984 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002985 return;
2986 }
2987 if (VDBG || (DBG && nri.request.isRequest())) {
2988 log("releasing " + nri.request + " (timeout)");
2989 }
2990 handleRemoveNetworkRequest(nri);
2991 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002992 }
2993
Erik Klineacdd6392016-07-07 16:50:58 +09002994 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002995 final NetworkRequestInfo nri =
2996 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2997 if (nri == null) {
2998 return;
Erik Kline57faba92015-11-25 12:49:38 +09002999 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003000 if (VDBG || (DBG && nri.request.isRequest())) {
3001 log("releasing " + nri.request + " (release request)");
3002 }
3003 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09003004 }
Erik Klineacdd6392016-07-07 16:50:58 +09003005
Hugo Benichidba33db2017-03-23 22:40:44 +09003006 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003007 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003008 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003009
Erik Klineacdd6392016-07-07 16:50:58 +09003010 synchronized (mUidToNetworkRequestCount) {
3011 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3012 if (requests < 1) {
3013 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3014 nri.mUid);
3015 } else if (requests == 1) {
3016 mUidToNetworkRequestCount.removeAt(
3017 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3018 } else {
3019 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3020 }
3021 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003022
Erik Klineacdd6392016-07-07 16:50:58 +09003023 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3024 if (nri.request.isRequest()) {
3025 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003026 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003027 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003028 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003029 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003030 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003031 log(" Removing from current network " + nai.name() +
3032 ", leaving " + nai.numNetworkRequests() + " requests.");
3033 }
3034 // If there are still lingered requests on this network, don't tear it down,
3035 // but resume lingering instead.
3036 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003037 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003038 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3039 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003040 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003041 wasKept = true;
3042 }
Hugo Benichicd952782017-09-20 11:20:14 +09003043 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003044 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3045 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003046 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003047 }
Erik Klineacdd6392016-07-07 16:50:58 +09003048 }
3049
Erik Klineacdd6392016-07-07 16:50:58 +09003050 // Maintain the illusion. When this request arrived, we might have pretended
3051 // that a network connected to serve it, even though the network was already
3052 // connected. Now that this request has gone away, we might have to pretend
3053 // that the network disconnected. LegacyTypeTracker will generate that
3054 // phantom disconnect for this type.
3055 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3056 boolean doRemove = true;
3057 if (wasKept) {
3058 // check if any of the remaining requests for this network are for the
3059 // same legacy type - if so, don't remove the nai
3060 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3061 NetworkRequest otherRequest = nai.requestAt(i);
3062 if (otherRequest.legacyType == nri.request.legacyType &&
3063 otherRequest.isRequest()) {
3064 if (DBG) log(" still have other legacy request - leaving");
3065 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003066 }
3067 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003068 }
3069
Erik Klineacdd6392016-07-07 16:50:58 +09003070 if (doRemove) {
3071 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003072 }
3073 }
Erik Klineacdd6392016-07-07 16:50:58 +09003074
3075 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3076 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3077 nri.request);
3078 }
3079 } else {
3080 // listens don't have a singular affectedNetwork. Check all networks to see
3081 // if this listen request applies and remove it.
3082 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3083 nai.removeRequest(nri.request.requestId);
3084 if (nri.request.networkCapabilities.hasSignalStrength() &&
3085 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3086 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3087 }
3088 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003089 }
3090 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003091
Lorenzo Colitti18660282016-07-04 12:55:44 +09003092 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003093 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3094 enforceConnectivityInternalPermission();
3095 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003096 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003097 }
3098
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003099 @Override
3100 public void setAvoidUnvalidated(Network network) {
3101 enforceConnectivityInternalPermission();
3102 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3103 }
3104
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003105 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3106 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3107 " accept=" + accept + " always=" + always);
3108
3109 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3110 if (nai == null) {
3111 // Nothing to do.
3112 return;
3113 }
3114
3115 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003116 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003117 return;
3118 }
3119
3120 if (!nai.networkMisc.explicitlySelected) {
3121 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3122 }
3123
3124 if (accept != nai.networkMisc.acceptUnvalidated) {
3125 int oldScore = nai.getCurrentScore();
3126 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003127 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003128 sendUpdatedScoreToFactories(nai);
3129 }
3130
3131 if (always) {
3132 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003133 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003134 }
3135
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003136 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003137 // Tell the NetworkAgent to not automatically reconnect to the network.
3138 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003139 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003140 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003141 }
3142
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003143 }
3144
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003145 private void handleSetAvoidUnvalidated(Network network) {
3146 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3147 if (nai == null || nai.lastValidated) {
3148 // Nothing to do. The network either disconnected or revalidated.
3149 return;
3150 }
3151 if (!nai.avoidUnvalidated) {
3152 int oldScore = nai.getCurrentScore();
3153 nai.avoidUnvalidated = true;
3154 rematchAllNetworksAndRequests(nai, oldScore);
3155 sendUpdatedScoreToFactories(nai);
3156 }
3157 }
3158
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003159 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003160 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003161 mHandler.sendMessageDelayed(
3162 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3163 PROMPT_UNVALIDATED_DELAY_MS);
3164 }
3165
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003166 @Override
3167 public void startCaptivePortalApp(Network network) {
3168 enforceConnectivityInternalPermission();
3169 mHandler.post(() -> {
3170 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3171 if (nai == null) return;
3172 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003173 try {
3174 nai.networkMonitor().launchCaptivePortalApp();
3175 } catch (RemoteException e) {
3176 e.rethrowFromSystemServer();
3177 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003178 });
3179 }
3180
Hugo Benichic8e9e122016-09-14 23:23:08 +00003181 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003182 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003183 }
3184
Erik Kline065ab6e2016-10-02 18:02:14 +09003185 private void rematchForAvoidBadWifiUpdate() {
3186 rematchAllNetworksAndRequests(null, 0);
3187 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3188 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3189 sendUpdatedScoreToFactories(nai);
3190 }
3191 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003192 }
3193
Erik Kline065ab6e2016-10-02 18:02:14 +09003194 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003195 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003196 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003197 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003198 if (!configRestrict) {
3199 pw.println("Bad Wi-Fi avoidance: unrestricted");
3200 return;
3201 }
3202
3203 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3204 pw.increaseIndent();
3205 pw.println("Config restrict: " + configRestrict);
3206
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003207 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003208 String description;
3209 // Can't use a switch statement because strings are legal case labels, but null is not.
3210 if ("0".equals(value)) {
3211 description = "get stuck";
3212 } else if (value == null) {
3213 description = "prompt";
3214 } else if ("1".equals(value)) {
3215 description = "avoid";
3216 } else {
3217 description = value + " (?)";
3218 }
3219 pw.println("User setting: " + description);
3220 pw.println("Network overrides:");
3221 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003222 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003223 if (nai.avoidUnvalidated) {
3224 pw.println(nai.name());
3225 }
3226 }
3227 pw.decreaseIndent();
3228 pw.decreaseIndent();
3229 }
3230
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003231 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
3232 final String action;
3233 switch (type) {
3234 case NO_INTERNET:
3235 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3236 break;
3237 case LOST_INTERNET:
3238 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3239 break;
3240 default:
3241 Slog.wtf(TAG, "Unknown notification type " + type);
3242 return;
3243 }
3244
3245 Intent intent = new Intent(action);
3246 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3247 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3248 intent.setClassName("com.android.settings",
3249 "com.android.settings.wifi.WifiNoInternetDialog");
3250
3251 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3252 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3253 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3254 }
3255
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003256 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003257 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003258 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3259
3260 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3261 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003262 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003263 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003264 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3265 return;
3266 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003267 showValidationNotification(nai, NotificationType.NO_INTERNET);
3268 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003269
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003270 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3271 NetworkCapabilities nc = nai.networkCapabilities;
3272 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003273
Erik Kline065ab6e2016-10-02 18:02:14 +09003274 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003275 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003276 showValidationNotification(nai, NotificationType.LOST_INTERNET);
3277 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003278 }
3279
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003280 @Override
3281 public int getMultipathPreference(Network network) {
3282 enforceAccessPermission();
3283
3284 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003285 if (nai != null && nai.networkCapabilities
3286 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003287 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3288 }
3289
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003290 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3291 if (networkPreference != null) {
3292 return networkPreference;
3293 }
3294
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003295 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3296 }
3297
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003298 @Override
3299 public NetworkRequest getDefaultRequest() {
3300 return mDefaultRequest;
3301 }
3302
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003303 private class InternalHandler extends Handler {
3304 public InternalHandler(Looper looper) {
3305 super(looper);
3306 }
3307
3308 @Override
3309 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003310 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003311 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003312 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003313 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003314 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003315 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003316 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003317 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003318 break;
3319 }
Jason Monkdecd2952013-10-10 14:02:51 -04003320 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003321 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003322 break;
3323 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003324 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003325 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3326 break;
3327 }
3328 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3329 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003330 break;
3331 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003332 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003333 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3334 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3335 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003336 break;
3337 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003338 case EVENT_REGISTER_NETWORK_REQUEST:
3339 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003340 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003341 break;
3342 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003343 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3344 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003345 handleRegisterNetworkRequestWithIntent(msg);
3346 break;
3347 }
Erik Kline57faba92015-11-25 12:49:38 +09003348 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3349 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3350 handleTimedOutNetworkRequest(nri);
3351 break;
3352 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003353 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3354 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3355 break;
3356 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003357 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003358 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003359 break;
3360 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003361 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003362 Network network = (Network) msg.obj;
3363 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003364 break;
3365 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003366 case EVENT_SET_AVOID_UNVALIDATED: {
3367 handleSetAvoidUnvalidated((Network) msg.obj);
3368 break;
3369 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003370 case EVENT_PROMPT_UNVALIDATED: {
3371 handlePromptUnvalidated((Network) msg.obj);
3372 break;
3373 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003374 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3375 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003376 break;
3377 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003378 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3379 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3380 mKeepaliveTracker.handleStartKeepalive(msg);
3381 break;
3382 }
3383 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3384 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3385 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3386 int slot = msg.arg1;
3387 int reason = msg.arg2;
3388 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3389 break;
3390 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003391 case EVENT_SYSTEM_READY: {
3392 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003393 // Might have been called already in handleRegisterNetworkAgent since
3394 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3395 // this several times is fine.
3396 try {
3397 nai.networkMonitor().notifySystemReady();
3398 } catch (RemoteException e) {
3399 e.rethrowFromSystemServer();
3400 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003401 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003402 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003403 break;
3404 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003405 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003406 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003407 break;
3408 }
Erik Klinea24d4592018-01-11 21:07:29 +09003409 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3410 handlePrivateDnsSettingsChanged();
3411 break;
dalyk7301aa42018-03-05 12:42:22 -05003412 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3413 handlePrivateDnsValidationUpdate(
3414 (PrivateDnsValidationUpdate) msg.obj);
3415 break;
junyulai05986c62018-08-07 19:50:45 +08003416 case EVENT_UID_RULES_CHANGED:
3417 handleUidRulesChanged(msg.arg1, msg.arg2);
3418 break;
3419 case EVENT_DATA_SAVER_CHANGED:
3420 handleRestrictBackgroundChanged(toBool(msg.arg1));
3421 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 }
3423 }
3424 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003425
3426 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003427 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003428 public int tether(String iface, String callerPkg) {
3429 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003430 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003431 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003432 } else {
3433 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3434 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003435 }
3436
3437 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003438 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003439 public int untether(String iface, String callerPkg) {
3440 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003441
3442 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003443 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003444 } else {
3445 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3446 }
3447 }
3448
3449 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003450 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003451 public int getLastTetherError(String iface) {
3452 enforceTetherAccessPermission();
3453
3454 if (isTetheringSupported()) {
3455 return mTethering.getLastTetherError(iface);
3456 } else {
3457 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3458 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003459 }
3460
3461 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003462 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003463 public String[] getTetherableUsbRegexs() {
3464 enforceTetherAccessPermission();
3465 if (isTetheringSupported()) {
3466 return mTethering.getTetherableUsbRegexs();
3467 } else {
3468 return new String[0];
3469 }
3470 }
3471
Lorenzo Colitti18660282016-07-04 12:55:44 +09003472 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003473 public String[] getTetherableWifiRegexs() {
3474 enforceTetherAccessPermission();
3475 if (isTetheringSupported()) {
3476 return mTethering.getTetherableWifiRegexs();
3477 } else {
3478 return new String[0];
3479 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003480 }
3481
Lorenzo Colitti18660282016-07-04 12:55:44 +09003482 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003483 public String[] getTetherableBluetoothRegexs() {
3484 enforceTetherAccessPermission();
3485 if (isTetheringSupported()) {
3486 return mTethering.getTetherableBluetoothRegexs();
3487 } else {
3488 return new String[0];
3489 }
3490 }
3491
Lorenzo Colitti18660282016-07-04 12:55:44 +09003492 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003493 public int setUsbTethering(boolean enable, String callerPkg) {
3494 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003495 if (isTetheringSupported()) {
3496 return mTethering.setUsbTethering(enable);
3497 } else {
3498 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3499 }
3500 }
3501
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003502 // TODO - move iface listing, queries, etc to new module
3503 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003504 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003505 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003506 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003507 return mTethering.getTetherableIfaces();
3508 }
3509
Lorenzo Colitti18660282016-07-04 12:55:44 +09003510 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003511 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003512 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003513 return mTethering.getTetheredIfaces();
3514 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003515
Lorenzo Colitti18660282016-07-04 12:55:44 +09003516 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003517 public String[] getTetheringErroredIfaces() {
3518 enforceTetherAccessPermission();
3519 return mTethering.getErroredIfaces();
3520 }
3521
Lorenzo Colitti18660282016-07-04 12:55:44 +09003522 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003523 public String[] getTetheredDhcpRanges() {
3524 enforceConnectivityInternalPermission();
3525 return mTethering.getTetheredDhcpRanges();
3526 }
3527
Udam Saini0e94c362017-06-07 12:06:28 -07003528 @Override
3529 public boolean isTetheringSupported(String callerPkg) {
3530 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3531 return isTetheringSupported();
3532 }
3533
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003534 // if ro.tether.denied = true we default to no tethering
3535 // gservices could set the secure setting to 1 though to enable it on a build where it
3536 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003537 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003538 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3539 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3540 Settings.Global.TETHER_SUPPORTED, defaultVal));
3541 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003542 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003543
3544 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3545 boolean adminUser = false;
3546 final long token = Binder.clearCallingIdentity();
3547 try {
3548 adminUser = mUserManager.isAdminUser();
3549 } finally {
3550 Binder.restoreCallingIdentity(token);
3551 }
3552
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003553 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003554 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003555
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003556 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003557 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3558 String callerPkg) {
3559 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003560 if (!isTetheringSupported()) {
3561 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3562 return;
3563 }
3564 mTethering.startTethering(type, receiver, showProvisioningUi);
3565 }
3566
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003567 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003568 public void stopTethering(int type, String callerPkg) {
3569 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003570 mTethering.stopTethering(type);
3571 }
3572
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003573 // Called when we lose the default network and have no replacement yet.
3574 // This will automatically be cleared after X seconds or a new default network
3575 // becomes CONNECTED, whichever happens first. The timer is started by the
3576 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003577 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003578 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003579 if (mNetTransitionWakeLock.isHeld()) {
3580 return;
3581 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003582 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003583 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3584 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003585 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003586 mWakelockLogs.log("ACQUIRE for " + forWhom);
3587 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3588 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003589 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003590
Hugo Benichi4c31b342017-03-30 23:18:10 +09003591 // Called when we gain a new default network to release the network transition wakelock in a
3592 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3593 // message is cancelled.
3594 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003595 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003596 if (!mNetTransitionWakeLock.isHeld()) {
3597 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003598 }
3599 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003600 // Cancel self timeout on wakelock hold.
3601 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3602 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3603 mHandler.sendMessageDelayed(msg, 1000);
3604 }
3605
3606 // Called when either message of ensureNetworkTransitionWakelock or
3607 // scheduleReleaseNetworkTransitionWakelock is processed.
3608 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3609 String event = eventName(eventId);
3610 synchronized (this) {
3611 if (!mNetTransitionWakeLock.isHeld()) {
3612 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3613 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3614 return;
3615 }
3616 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003617 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3618 mTotalWakelockDurationMs += lockDuration;
3619 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3620 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003621 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003622 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003623 }
3624
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003625 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003626 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003627 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003628 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003629 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003630 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003631 }
3632
Lorenzo Colitti18660282016-07-04 12:55:44 +09003633 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003634 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003635 enforceAccessPermission();
3636 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003637 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003638 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003639 mHandler.sendMessage(
3640 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3641 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003642
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003643 private void handleReportNetworkConnectivity(
3644 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003645 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003646 if (network == null) {
3647 nai = getDefaultNetwork();
3648 } else {
3649 nai = getNetworkAgentInfoForNetwork(network);
3650 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003651 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3652 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3653 return;
3654 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003655 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003656 if (hasConnectivity == nai.lastValidated) {
3657 return;
3658 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003659 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003660 int netid = nai.network.netId;
3661 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003662 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003663 // Validating a network that has not yet connected could result in a call to
3664 // rematchNetworkAndRequests() which is not meant to work on such networks.
3665 if (!nai.everConnected) {
3666 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003667 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003668 LinkProperties lp = getLinkProperties(nai);
3669 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3670 return;
3671 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003672 try {
3673 nai.networkMonitor().forceReevaluation(uid);
3674 } catch (RemoteException e) {
3675 e.rethrowFromSystemServer();
3676 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003677 }
3678
Lorenzo Colitti18660282016-07-04 12:55:44 +09003679 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003680 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003681 if (network == null) return mProxyTracker.getDefaultProxy();
3682 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003683 if (globalProxy != null) return globalProxy;
3684 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3685 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3686 // caller may not have.
3687 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3688 if (nai == null) return null;
3689 synchronized (nai) {
3690 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3691 if (proxyInfo == null) return null;
3692 return new ProxyInfo(proxyInfo);
3693 }
3694 }
3695
Chalard Jean3c443fc2018-06-07 18:37:59 +09003696 @Override
3697 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003698 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003699 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003700 }
3701
Chalard Jean5afbc832018-06-07 18:02:37 +09003702 @Override
3703 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003704 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003705 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003706 }
3707
Jason Monk207900c2014-04-25 15:00:09 -04003708 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003709 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003710 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003711 proxy = null;
3712 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003713 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003714 }
3715
Paul Jensene0bef712014-12-10 15:12:18 -05003716 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3717 // This method gets called when any network changes proxy, but the broadcast only ever contains
3718 // the default proxy (even if it hasn't changed).
3719 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3720 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003721 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003722 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3723 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3724
Chalard Jean4949dd72018-06-07 17:41:29 +09003725 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09003726 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05003727 }
3728 }
3729
Robert Greenwalt434203a2010-10-11 16:00:27 -07003730 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003731 final private HashMap<Uri, Integer> mUriEventMap;
3732 final private Context mContext;
3733 final private Handler mHandler;
3734
3735 SettingsObserver(Context context, Handler handler) {
3736 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003737 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003738 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003739 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003740 }
3741
Erik Klineda4bfa82015-04-30 12:58:40 +09003742 void observe(Uri uri, int what) {
3743 mUriEventMap.put(uri, what);
3744 final ContentResolver resolver = mContext.getContentResolver();
3745 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003746 }
3747
3748 @Override
3749 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003750 Slog.wtf(TAG, "Should never be reached.");
3751 }
3752
3753 @Override
3754 public void onChange(boolean selfChange, Uri uri) {
3755 final Integer what = mUriEventMap.get(uri);
3756 if (what != null) {
3757 mHandler.obtainMessage(what.intValue()).sendToTarget();
3758 } else {
3759 loge("No matching event to send for URI=" + uri);
3760 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003761 }
3762 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003763
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003764 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003765 Slog.d(TAG, s);
3766 }
3767
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003768 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003769 Slog.e(TAG, s);
3770 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003771
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003772 private static void loge(String s, Throwable t) {
3773 Slog.e(TAG, s, t);
3774 }
3775
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003776 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003777 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003778 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3779 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3780 *
3781 * @param oldPackage Package name of the application which currently controls VPN, which will
3782 * be replaced. If there is no such application, this should should either be
3783 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3784 * @param newPackage Package name of the application which should gain control of VPN, or
3785 * {@code null} to disable.
3786 * @param userId User for whom to prepare the new VPN.
3787 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003788 * @hide
3789 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003790 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003791 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3792 int userId) {
3793 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003794
Hugo Benichi20035e02017-04-26 14:53:28 +09003795 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003796 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003797 Vpn vpn = mVpns.get(userId);
3798 if (vpn != null) {
3799 return vpn.prepare(oldPackage, newPackage);
3800 } else {
3801 return false;
3802 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003803 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003804 }
3805
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003806 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003807 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3808 * This method is used by system-privileged apps.
3809 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3810 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3811 *
3812 * @param packageName The package for which authorization state should change.
3813 * @param userId User for whom {@code packageName} is installed.
3814 * @param authorized {@code true} if this app should be able to start a VPN connection without
3815 * explicit user approval, {@code false} if not.
3816 *
Jeff Davidson05542602014-08-11 14:07:27 -07003817 * @hide
3818 */
3819 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003820 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3821 enforceCrossUserPermission(userId);
3822
Hugo Benichi20035e02017-04-26 14:53:28 +09003823 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003824 Vpn vpn = mVpns.get(userId);
3825 if (vpn != null) {
3826 vpn.setPackageAuthorization(packageName, authorized);
3827 }
Jeff Davidson05542602014-08-11 14:07:27 -07003828 }
3829 }
3830
3831 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003832 * Configure a TUN interface and return its file descriptor. Parameters
3833 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003834 * and not available in ConnectivityManager. Permissions are checked in
3835 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003836 * @hide
3837 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003838 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003839 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003840 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003841 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003842 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003843 return mVpns.get(user).establish(config);
3844 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003845 }
3846
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003847 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003848 * Start legacy VPN, controlling native daemons as needed. Creates a
3849 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003850 */
3851 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003852 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003853 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003854 final LinkProperties egress = getActiveLinkProperties();
3855 if (egress == null) {
3856 throw new IllegalStateException("Missing active network connection");
3857 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003858 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003859 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003860 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3861 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003862 }
3863
3864 /**
3865 * Return the information of the ongoing legacy VPN. This method is used
3866 * by VpnSettings and not available in ConnectivityManager. Permissions
3867 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003868 */
3869 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003870 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3871 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003872
Hugo Benichi20035e02017-04-26 14:53:28 +09003873 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003874 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003875 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003876 }
3877
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003878 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003879 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3880 * and not available in ConnectivityManager.
3881 */
3882 @Override
3883 public VpnInfo[] getAllVpnInfo() {
3884 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003885 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003886 if (mLockdownEnabled) {
3887 return new VpnInfo[0];
3888 }
3889
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003890 List<VpnInfo> infoList = new ArrayList<>();
3891 for (int i = 0; i < mVpns.size(); i++) {
3892 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3893 if (info != null) {
3894 infoList.add(info);
3895 }
3896 }
3897 return infoList.toArray(new VpnInfo[infoList.size()]);
3898 }
3899 }
3900
3901 /**
3902 * @return VPN information for accounting, or null if we can't retrieve all required
3903 * information, e.g primary underlying iface.
3904 */
3905 @Nullable
3906 private VpnInfo createVpnInfo(Vpn vpn) {
3907 VpnInfo info = vpn.getVpnInfo();
3908 if (info == null) {
3909 return null;
3910 }
3911 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3912 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3913 // the underlyingNetworks list.
3914 if (underlyingNetworks == null) {
3915 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3916 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3917 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3918 }
3919 } else if (underlyingNetworks.length > 0) {
3920 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3921 if (linkProperties != null) {
3922 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3923 }
3924 }
3925 return info.primaryUnderlyingIface == null ? null : info;
3926 }
3927
3928 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003929 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3930 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003931 * Permissions are checked in Vpn class.
3932 * @hide
3933 */
3934 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003935 public VpnConfig getVpnConfig(int userId) {
3936 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003937 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003938 Vpn vpn = mVpns.get(userId);
3939 if (vpn != null) {
3940 return vpn.getVpnConfig();
3941 } else {
3942 return null;
3943 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003944 }
3945 }
3946
Chalard Jean6b65ec72018-05-18 22:02:56 +09003947 /**
3948 * Ask all VPN objects to recompute and update their capabilities.
3949 *
3950 * When underlying networks change, VPNs may have to update capabilities to reflect things
3951 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3952 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3953 * handler thread through their agent, this is asynchronous. When the capabilities objects
3954 * are computed they will be up-to-date as they are computed synchronously from here and
3955 * this is running on the ConnectivityService thread.
3956 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3957 */
3958 private void updateAllVpnsCapabilities() {
3959 synchronized (mVpns) {
3960 for (int i = 0; i < mVpns.size(); i++) {
3961 final Vpn vpn = mVpns.valueAt(i);
3962 vpn.updateCapabilities();
3963 }
3964 }
3965 }
3966
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003967 @Override
3968 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003969 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3970 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3971 return false;
3972 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003973
Hugo Benichi69744342017-11-27 10:57:16 +09003974 synchronized (mVpns) {
3975 // Tear down existing lockdown if profile was removed
3976 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3977 if (mLockdownEnabled) {
3978 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3979 if (profileTag == null) {
3980 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3981 return false;
3982 }
3983 String profileName = new String(profileTag);
3984 final VpnProfile profile = VpnProfile.decode(
3985 profileName, mKeyStore.get(Credentials.VPN + profileName));
3986 if (profile == null) {
3987 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3988 setLockdownTracker(null);
3989 return true;
3990 }
3991 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003992 Vpn vpn = mVpns.get(user);
3993 if (vpn == null) {
3994 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3995 return false;
3996 }
Luke Huang4e25ec62018-09-27 16:58:23 +08003997 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003998 } else {
3999 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004000 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004001 }
4002
4003 return true;
4004 }
4005
4006 /**
4007 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4008 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4009 */
Hugo Benichi69744342017-11-27 10:57:16 +09004010 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004011 private void setLockdownTracker(LockdownVpnTracker tracker) {
4012 // Shutdown any existing tracker
4013 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004014 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4015 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004016 mLockdownTracker = null;
4017 if (existing != null) {
4018 existing.shutdown();
4019 }
4020
Robin Leec3736bc2017-03-10 16:19:54 +00004021 if (tracker != null) {
4022 mLockdownTracker = tracker;
4023 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004024 }
4025 }
4026
Hugo Benichi69744342017-11-27 10:57:16 +09004027 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004028 private void throwIfLockdownEnabled() {
4029 if (mLockdownEnabled) {
4030 throw new IllegalStateException("Unavailable in lockdown mode");
4031 }
4032 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004033
Robin Lee244ce8e2016-01-05 18:03:46 +00004034 /**
Robin Lee17e61832016-05-09 13:46:28 +01004035 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4036 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004037 *
Robin Lee17e61832016-05-09 13:46:28 +01004038 * @return {@code true} if the service was started, the service was already connected, or there
4039 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004040 */
Robin Lee17e61832016-05-09 13:46:28 +01004041 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004042 synchronized (mVpns) {
4043 Vpn vpn = mVpns.get(userId);
4044 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004045 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004046 // exists already.
4047 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4048 return false;
4049 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004050
Robin Lee812800c2016-05-13 15:38:08 +01004051 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004052 }
4053 }
4054
4055 @Override
Charles He36738632017-05-15 17:07:18 +01004056 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4057 enforceSettingsPermission();
4058 enforceCrossUserPermission(userId);
4059
4060 synchronized (mVpns) {
4061 Vpn vpn = mVpns.get(userId);
4062 if (vpn == null) {
4063 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4064 return false;
4065 }
4066 return vpn.isAlwaysOnPackageSupported(packageName);
4067 }
4068 }
4069
4070 @Override
Robin Leedc679712016-05-03 13:23:03 +01004071 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004072 enforceConnectivityInternalPermission();
4073 enforceCrossUserPermission(userId);
4074
Robin Lee244ce8e2016-01-05 18:03:46 +00004075 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004076 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4077 if (LockdownVpnTracker.isEnabled()) {
4078 return false;
4079 }
4080
Robin Lee244ce8e2016-01-05 18:03:46 +00004081 Vpn vpn = mVpns.get(userId);
4082 if (vpn == null) {
4083 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4084 return false;
4085 }
Robin Lee17e61832016-05-09 13:46:28 +01004086 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004087 return false;
4088 }
Robin Lee17e61832016-05-09 13:46:28 +01004089 if (!startAlwaysOnVpn(userId)) {
4090 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00004091 return false;
4092 }
4093 }
4094 return true;
4095 }
4096
4097 @Override
4098 public String getAlwaysOnVpnPackage(int userId) {
4099 enforceConnectivityInternalPermission();
4100 enforceCrossUserPermission(userId);
4101
4102 synchronized (mVpns) {
4103 Vpn vpn = mVpns.get(userId);
4104 if (vpn == null) {
4105 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4106 return null;
4107 }
4108 return vpn.getAlwaysOnPackage();
4109 }
4110 }
4111
Wink Savilleab9321d2013-06-29 21:10:57 -07004112 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004113 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004114 // TODO: Remove? Any reason to trigger a provisioning check?
4115 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004116 }
4117
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004118 /** Location to an updatable file listing carrier provisioning urls.
4119 * An example:
4120 *
4121 * <?xml version="1.0" encoding="utf-8"?>
4122 * <provisioningUrls>
4123 * <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 -07004124 * </provisioningUrls>
4125 */
4126 private static final String PROVISIONING_URL_PATH =
4127 "/data/misc/radio/provisioning_urls.xml";
4128 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004129
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004130 /** XML tag for root element. */
4131 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4132 /** XML tag for individual url */
4133 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004134 /** XML attribute for mcc */
4135 private static final String ATTR_MCC = "mcc";
4136 /** XML attribute for mnc */
4137 private static final String ATTR_MNC = "mnc";
4138
Paul Jensen434dde82015-06-11 09:43:30 -04004139 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004140 FileReader fileReader = null;
4141 XmlPullParser parser = null;
4142 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004143
4144 try {
4145 fileReader = new FileReader(mProvisioningUrlFile);
4146 parser = Xml.newPullParser();
4147 parser.setInput(fileReader);
4148 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4149
4150 while (true) {
4151 XmlUtils.nextElement(parser);
4152
4153 String element = parser.getName();
4154 if (element == null) break;
4155
Paul Jensen434dde82015-06-11 09:43:30 -04004156 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004157 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4158 try {
4159 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4160 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4161 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4162 parser.next();
4163 if (parser.getEventType() == XmlPullParser.TEXT) {
4164 return parser.getText();
4165 }
4166 }
4167 }
4168 } catch (NumberFormatException e) {
4169 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4170 }
4171 }
4172 }
4173 return null;
4174 } catch (FileNotFoundException e) {
4175 loge("Carrier Provisioning Urls file not found");
4176 } catch (XmlPullParserException e) {
4177 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4178 } catch (IOException e) {
4179 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4180 } finally {
4181 if (fileReader != null) {
4182 try {
4183 fileReader.close();
4184 } catch (IOException e) {}
4185 }
4186 }
4187 return null;
4188 }
4189
Wink Saville42d4f082013-07-20 20:31:59 -07004190 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004191 public String getMobileProvisioningUrl() {
4192 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004193 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004194 if (TextUtils.isEmpty(url)) {
4195 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004196 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004197 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004198 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004199 }
Wink Saville8cf35602013-07-10 23:00:07 -07004200 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004201 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004202 String phoneNumber = mTelephonyManager.getLine1Number();
4203 if (TextUtils.isEmpty(phoneNumber)) {
4204 phoneNumber = "0000000000";
4205 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004206 url = String.format(url,
4207 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4208 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004209 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004210 }
4211
Wink Savilleab9321d2013-06-29 21:10:57 -07004212 return url;
4213 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004214
Wink Saville948282b2013-08-29 08:55:16 -07004215 @Override
4216 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004217 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004218 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004219 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4220 return;
4221 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004222 final long ident = Binder.clearCallingIdentity();
4223 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004224 // Concatenate the range of types onto the range of NetIDs.
4225 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4226 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004227 } finally {
4228 Binder.restoreCallingIdentity(ident);
4229 }
Wink Saville948282b2013-08-29 08:55:16 -07004230 }
Wink Saville7788c612013-08-29 14:57:08 -07004231
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004232 @Override
4233 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004234 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004235 final long ident = Binder.clearCallingIdentity();
4236 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004237 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004238 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004239 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4240 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004241 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004242 } finally {
4243 Binder.restoreCallingIdentity(ident);
4244 }
4245 }
4246
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004247 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004248 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004249 Vpn userVpn = mVpns.get(userId);
4250 if (userVpn != null) {
4251 loge("Starting user already has a VPN");
4252 return;
4253 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004254 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004255 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004256 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4257 updateLockdownVpn();
4258 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004259 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004260 }
4261
4262 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004263 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004264 Vpn userVpn = mVpns.get(userId);
4265 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004266 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004267 return;
4268 }
Robin Lee17e61832016-05-09 13:46:28 +01004269 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004270 mVpns.delete(userId);
4271 }
4272 }
4273
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004274 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004275 mPermissionMonitor.onUserAdded(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004276 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004277 final int vpnsSize = mVpns.size();
4278 for (int i = 0; i < vpnsSize; i++) {
4279 Vpn vpn = mVpns.valueAt(i);
4280 vpn.onUserAdded(userId);
4281 }
4282 }
4283 }
4284
4285 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004286 mPermissionMonitor.onUserRemoved(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004287 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004288 final int vpnsSize = mVpns.size();
4289 for (int i = 0; i < vpnsSize; i++) {
4290 Vpn vpn = mVpns.valueAt(i);
4291 vpn.onUserRemoved(userId);
4292 }
4293 }
4294 }
4295
junyulai2454b692018-11-01 17:16:31 +08004296 private void onPackageAdded(String packageName, int uid) {
4297 if (TextUtils.isEmpty(packageName) || uid < 0) {
4298 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4299 return;
4300 }
4301 mPermissionMonitor.onPackageAdded(packageName, uid);
4302 }
4303
junyulaiefb04d32018-11-12 22:39:30 +08004304 private void onPackageReplaced(String packageName, int uid) {
4305 if (TextUtils.isEmpty(packageName) || uid < 0) {
4306 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4307 return;
4308 }
4309 final int userId = UserHandle.getUserId(uid);
4310 synchronized (mVpns) {
4311 final Vpn vpn = mVpns.get(userId);
4312 if (vpn == null) {
4313 return;
4314 }
4315 // Legacy always-on VPN won't be affected since the package name is not set.
4316 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4317 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4318 + userId);
4319 vpn.startAlwaysOnVpn();
4320 }
4321 }
4322 }
4323
4324 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004325 if (TextUtils.isEmpty(packageName) || uid < 0) {
4326 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4327 return;
4328 }
4329 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004330
4331 final int userId = UserHandle.getUserId(uid);
4332 synchronized (mVpns) {
4333 final Vpn vpn = mVpns.get(userId);
4334 if (vpn == null) {
4335 return;
4336 }
4337 // Legacy always-on VPN won't be affected since the package name is not set.
4338 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4339 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4340 + userId);
4341 vpn.setAlwaysOnPackage(null, false);
4342 }
4343 }
junyulai2454b692018-11-01 17:16:31 +08004344 }
4345
Robin Lee89e7a692016-02-29 14:38:17 +00004346 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004347 synchronized (mVpns) {
4348 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4349 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4350 updateLockdownVpn();
4351 } else {
4352 startAlwaysOnVpn(userId);
4353 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004354 }
4355 }
4356
junyulai2454b692018-11-01 17:16:31 +08004357 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004358 @Override
4359 public void onReceive(Context context, Intent intent) {
4360 final String action = intent.getAction();
4361 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004362 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4363 final Uri packageData = intent.getData();
4364 final String packageName =
4365 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004366 if (userId == UserHandle.USER_NULL) return;
4367
Robin Lee323f29d2016-05-04 16:38:06 +01004368 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004369 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004370 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004371 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004372 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4373 onUserAdded(userId);
4374 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4375 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004376 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4377 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004378 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4379 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004380 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4381 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004382 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004383 final boolean isReplacing = intent.getBooleanExtra(
4384 Intent.EXTRA_REPLACING, false);
4385 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004386 }
4387 }
4388 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004389
Robin Lee95204e02017-01-27 11:59:22 +00004390 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4391 @Override
4392 public void onReceive(Context context, Intent intent) {
4393 // Try creating lockdown tracker, since user present usually means
4394 // unlocked keystore.
4395 updateLockdownVpn();
4396 mContext.unregisterReceiver(this);
4397 }
4398 };
4399
Chalard Jean4133a122018-06-04 13:33:12 +09004400 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4401 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004402
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004403 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4404 // Map from UID to number of NetworkRequests that UID has filed.
4405 @GuardedBy("mUidToNetworkRequestCount")
4406 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4407
Robert Greenwalta67be032014-05-16 15:49:14 -07004408 private static class NetworkFactoryInfo {
4409 public final String name;
4410 public final Messenger messenger;
4411 public final AsyncChannel asyncChannel;
4412
4413 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4414 this.name = name;
4415 this.messenger = messenger;
4416 this.asyncChannel = asyncChannel;
4417 }
4418 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004419
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004420 private void ensureNetworkRequestHasType(NetworkRequest request) {
4421 if (request.type == NetworkRequest.Type.NONE) {
4422 throw new IllegalArgumentException(
4423 "All NetworkRequests in ConnectivityService must have a type");
4424 }
4425 }
4426
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004427 /**
4428 * Tracks info about the requester.
4429 * Also used to notice when the calling process dies so we can self-expire
4430 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004432 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004433 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004434 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004435 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004436 final int mPid;
4437 final int mUid;
4438 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004439
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004440 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004441 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004442 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004443 mPendingIntent = pi;
4444 messenger = null;
4445 mBinder = null;
4446 mPid = getCallingPid();
4447 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004448 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004449 }
4450
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004451 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004452 super();
4453 messenger = m;
4454 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004455 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004456 mBinder = binder;
4457 mPid = getCallingPid();
4458 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004459 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004460 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004461
4462 try {
4463 mBinder.linkToDeath(this, 0);
4464 } catch (RemoteException e) {
4465 binderDied();
4466 }
4467 }
4468
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004469 private void enforceRequestCountLimit() {
4470 synchronized (mUidToNetworkRequestCount) {
4471 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4472 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004473 throw new ServiceSpecificException(
4474 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004475 }
4476 mUidToNetworkRequestCount.put(mUid, networkRequests);
4477 }
4478 }
4479
Robert Greenwalt9258c642014-03-26 16:47:06 -07004480 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004481 if (mBinder != null) {
4482 mBinder.unlinkToDeath(this, 0);
4483 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004484 }
4485
4486 public void binderDied() {
4487 log("ConnectivityService NetworkRequestInfo binderDied(" +
4488 request + ", " + mBinder + ")");
4489 releaseNetworkRequest(request);
4490 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004491
4492 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004493 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004494 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004495 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004496 }
4497
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004498 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4499 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4500 if (badCapability != null) {
4501 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004502 }
4503 }
4504
Chalard Jeanb03a6222018-04-11 21:09:10 +09004505 // This checks that the passed capabilities either do not request a specific SSID, or the
4506 // calling app has permission to do so.
4507 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4508 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004509 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004510 throw new SecurityException("Insufficient permissions to request a specific SSID");
4511 }
4512 }
4513
Erik Kline9d598e12015-07-13 16:37:51 +09004514 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004515 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004516 synchronized (nai) {
4517 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4518 if (nri.request.networkCapabilities.hasSignalStrength() &&
4519 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4520 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4521 }
4522 }
4523 }
Chalard Jean4133a122018-06-04 13:33:12 +09004524 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004525 }
4526
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004527 private void updateSignalStrengthThresholds(
4528 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4529 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004530 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004531 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4532
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004533 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004534 String detail;
4535 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4536 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4537 } else {
4538 detail = reason;
4539 }
4540 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4541 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4542 }
4543
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004544 nai.asyncChannel.sendMessage(
4545 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004546 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004547 }
4548
Etan Cohen859748f2017-04-03 17:42:34 -07004549 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4550 if (nc == null) {
4551 return;
4552 }
4553 NetworkSpecifier ns = nc.getNetworkSpecifier();
4554 if (ns == null) {
4555 return;
4556 }
4557 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4558 ns.assertValidFromUid(Binder.getCallingUid());
4559 }
4560
Robert Greenwalt9258c642014-03-26 16:47:06 -07004561 @Override
4562 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004563 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004564 final NetworkRequest.Type type = (networkCapabilities == null)
4565 ? NetworkRequest.Type.TRACK_DEFAULT
4566 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004567 // If the requested networkCapabilities is null, take them instead from
4568 // the default network request. This allows callers to keep track of
4569 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004570 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004571 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004572 enforceAccessPermission();
4573 } else {
4574 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4575 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004576 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4577 // of the app when the request is filed, but we never change the request if the app
4578 // changes network state. http://b/29964605
4579 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004580 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004581 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004582 ensureSufficientPermissionsForRequest(networkCapabilities,
4583 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004584 // Set the UID range for this request to the single UID of the requester, or to an empty
4585 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004586 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4587 // are no visible methods to set the UIDs, an app could use reflection to try and get
4588 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004589 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004590
Etan Cohenba07c8c2017-02-05 10:42:27 -08004591 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004592 throw new IllegalArgumentException("Bad timeout specified");
4593 }
Etan Cohen859748f2017-04-03 17:42:34 -07004594 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004595
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004596 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004597 nextNetworkRequestId(), type);
4598 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004599 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004600
4601 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004602 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004603 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004604 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004605 }
4606 return networkRequest;
4607 }
4608
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004609 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004610 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004611 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004612 } else {
4613 enforceChangePermission();
4614 }
4615 }
4616
fenglub15e72b2015-03-20 11:29:56 -07004617 @Override
fengludb571472015-04-21 17:12:05 -07004618 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004619 enforceAccessPermission();
4620 NetworkAgentInfo nai = null;
4621 if (network == null) {
4622 return false;
4623 }
4624 synchronized (mNetworkForNetId) {
4625 nai = mNetworkForNetId.get(network.netId);
4626 }
4627 if (nai != null) {
4628 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004629 synchronized (mBandwidthRequests) {
4630 final int uid = Binder.getCallingUid();
4631 Integer uidReqs = mBandwidthRequests.get(uid);
4632 if (uidReqs == null) {
4633 uidReqs = new Integer(0);
4634 }
4635 mBandwidthRequests.put(uid, ++uidReqs);
4636 }
fenglub15e72b2015-03-20 11:29:56 -07004637 return true;
4638 }
4639 return false;
4640 }
4641
Felipe Lemeee27cab2016-06-20 16:36:29 -07004642 private boolean isSystem(int uid) {
4643 return uid < Process.FIRST_APPLICATION_UID;
4644 }
fenglub15e72b2015-03-20 11:29:56 -07004645
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004646 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004647 final int uid = Binder.getCallingUid();
4648 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004649 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004650 return;
4651 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004652 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4653 // Policy already enforced.
4654 return;
4655 }
4656 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4657 // If UID is restricted, don't allow them to bring up metered APNs.
4658 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004659 }
4660 }
4661
Robert Greenwalt9258c642014-03-26 16:47:06 -07004662 @Override
4663 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4664 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004665 checkNotNull(operation, "PendingIntent cannot be null.");
4666 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4667 enforceNetworkRequestPermissions(networkCapabilities);
4668 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004669 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004670 ensureSufficientPermissionsForRequest(networkCapabilities,
4671 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004672 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004673 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004674
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004675 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004676 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4677 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004678 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004679 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4680 nri));
4681 return networkRequest;
4682 }
4683
Jeremy Joslin79294842014-12-03 17:15:28 -08004684 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4685 mHandler.sendMessageDelayed(
4686 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4687 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4688 }
4689
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004690 @Override
4691 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004692 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004693 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4694 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004695 }
4696
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004697 // In order to implement the compatibility measure for pre-M apps that call
4698 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4699 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4700 // This ensures it has permission to do so.
4701 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4702 if (nc == null) {
4703 return false;
4704 }
4705 int[] transportTypes = nc.getTransportTypes();
4706 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4707 return false;
4708 }
4709 try {
4710 mContext.enforceCallingOrSelfPermission(
4711 android.Manifest.permission.ACCESS_WIFI_STATE,
4712 "ConnectivityService");
4713 } catch (SecurityException e) {
4714 return false;
4715 }
4716 return true;
4717 }
4718
Robert Greenwalt9258c642014-03-26 16:47:06 -07004719 @Override
4720 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4721 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004722 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4723 enforceAccessPermission();
4724 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004725
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004726 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004727 ensureSufficientPermissionsForRequest(networkCapabilities,
4728 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004729 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004730 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4731 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4732 // onLost and onAvailable callbacks when networks move in and out of the background.
4733 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4734 // can't request networks.
4735 restrictBackgroundRequestForCaller(nc);
4736 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004737
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004738 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004739 NetworkRequest.Type.LISTEN);
4740 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004741 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004742
4743 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4744 return networkRequest;
4745 }
4746
4747 @Override
4748 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4749 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004750 checkNotNull(operation, "PendingIntent cannot be null.");
4751 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4752 enforceAccessPermission();
4753 }
Etan Cohen859748f2017-04-03 17:42:34 -07004754 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004755 ensureSufficientPermissionsForRequest(networkCapabilities,
4756 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004757
Chalard Jeandda156a2018-01-10 21:19:32 +09004758 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004759 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004760
4761 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004762 NetworkRequest.Type.LISTEN);
4763 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004764 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004765
4766 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004767 }
4768
Erik Klineacdd6392016-07-07 16:50:58 +09004769 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004770 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004771 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004772 mHandler.sendMessage(mHandler.obtainMessage(
4773 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004774 }
4775
4776 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004777 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004778 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004779 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4780 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004781 }
4782
Robert Greenwalta67be032014-05-16 15:49:14 -07004783 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004784 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004785 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4786 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4787 }
4788
4789 @Override
4790 public void unregisterNetworkFactory(Messenger messenger) {
4791 enforceConnectivityInternalPermission();
4792 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4793 }
4794
4795 private void handleUnregisterNetworkFactory(Messenger messenger) {
4796 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4797 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004798 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004799 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004800 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004801 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004802 }
4803
Robert Greenwalt7b816022014-04-18 15:25:25 -07004804 /**
4805 * NetworkAgentInfo supporting a request by requestId.
4806 * These have already been vetted (their Capabilities satisfy the request)
4807 * and the are the highest scored network available.
4808 * the are keyed off the Requests requestId.
4809 */
Hugo Benichicd952782017-09-20 11:20:14 +09004810 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4811 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004812 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004813
Paul Jensen31a94f42015-02-13 14:18:39 -05004814 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4815 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004816 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004817 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4818 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4819 // there may not be a strict 1:1 correlation between the two.
4820 @GuardedBy("mNetworkForNetId")
4821 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004822
Robert Greenwalt7b816022014-04-18 15:25:25 -07004823 // NetworkAgentInfo keyed off its connecting messenger
4824 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004825 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004826 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004827
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004828 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004829 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004830
Paul Jensen2c311d62014-11-17 12:34:51 -05004831 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004832 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004833
Erik Klineda4bfa82015-04-30 12:58:40 +09004834 // Request used to optionally keep mobile data active even when higher
4835 // priority networks like Wi-Fi are active.
4836 private final NetworkRequest mDefaultMobileDataRequest;
4837
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004838 // Request used to optionally keep wifi data active even when higher
4839 // priority networks like ethernet are active.
4840 private final NetworkRequest mDefaultWifiRequest;
4841
Hugo Benichicd952782017-09-20 11:20:14 +09004842 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4843 synchronized (mNetworkForRequestId) {
4844 return mNetworkForRequestId.get(requestId);
4845 }
4846 }
4847
4848 private void clearNetworkForRequest(int requestId) {
4849 synchronized (mNetworkForRequestId) {
4850 mNetworkForRequestId.remove(requestId);
4851 }
4852 }
4853
4854 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4855 synchronized (mNetworkForRequestId) {
4856 mNetworkForRequestId.put(requestId, nai);
4857 }
4858 }
4859
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004860 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004861 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004862 }
4863
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004864 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004865 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004866 }
4867
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004868 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4869 return nri.request.requestId == mDefaultRequest.requestId;
4870 }
4871
Paul Jensen31a94f42015-02-13 14:18:39 -05004872 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004873 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004874 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004875 enforceConnectivityInternalPermission();
4876
Rubin Xu1bb5c082017-09-05 18:40:49 +01004877 LinkProperties lp = new LinkProperties(linkProperties);
4878 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004879 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4880 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004881 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004882 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004883 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Lorenzo Colitti9307ca22019-01-12 01:54:23 +09004884 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004885 // Make sure the network capabilities reflect what the agent info says.
4886 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09004887 final String extraInfo = networkInfo.getExtraInfo();
4888 final String name = TextUtils.isEmpty(extraInfo)
4889 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004890 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004891 final long token = Binder.clearCallingIdentity();
4892 try {
4893 mContext.getSystemService(NetworkStack.class)
4894 .makeNetworkMonitor(nai.network, name, new NetworkMonitorCallbacks(nai));
4895 } finally {
4896 Binder.restoreCallingIdentity(token);
4897 }
4898 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
4899 // If the network disconnects or sends any other event before that, messages are deferred by
4900 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
4901 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05004902 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004903 }
4904
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004905 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
4906 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004907 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004908 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004909 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004910 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004911 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004912 synchronized (this) {
4913 if (mSystemReady) {
4914 try {
4915 networkMonitor.notifySystemReady();
4916 } catch (RemoteException e) {
4917 e.rethrowFromSystemServer();
4918 }
4919 }
4920 }
4921
4922 try {
4923 networkMonitor.start();
4924 } catch (RemoteException e) {
4925 e.rethrowFromSystemServer();
4926 }
Erik Klinee5dac902018-03-04 21:01:01 +09004927 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4928 NetworkInfo networkInfo = nai.networkInfo;
4929 nai.networkInfo = null;
4930 updateNetworkInfo(nai, networkInfo);
4931 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004932 }
4933
lucaslin25a4ec32018-11-28 12:51:55 +08004934 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
4935 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004936 int netId = networkAgent.network.netId;
4937
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004938 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4939 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004940 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004941 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004942 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004943
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004944 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004945 updateMtu(newLp, oldLp);
4946 // TODO - figure out what to do for clat
4947// for (LinkProperties lp : newLp.getStackedLinks()) {
4948// updateMtu(lp, null);
4949// }
lucaslin041a1af2018-11-28 19:27:52 +08004950 if (isDefaultNetwork(networkAgent)) {
4951 updateTcpBufferSizes(newLp.getTcpBufferSizes());
4952 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004953
Erik Kline94887872016-04-05 13:30:49 +09004954 updateRoutes(newLp, oldLp, netId);
4955 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004956 // Make sure LinkProperties represents the latest private DNS status.
4957 // This does not need to be done before updateDnses because the
4958 // LinkProperties are not the source of the private DNS configuration.
4959 // updateDnses will fetch the private DNS configuration from DnsManager.
4960 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004961
Paul Jensene0bef712014-12-10 15:12:18 -05004962 if (isDefaultNetwork(networkAgent)) {
4963 handleApplyDefaultProxy(newLp.getHttpProxy());
4964 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004965 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004966 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004967 // TODO - move this check to cover the whole function
4968 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004969 synchronized (networkAgent) {
4970 networkAgent.linkProperties = newLp;
4971 }
lucaslin25a4ec32018-11-28 12:51:55 +08004972 // Start or stop clat accordingly to network state.
4973 networkAgent.updateClat(mNMS);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004974 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08004975 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004976 try {
4977 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
4978 } catch (RemoteException e) {
4979 e.rethrowFromSystemServer();
4980 }
lucaslin25a4ec32018-11-28 12:51:55 +08004981 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4982 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004983 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004984
4985 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004986 }
4987
Joel Scherpelz668370b2017-06-08 15:35:21 +09004988 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09004989 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004990 // marks on unsupported interfaces is harmless.
4991 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4992 return;
4993 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004994
Joel Scherpelz668370b2017-06-08 15:35:21 +09004995 int mark = mContext.getResources().getInteger(
4996 com.android.internal.R.integer.config_networkWakeupPacketMark);
4997 int mask = mContext.getResources().getInteger(
4998 com.android.internal.R.integer.config_networkWakeupPacketMask);
4999
5000 // Mask/mark of zero will not detect anything interesting.
5001 // Don't install rules unless both values are nonzero.
5002 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005003 return;
5004 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005005
5006 final String prefix = "iface:" + iface;
5007 try {
5008 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005009 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005010 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005011 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005012 }
5013 } catch (Exception e) {
5014 loge("Exception modifying wakeup packet monitoring: " + e);
5015 }
5016
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005017 }
5018
5019 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5020 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005021 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005022 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5023 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005024 for (String iface : interfaceDiff.added) {
5025 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005026 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005027 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005028 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005029 } catch (Exception e) {
5030 loge("Exception adding interface: " + e);
5031 }
5032 }
5033 for (String iface : interfaceDiff.removed) {
5034 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005035 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005036 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005037 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005038 } catch (Exception e) {
5039 loge("Exception removing interface: " + e);
5040 }
5041 }
5042 }
5043
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005044 /**
5045 * Have netd update routes from oldLp to newLp.
5046 * @return true if routes changed between oldLp and newLp
5047 */
5048 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005049 // Compare the route diff to determine which routes should be added and removed.
5050 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5051 oldLp != null ? oldLp.getAllRoutes() : null,
5052 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005053
5054 // add routes before removing old in case it helps with continuous connectivity
5055
Chalard Jean4d660112018-06-04 16:52:49 +09005056 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005057 for (RouteInfo route : routeDiff.added) {
5058 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005059 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005060 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005061 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005062 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005063 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5064 loge("Exception in addRoute for non-gateway: " + e);
5065 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005066 }
5067 }
5068 for (RouteInfo route : routeDiff.added) {
5069 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005070 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005071 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005072 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005073 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005074 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5075 loge("Exception in addRoute for gateway: " + e);
5076 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005077 }
5078 }
5079
5080 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005081 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005082 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005083 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005084 } catch (Exception e) {
5085 loge("Exception in removeRoute: " + e);
5086 }
5087 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005088 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005089 }
Erik Kline41368502015-06-17 13:19:54 +09005090
Erik Kline94887872016-04-05 13:30:49 +09005091 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5092 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5093 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005094 }
Erik Kline94887872016-04-05 13:30:49 +09005095
Erik Kline1742fe12017-12-13 19:40:49 +09005096 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5097 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5098
Erik Klinea24d4592018-01-11 21:07:29 +09005099 if (DBG) {
5100 final Collection<InetAddress> dnses = newLp.getDnsServers();
5101 log("Setting DNS servers for network " + netId + " to " + dnses);
5102 }
Erik Kline94887872016-04-05 13:30:49 +09005103 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005104 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005105 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005106 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005107 }
Erik Kline4edba012017-04-07 15:29:29 +09005108 }
5109
Luke Huang8a462ec2018-08-24 20:33:16 +08005110 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005111 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005112 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005113 }
5114 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005115 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005116 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005117 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005118 }
5119
Paul Jensen3d194ea2015-06-16 14:27:36 -04005120 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005121 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5122 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5123 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005124 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005125 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005126 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005127 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5128 // causing a connect/teardown loop.
5129 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5130 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005131 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005132 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005133 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5134 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005135 // does not cause any request (that is not a listen) currently matching that agent to
5136 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005137 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005138 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005139 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005140 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005141 }
5142
Paul Jensen3d194ea2015-06-16 14:27:36 -04005143 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005144 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005145 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005146 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005147 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005148 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005149 }
Paul Jensene0988542015-06-25 15:30:08 -04005150 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005151 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005152 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005153 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005154 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005155 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005156 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005157 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005158 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005159 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005160 if (nai.isSuspended()) {
5161 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5162 } else {
5163 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5164 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005165
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005166 return newNc;
5167 }
5168
5169 /**
5170 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5171 *
5172 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5173 * capabilities we manage and store in {@code nai}, such as validated status and captive
5174 * portal status)
5175 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5176 * potentially triggers rematches.
5177 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5178 * change.)
5179 *
5180 * @param oldScore score of the network before any of the changes that prompted us
5181 * to call this function.
5182 * @param nai the network having its capabilities updated.
5183 * @param nc the new network capabilities.
5184 */
5185 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5186 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5187
5188 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005189
Luke Huang8a462ec2018-08-24 20:33:16 +08005190 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5191 final int newPermission = getNetworkPermission(newNc);
5192 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005193 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005194 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005195 } catch (RemoteException e) {
5196 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005197 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005198 }
5199
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005200 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005201 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005202 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005203 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005204 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005205
Chalard Jeanf213ca12018-01-16 18:43:05 +09005206 updateUids(nai, prevNc, newNc);
5207
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005208 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005209 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5210 // the change we're processing can't affect any requests, it can only affect the listens
5211 // on this network. We might have been called by rematchNetworkAndRequests when a
5212 // network changed foreground state.
5213 processListenRequests(nai, true);
5214 } else {
5215 // If the requestable capabilities have changed or the score changed, we can't have been
5216 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005217 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005218 try {
5219 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5220 } catch (RemoteException e) {
5221 e.rethrowFromSystemServer();
5222 }
Paul Jensene0988542015-06-25 15:30:08 -04005223 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005224 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005225
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005226 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005227 final boolean oldMetered = prevNc.isMetered();
5228 final boolean newMetered = newNc.isMetered();
5229 final boolean meteredChanged = oldMetered != newMetered;
5230
5231 if (meteredChanged) {
5232 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5233 mRestrictBackground);
5234 }
5235
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005236 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005237 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005238
5239 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005240 if (meteredChanged || roamingChanged) {
5241 notifyIfacesChangedForNetworkStats();
5242 }
5243 }
5244
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005245 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005246 // Tell VPNs about updated capabilities, since they may need to
5247 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005248 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005249 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005250 }
5251
Chalard Jeanf213ca12018-01-16 18:43:05 +09005252 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5253 NetworkCapabilities newNc) {
5254 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5255 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5256 if (null == prevRanges) prevRanges = new ArraySet<>();
5257 if (null == newRanges) newRanges = new ArraySet<>();
5258 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5259
5260 prevRanges.removeAll(newRanges);
5261 newRanges.removeAll(prevRangesCopy);
5262
5263 try {
5264 if (!newRanges.isEmpty()) {
5265 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5266 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005267 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005268 }
5269 if (!prevRanges.isEmpty()) {
5270 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5271 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005272 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005273 }
5274 } catch (Exception e) {
5275 // Never crash!
5276 loge("Exception in updateUids: " + e);
5277 }
5278 }
5279
Hugo Benichief502882017-09-01 01:23:32 +00005280 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07005281 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005282 // Ignore updates for disconnected networks
5283 return;
5284 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005285 // newLp is already a defensive copy.
5286 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005287 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005288 log("Update of LinkProperties for " + nai.name() +
5289 "; created=" + nai.created +
5290 "; everConnected=" + nai.everConnected);
5291 }
lucaslin25a4ec32018-11-28 12:51:55 +08005292 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005293 }
5294
Paul Jensenc8b9a742014-09-30 15:37:41 -04005295 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005296 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5297 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005298 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005299 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04005300 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
5301 }
5302 }
5303
Robert Greenwalt7b816022014-04-18 15:25:25 -07005304 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005305 if (VDBG || DDBG){
5306 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5307 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005308 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07005309 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5310 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005311 }
5312 }
5313
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005314 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5315 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005316 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005317 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005318 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5319 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005320 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005321 sendIntent(nri.mPendingIntent, intent);
5322 }
5323 // else not handled
5324 }
5325
5326 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5327 mPendingIntentWakeLock.acquire();
5328 try {
5329 if (DBG) log("Sending " + pendingIntent);
5330 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5331 } catch (PendingIntent.CanceledException e) {
5332 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5333 mPendingIntentWakeLock.release();
5334 releasePendingNetworkRequest(pendingIntent);
5335 }
5336 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5337 }
5338
5339 @Override
5340 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5341 String resultData, Bundle resultExtras) {
5342 if (DBG) log("Finished sending " + pendingIntent);
5343 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005344 // Release with a delay so the receiving client has an opportunity to put in its
5345 // own request.
5346 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005347 }
5348
Chalard Jeanf19db372018-01-26 19:24:40 +09005349 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005350 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005351 if (nri.messenger == null) {
5352 return; // Default request has no msgr
5353 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005354 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005355 // TODO: check if defensive copies of data is needed.
5356 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005357 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005358 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5359 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005360 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005361 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005362 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005363 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5364 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005365 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005366 // For this notification, arg1 contains the blocked status.
5367 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005368 break;
5369 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005370 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005371 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005372 break;
5373 }
5374 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005375 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005376 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005377 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005378 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005379 break;
5380 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005381 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005382 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005383 break;
5384 }
junyulai05986c62018-08-07 19:50:45 +08005385 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005386 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005387 msg.arg1 = arg1;
5388 break;
5389 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005390 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005391 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005392 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005393 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005394 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005395 String notification = ConnectivityManager.getCallbackName(notificationType);
5396 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005397 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005398 nri.messenger.send(msg);
5399 } catch (RemoteException e) {
5400 // may occur naturally in the race of binder death.
5401 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5402 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005403 }
5404
Hugo Benichidba33db2017-03-23 22:40:44 +09005405 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5406 bundle.putParcelable(t.getClass().getSimpleName(), t);
5407 }
5408
Paul Jensenc8b9a742014-09-30 15:37:41 -04005409 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005410 if (nai.numRequestNetworkRequests() != 0) {
5411 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5412 NetworkRequest nr = nai.requestAt(i);
5413 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005414 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005415 loge("Dead network still had at least " + nr);
5416 break;
5417 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005418 }
5419 nai.asyncChannel.disconnect();
5420 }
5421
Robert Greenwalt7b816022014-04-18 15:25:25 -07005422 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5423 if (oldNetwork == null) {
5424 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5425 return;
5426 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005427 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005428
5429 // If we get here it means that the last linger timeout for this network expired. So there
5430 // must be no other active linger timers, and we must stop lingering.
5431 oldNetwork.clearLingerState();
5432
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005433 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005434 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005435 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005436 } else {
5437 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005438 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5439 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005440 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005441 }
5442
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005443 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005444 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005445
Paul Jensen27b02b72014-07-14 12:03:33 -04005446 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005447 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005448 } catch (Exception e) {
5449 loge("Exception setting default network :" + e);
5450 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005451
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005452 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005453 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005454 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005455 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005456 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005457 }
5458
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005459 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005460 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5461 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5462 NetworkRequest nr = nri.request;
5463 if (!nr.isListen()) continue;
5464 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5465 nai.removeRequest(nri.request.requestId);
5466 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5467 }
5468 }
5469
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005470 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005471 try {
5472 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5473 } catch (RemoteException e) {
5474 e.rethrowFromSystemServer();
5475 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005476 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5477 }
5478
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005479 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5480 NetworkRequest nr = nri.request;
5481 if (!nr.isListen()) continue;
5482 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5483 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005484 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005485 }
5486 }
5487 }
5488
Paul Jensen2161a8e2014-09-11 11:00:39 -04005489 // Handles a network appearing or improving its score.
5490 //
5491 // - Evaluates all current NetworkRequests that can be
5492 // satisfied by newNetwork, and reassigns to newNetwork
5493 // any such requests for which newNetwork is the best.
5494 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005495 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005496 // needed. A network is needed if it is the best network for
5497 // one or more NetworkRequests, or if it is a VPN.
5498 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005499 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005500 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005501 //
5502 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5503 // networks that have no chance (i.e. even if validated)
5504 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005505 //
5506 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5507 // it does not remove NetworkRequests that other Networks could better satisfy.
5508 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5509 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5510 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005511 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005512 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005513 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5514 // performed to tear down unvalidated networks that have no chance (i.e. even if
5515 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005516 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005517 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005518 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005519 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005520 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005521 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005522
5523 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5524 final int score = newNetwork.getCurrentScore();
5525
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005526 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005527
Paul Jensen2161a8e2014-09-11 11:00:39 -04005528 // Find and migrate to this Network any NetworkRequests for
5529 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005530 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5531 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005532 NetworkCapabilities nc = newNetwork.networkCapabilities;
5533 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005534 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005535 // Process requests in the first pass and listens in the second pass. This allows us to
5536 // change a network's capabilities depending on which requests it has. This is only
5537 // correct if the change in capabilities doesn't affect whether the network satisfies
5538 // requests or not, and doesn't affect the network's score.
5539 if (nri.request.isListen()) continue;
5540
Hugo Benichicd952782017-09-20 11:20:14 +09005541 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005542 final boolean satisfies = newNetwork.satisfies(nri.request);
5543 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005544 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005545 log("Network " + newNetwork.name() + " was already satisfying" +
5546 " request " + nri.request.requestId + ". No change.");
5547 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005548 keep = true;
5549 continue;
5550 }
5551
5552 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005553 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005554 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005555 // next check if it's better than any current network we're using for
5556 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005557 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005558 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005559 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005560 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005561 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005562 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005563 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005564 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005565 if (VDBG || DDBG){
5566 log(" accepting network in place of " + currentNetwork.name());
5567 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005568 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005569 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005570 affectedNetworks.add(currentNetwork);
5571 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005572 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005573 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005574 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005575 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005576 if (!newNetwork.addRequest(nri.request)) {
5577 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5578 }
5579 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005580 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005581 // Tell NetworkFactories about the new score, so they can stop
5582 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005583 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005584 // network. Think about if there is a way to reduce this. Push
5585 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005586 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005587 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005588 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005589 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005590 if (currentNetwork != null) {
5591 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5592 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005593 }
5594 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005595 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005596 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5597 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005598 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005599 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5600 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5601 // This means this code doesn't have to handle the case where "currentNetwork" no
5602 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5603 if (DBG) {
5604 log("Network " + newNetwork.name() + " stopped satisfying" +
5605 " request " + nri.request.requestId);
5606 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005607 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005608 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005609 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005610 sendUpdatedScoreToFactories(nri.request, 0);
5611 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005612 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5613 newNetwork.name() +
5614 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005615 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005616 // TODO: Technically, sending CALLBACK_LOST here is
5617 // incorrect if there is a replacement network currently
5618 // connected that can satisfy nri, which is a request
5619 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005620 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5621 // so this code is only incorrect for a network that loses
5622 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005623 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005624 }
5625 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005626 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005627 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005628 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005629 makeDefault(newNetwork);
5630 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005631 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005632 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005633 // Have a new default network, release the transition wakelock in
5634 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005635 }
5636
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005637 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5638 Slog.wtf(TAG, String.format(
5639 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005640 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005641 }
5642 if (newNetwork.getCurrentScore() != score) {
5643 Slog.wtf(TAG, String.format(
5644 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005645 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005646 }
5647
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005648 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005649 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5650 // If the network went from background to foreground or vice versa, we need to update
5651 // its foreground state. It is safe to do this after rematching the requests because
5652 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5653 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005654 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005655 } else {
5656 processListenRequests(newNetwork, false);
5657 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005658
Paul Jensencf4c2c62015-07-01 14:16:32 -04005659 // do this after the default net is switched, but
5660 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005661 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005662
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005663 // Linger any networks that are no longer needed. This should be done after sending the
5664 // available callback for newNetwork.
5665 for (NetworkAgentInfo nai : affectedNetworks) {
5666 updateLingerState(nai, now);
5667 }
5668 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5669 // does not need to be done in any particular order.
5670 updateLingerState(newNetwork, now);
5671
Paul Jensencf4c2c62015-07-01 14:16:32 -04005672 if (isNewDefault) {
5673 // Maintain the illusion: since the legacy API only
5674 // understands one network at a time, we must pretend
5675 // that the current default network disconnected before
5676 // the new one connected.
5677 if (oldDefaultNetwork != null) {
5678 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5679 oldDefaultNetwork, true);
5680 }
5681 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5682 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5683 notifyLockdownVpn(newNetwork);
5684 }
5685
Robert Greenwalt7b816022014-04-18 15:25:25 -07005686 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005687 // Notify battery stats service about this network, both the normal
5688 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005689 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005690 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005691 final IBatteryStats bs = BatteryStatsService.getService();
5692 final int type = newNetwork.networkInfo.getType();
5693
5694 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5695 bs.noteNetworkInterfaceType(baseIface, type);
5696 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5697 final String stackedIface = stacked.getInterfaceName();
5698 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005699 }
5700 } catch (RemoteException ignored) {
5701 }
5702
Robert Greenwalt152ed372014-12-17 17:19:53 -08005703 // This has to happen after the notifyNetworkCallbacks as that tickles each
5704 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005705 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005706 // and will generally do a dns request so they can ensureRouteToHost and if
5707 // they do that before the callbacks happen they'll use the default network.
5708 //
5709 // TODO: Is there still a race here? We send the broadcast
5710 // after sending the callback, but if the app can receive the
5711 // broadcast before the callback, it might still break.
5712 //
5713 // This *does* introduce a race where if the user uses the new api
5714 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5715 // they may get old info. Reverse this after the old startUsing api is removed.
5716 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005717 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5718 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005719 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005720 // legacy type tracker filters out repeat adds
5721 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5722 }
5723 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005724
5725 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5726 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5727 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5728 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5729 if (newNetwork.isVPN()) {
5730 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5731 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005732 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005733 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5734 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005735 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005736 if (nai.getLingerExpiry() > 0) {
5737 // This network has active linger timers and no requests, but is not
5738 // lingering. Linger it.
5739 //
5740 // One way (the only way?) this can happen if this network is unvalidated
5741 // and became unneeded due to another network improving its score to the
5742 // point where this network will no longer be able to satisfy any requests
5743 // even if it validates.
5744 updateLingerState(nai, now);
5745 } else {
5746 if (DBG) log("Reaping " + nai.name());
5747 teardownUnneededNetwork(nai);
5748 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005749 }
5750 }
5751 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005752 }
5753
Paul Jensen1c7ba022015-06-16 14:27:36 -04005754 /**
5755 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5756 * being disconnected.
5757 * @param changed If only one Network's score or capabilities have been modified since the last
5758 * time this function was called, pass this Network in this argument, otherwise pass
5759 * null.
5760 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5761 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5762 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5763 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5764 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005765 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005766 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005767 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5768 // to avoid the slowness. It is not simply enough to process just "changed", for
5769 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005770 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005771
5772 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5773 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5774 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005775 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005776 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005777 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005778 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005779 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5780 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5781 // Rematch higher scoring networks first to prevent requests first matching a lower
5782 // scoring network and then a higher scoring network, which could produce multiple
5783 // callbacks and inadvertently unlinger networks.
5784 Arrays.sort(nais);
5785 for (NetworkAgentInfo nai : nais) {
5786 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005787 // Only reap the last time through the loop. Reaping before all rematching
5788 // is complete could incorrectly teardown a network that hasn't yet been
5789 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005790 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005791 : ReapUnvalidatedNetworks.REAP,
5792 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005793 }
5794 }
5795 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005796
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005797 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005798 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005799 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005800 // For now only update icons for default connection.
5801 // TODO: Update WiFi and cellular icons separately. b/17237507
5802 if (!isDefaultNetwork(nai)) return;
5803
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005804 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005805 // Don't repeat publish.
5806 if (newInetCondition == mDefaultInetConditionPublished) return;
5807
5808 mDefaultInetConditionPublished = newInetCondition;
5809 sendInetConditionBroadcast(nai.networkInfo);
5810 }
5811
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005812 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005813 synchronized (mVpns) {
5814 if (mLockdownTracker != null) {
5815 if (nai != null && nai.isVPN()) {
5816 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5817 } else {
5818 mLockdownTracker.onNetworkInfoChanged();
5819 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005820 }
5821 }
5822 }
5823
Robert Greenwalt7b816022014-04-18 15:25:25 -07005824 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005825 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005826 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005827 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005828 synchronized (networkAgent) {
5829 oldInfo = networkAgent.networkInfo;
5830 networkAgent.networkInfo = newInfo;
5831 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005832 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005833
Robert Greenwalt7b816022014-04-18 15:25:25 -07005834 if (DBG) {
5835 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5836 (oldInfo == null ? "null" : oldInfo.getState()) +
5837 " to " + state);
5838 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005839
Robin Lee585e2482016-05-01 23:00:00 +01005840 if (!networkAgent.created
5841 && (state == NetworkInfo.State.CONNECTED
5842 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005843
5844 // A network that has just connected has zero requests and is thus a foreground network.
5845 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5846
Robert Greenwalt7b816022014-04-18 15:25:25 -07005847 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005848 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005849 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08005850 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005851 (networkAgent.networkMisc == null ||
5852 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005853 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08005854 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005855 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005856 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005857 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005858 loge("Error creating network " + networkAgent.network.netId + ": "
5859 + e.getMessage());
5860 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005861 }
Paul Jenseneec75412014-08-04 12:21:19 -04005862 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005863 }
5864
5865 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5866 networkAgent.everConnected = true;
5867
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005868 if (networkAgent.linkProperties == null) {
5869 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5870 }
5871
Erik Kline736353a2018-03-21 07:18:33 -07005872 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08005873 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
5874 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005875
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005876 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
5877 // command must be sent after updating LinkProperties to maximize chances of
5878 // NetworkMonitor seeing the correct LinkProperties when starting.
5879 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
5880 try {
5881 networkAgent.networkMonitor().notifyNetworkConnected();
5882 } catch (RemoteException e) {
5883 e.rethrowFromSystemServer();
5884 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005885 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005886
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005887 if (networkAgent.isVPN()) {
5888 // Temporarily disable the default proxy (not global).
Chalard Jean60778f92018-06-08 19:08:25 +09005889 mProxyTracker.setDefaultProxyEnabled(false);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005890 // TODO: support proxy per network.
5891 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005892
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005893 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5894 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5895 // capabilities, so it only needs to be done once on initial connect, not every time the
5896 // network's capabilities change. Note that we do this before rematching the network,
5897 // so we could decide to tear it down immediately afterwards. That's fine though - on
5898 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5899 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005900 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005901
Paul Jensen2161a8e2014-09-11 11:00:39 -04005902 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005903 final long now = SystemClock.elapsedRealtime();
5904 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005905
5906 // This has to happen after matching the requests, because callbacks are just requests.
5907 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005908 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005909 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005910 if (networkAgent.isVPN()) {
Chalard Jean60778f92018-06-08 19:08:25 +09005911 mProxyTracker.setDefaultProxyEnabled(true);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005912 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005913 }
Chalard Jean392971c2018-05-11 20:19:20 +09005914 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005915 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5916 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09005917 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07005918 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005919 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005920 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005921 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5922 networkAgent.networkCapabilities);
5923 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5924 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005925 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5926 ConnectivityManager.CALLBACK_SUSPENDED :
5927 ConnectivityManager.CALLBACK_RESUMED));
5928 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005929 }
5930 }
5931
Robert Greenwaltac96c522014-06-03 16:43:57 -07005932 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005933 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005934 if (score < 0) {
5935 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5936 "). Bumping score to min of 0");
5937 score = 0;
5938 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005939
Paul Jensen2161a8e2014-09-11 11:00:39 -04005940 final int oldScore = nai.getCurrentScore();
5941 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005942
Paul Jensen85cf78e2015-06-25 13:25:07 -04005943 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005944
Paul Jensenc8b9a742014-09-30 15:37:41 -04005945 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005946 }
5947
Erik Klinec75d4fa2017-02-15 19:59:17 +09005948 // Notify only this one new request of the current state. Transfer all the
5949 // current state by calling NetworkCapabilities and LinkProperties callbacks
5950 // so that callers can be guaranteed to have as close to atomicity in state
5951 // transfer as can be supported by this current API.
5952 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005953 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005954 if (nri.mPendingIntent != null) {
5955 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5956 // Attempt no subsequent state pushes where intents are involved.
5957 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005958 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005959
junyulai05986c62018-08-07 19:50:45 +08005960 final boolean metered = nai.networkCapabilities.isMetered();
5961 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
5962 metered, mRestrictBackground);
5963 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
5964 }
5965
5966 /**
5967 * Notify of the blocked state apps with a registered callback matching a given NAI.
5968 *
5969 * Unlike other callbacks, blocked status is different between each individual uid. So for
5970 * any given nai, all requests need to be considered according to the uid who filed it.
5971 *
5972 * @param nai The target NetworkAgentInfo.
5973 * @param oldMetered True if the previous network capabilities is metered.
5974 * @param newRestrictBackground True if data saver is enabled.
5975 */
5976 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
5977 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
5978
5979 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5980 NetworkRequest nr = nai.requestAt(i);
5981 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5982 final int uidRules = mUidRules.get(nri.mUid);
5983 final boolean oldBlocked, newBlocked;
5984 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
5985 // between these two calls.
5986 synchronized (mVpns) {
5987 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
5988 oldRestrictBackground);
5989 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
5990 newRestrictBackground);
5991 }
5992 if (oldBlocked != newBlocked) {
5993 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
5994 encodeBool(newBlocked));
5995 }
5996 }
5997 }
5998
5999 /**
6000 * Notify apps with a given UID of the new blocked state according to new uid rules.
6001 * @param uid The uid for which the rules changed.
6002 * @param newRules The new rules to apply.
6003 */
6004 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6005 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6006 final boolean metered = nai.networkCapabilities.isMetered();
6007 final boolean oldBlocked, newBlocked;
6008 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6009 // rules changed event. And this function actually loop through all connected nai and
6010 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6011 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6012 synchronized (mVpns) {
6013 oldBlocked = isUidNetworkingWithVpnBlocked(
6014 uid, mUidRules.get(uid), metered, mRestrictBackground);
6015 newBlocked = isUidNetworkingWithVpnBlocked(
6016 uid, newRules, metered, mRestrictBackground);
6017 }
6018 if (oldBlocked == newBlocked) {
6019 return;
6020 }
6021 final int arg = encodeBool(newBlocked);
6022 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6023 NetworkRequest nr = nai.requestAt(i);
6024 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6025 if (nri != null && nri.mUid == uid) {
6026 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6027 }
6028 }
6029 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006030 }
6031
Robert Greenwalt8d482522015-06-24 13:23:42 -07006032 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006033 // The NetworkInfo we actually send out has no bearing on the real
6034 // state of affairs. For example, if the default connection is mobile,
6035 // and a request for HIPRI has just gone away, we need to pretend that
6036 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6037 // the state to DISCONNECTED, even though the network is of type MOBILE
6038 // and is still connected.
6039 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6040 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006041 if (state != DetailedState.DISCONNECTED) {
6042 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006043 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006044 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006045 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006046 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6047 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6048 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6049 if (info.isFailover()) {
6050 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6051 nai.networkInfo.setFailover(false);
6052 }
6053 if (info.getReason() != null) {
6054 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6055 }
6056 if (info.getExtraInfo() != null) {
6057 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6058 }
6059 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006060 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006061 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006062 if (newDefaultAgent != null) {
6063 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6064 newDefaultAgent.networkInfo);
6065 } else {
6066 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6067 }
6068 }
6069 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6070 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006071 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006072 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006073 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006074 }
6075 }
6076 }
6077
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006078 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006079 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006080 String notification = ConnectivityManager.getCallbackName(notifyType);
6081 log("notifyType " + notification + " for " + networkAgent.name());
6082 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006083 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6084 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006085 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6086 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006087 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6088 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006089 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006090 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006091 } else {
6092 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6093 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006094 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006095 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006096
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006097 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6098 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6099 }
6100
Jeff Sharkey69736342014-12-08 14:50:12 -08006101 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006102 * Returns the list of all interfaces that could be used by network traffic that does not
6103 * explicitly specify a network. This includes the default network, but also all VPNs that are
6104 * currently connected.
6105 *
6106 * Must be called on the handler thread.
6107 */
6108 private Network[] getDefaultNetworks() {
6109 ArrayList<Network> defaultNetworks = new ArrayList<>();
6110 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6111 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6112 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6113 defaultNetworks.add(nai.network);
6114 }
6115 }
6116 return defaultNetworks.toArray(new Network[0]);
6117 }
6118
6119 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006120 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6121 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006122 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006123 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08006124 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006125 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08006126 } catch (Exception ignored) {
6127 }
6128 }
6129
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006130 @Override
6131 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006132 int user = UserHandle.getUserId(Binder.getCallingUid());
6133 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006134 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006135 return mVpns.get(user).addAddress(address, prefixLength);
6136 }
6137 }
6138
6139 @Override
6140 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006141 int user = UserHandle.getUserId(Binder.getCallingUid());
6142 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006143 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006144 return mVpns.get(user).removeAddress(address, prefixLength);
6145 }
6146 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006147
6148 @Override
6149 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006150 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006151 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006152 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006153 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006154 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006155 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006156 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006157 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006158 }
6159 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006160 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006161
6162 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006163 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006164 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006165 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006166 }
6167
6168 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006169 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
6170 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
6171 enforceKeepalivePermission();
6172 mKeepaliveTracker.startNattKeepalive(
6173 getNetworkAgentInfoForNetwork(network),
6174 intervalSeconds, messenger, binder,
6175 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
6176 }
6177
6178 @Override
6179 public void stopKeepalive(Network network, int slot) {
6180 mHandler.sendMessage(mHandler.obtainMessage(
6181 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
6182 }
6183
6184 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006185 public void factoryReset() {
6186 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006187
6188 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6189 return;
6190 }
6191
Robin Lee3b3dd942015-05-12 18:14:58 +01006192 final int userId = UserHandle.getCallingUserId();
6193
Stuart Scottf1fb3972015-04-02 18:00:02 -07006194 // Turn airplane mode off
6195 setAirplaneMode(false);
6196
Stuart Scotte3e314d2015-04-20 14:07:45 -07006197 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6198 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006199 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006200 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006201 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006202 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006203 }
6204
Stuart Scotte3e314d2015-04-20 14:07:45 -07006205 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006206 // Remove always-on package
6207 synchronized (mVpns) {
6208 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6209 if (alwaysOnPackage != null) {
6210 setAlwaysOnVpnPackage(userId, null, false);
6211 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6212 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006213
Hugo Benichi69744342017-11-27 10:57:16 +09006214 // Turn Always-on VPN off
6215 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6216 final long ident = Binder.clearCallingIdentity();
6217 try {
6218 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6219 mLockdownEnabled = false;
6220 setLockdownTracker(null);
6221 } finally {
6222 Binder.restoreCallingIdentity(ident);
6223 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006224 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006225
Hugo Benichi69744342017-11-27 10:57:16 +09006226 // Turn VPN off
6227 VpnConfig vpnConfig = getVpnConfig(userId);
6228 if (vpnConfig != null) {
6229 if (vpnConfig.legacy) {
6230 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6231 } else {
6232 // Prevent this app (packagename = vpnConfig.user) from initiating
6233 // VPN connections in the future without user intervention.
6234 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006235
Hugo Benichi69744342017-11-27 10:57:16 +09006236 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6237 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006238 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006239 }
6240 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006241
6242 Settings.Global.putString(mContext.getContentResolver(),
6243 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006244 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006245
Ricky Wai44dcbde2018-01-23 04:09:45 +00006246 @Override
6247 public byte[] getNetworkWatchlistConfigHash() {
6248 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6249 if (nwm == null) {
6250 loge("Unable to get NetworkWatchlistManager");
6251 return null;
6252 }
6253 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6254 return nwm.getWatchlistConfigHash();
6255 }
6256
Paul Jensencf4c2c62015-07-01 14:16:32 -04006257 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006258 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6259 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006260 }
6261
6262 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006263 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6264 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6265 }
6266
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006267 @VisibleForTesting
6268 public boolean hasService(String name) {
6269 return ServiceManager.checkService(name) != null;
6270 }
6271
Hugo Benichi64901e52017-10-19 14:42:40 +09006272 @VisibleForTesting
6273 protected IpConnectivityMetrics.Logger metricsLogger() {
6274 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6275 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006276 }
6277
6278 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006279 int[] transports = nai.networkCapabilities.getTransportTypes();
6280 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006281 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006282
6283 private static boolean toBool(int encodedBoolean) {
6284 return encodedBoolean != 0; // Only 0 means false.
6285 }
6286
6287 private static int encodeBool(boolean b) {
6288 return b ? 1 : 0;
6289 }
mswest46386886f2018-03-12 10:34:34 -07006290
6291 @Override
6292 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6293 FileDescriptor err, String[] args, ShellCallback callback,
6294 ResultReceiver resultReceiver) {
6295 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6296 }
6297
6298 private class ShellCmd extends ShellCommand {
6299
6300 @Override
6301 public int onCommand(String cmd) {
6302 if (cmd == null) {
6303 return handleDefaultCommands(cmd);
6304 }
6305 final PrintWriter pw = getOutPrintWriter();
6306 try {
6307 switch (cmd) {
6308 case "airplane-mode":
6309 final String action = getNextArg();
6310 if ("enable".equals(action)) {
6311 setAirplaneMode(true);
6312 return 0;
6313 } else if ("disable".equals(action)) {
6314 setAirplaneMode(false);
6315 return 0;
6316 } else if (action == null) {
6317 final ContentResolver cr = mContext.getContentResolver();
6318 final int enabled = Settings.Global.getInt(cr,
6319 Settings.Global.AIRPLANE_MODE_ON);
6320 pw.println(enabled == 0 ? "disabled" : "enabled");
6321 return 0;
6322 } else {
6323 onHelp();
6324 return -1;
6325 }
6326 default:
6327 return handleDefaultCommands(cmd);
6328 }
6329 } catch (Exception e) {
6330 pw.println(e);
6331 }
6332 return -1;
6333 }
6334
6335 @Override
6336 public void onHelp() {
6337 PrintWriter pw = getOutPrintWriter();
6338 pw.println("Connectivity service commands:");
6339 pw.println(" help");
6340 pw.println(" Print this help text.");
6341 pw.println(" airplane-mode [enable|disable]");
6342 pw.println(" Turn airplane mode on or off.");
6343 pw.println(" airplane-mode");
6344 pw.println(" Get airplane mode.");
6345 }
6346 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006347
6348 /**
6349 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6350 * for testing.
6351 */
6352 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6353 if (checkNetworkStackPermission()) {
6354 return null;
6355 }
6356 final int uid = Binder.getCallingUid();
6357 final int user = UserHandle.getUserId(uid);
6358 synchronized (mVpns) {
6359 Vpn vpn = mVpns.get(user);
6360 try {
6361 if (vpn.getVpnInfo().ownerUid == uid) return vpn;
6362 } catch (NullPointerException e) {
6363 /* vpn is null, or VPN is not connected and getVpnInfo() is null. */
6364 }
6365 }
6366 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6367 + "permission");
6368 }
6369
6370 /**
6371 * @param connectionInfo the connection to resolve.
6372 * @return {@code uid} if the connection is found and the app has permission to observe it
6373 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6374 * connection is not found.
6375 */
6376 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6377 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6378 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6379 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6380 }
6381
6382 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6383 connectionInfo.local, connectionInfo.remote);
6384
6385 /* Filter out Uids not associated with the VPN. */
6386 if (vpn != null && !vpn.appliesToUid(uid)) {
6387 return INVALID_UID;
6388 }
6389
6390 return uid;
6391 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006392}