blob: 694ae6a2738e7cf364dd05d4b6e6c7b0f69e8f91 [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;
Paul Jensen3d194ea2015-06-16 14:27:36 -040028import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080038import static android.net.NetworkPolicyManager.RULE_NONE;
39import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070040import static android.os.Process.INVALID_UID;
41import static android.system.OsConstants.IPPROTO_TCP;
42import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060043
Hugo Benichia0385682017-03-22 17:07:57 +090044import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060045
Wenchao Tongf5ea3402015-03-04 13:26:38 -080046import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080047import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090048import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070049import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070050import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.ContentResolver;
52import android.content.Context;
53import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070054import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070055import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070056import android.database.ContentObserver;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070057import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090059import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050061import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080062import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050063import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070064import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070065import android.net.INetworkPolicyListener;
66import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070067import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080068import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070069import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010070import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070071import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070072import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070073import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070074import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070076import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070077import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090078import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070079import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070080import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070081import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070082import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070083import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000084import android.net.NetworkWatchlistManager;
Jason Monk207900c2014-04-25 15:00:09 -040085import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070086import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040087import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040088import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060089import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090090import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090091import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070092import android.net.netlink.InetDiagMessage;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090093import android.net.util.MultinetworkPolicyTracker;
Luke Huang674660f2018-09-27 19:33:11 +080094import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080096import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070097import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040098import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700100import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700101import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700102import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.Looper;
104import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700105import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700106import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900107import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700108import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700109import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700110import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800111import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900112import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900113import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700114import android.os.ShellCallback;
115import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900116import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700117import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400118import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700120import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700121import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700122import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700123import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900124import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700125import android.util.LocalLog;
126import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600127import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800128import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700129import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500130import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700131import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
Wink Savilleab9321d2013-06-29 21:10:57 -0700134import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400135import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400136import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700137import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700138import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700139import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800140import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700141import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900142import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700143import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600144import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700145import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900146import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900147import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700148import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700149import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400150import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900151import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900152import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk7301aa42018-03-05 12:42:22 -0500153import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900154import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900155import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100156import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700157import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900158import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700159import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600160import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400161import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900162import com.android.server.connectivity.NetworkNotificationManager;
163import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700164import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900165import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800166import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700167import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100168import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500169import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700170import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700171import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900172import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700173import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600174
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700175import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700176
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700177import org.xmlpull.v1.XmlPullParser;
178import org.xmlpull.v1.XmlPullParserException;
179
180import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700182import java.io.FileNotFoundException;
183import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700184import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700186import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700187import java.net.InetAddress;
188import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700189import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700190import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700191import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700192import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900193import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800194import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700195import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700196import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700197import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700198import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700199import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900200import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600201import java.util.SortedSet;
202import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204/**
205 * @hide
206 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800207public class ConnectivityService extends IConnectivityManager.Stub
208 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900209 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
Chalard Jean4133a122018-06-04 13:33:12 +0900211 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900212 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900213 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900214 private static final String NETWORK_ARG = "networks";
215 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900216
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900217 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700218 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900220 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700221
Jeff Sharkey899223b2012-08-04 15:24:58 -0700222 // TODO: create better separation between radio types and network types
223
Robert Greenwalt42acef32009-08-12 16:08:25 -0700224 // how long to wait before switching back to a radio's default network
225 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
226 // system property that can override the above value
227 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
228 "android.telephony.apn-restore";
229
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900230 // How long to wait before putting up a "This network doesn't have an Internet connection,
231 // connect anyway?" dialog after the user selects a network that doesn't validate.
232 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
233
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900234 // Default to 30s linger time-out. Modifiable only for testing.
235 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
236 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
237 @VisibleForTesting
238 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
239
Jeremy Joslin79294842014-12-03 17:15:28 -0800240 // How long to delay to removal of a pending intent based request.
241 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
242 private final int mReleasePendingIntentDelayMs;
243
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900244 private MockableSystemProperties mSystemProperties;
245
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800246 private Tethering mTethering;
247
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700248 private final PermissionMonitor mPermissionMonitor;
249
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700250 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700251
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900252 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700253 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900254 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700255
Hugo Benichi69744342017-11-27 10:57:16 +0900256 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
257 // a direct call to LockdownVpnTracker.isEnabled().
258 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700259 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900260 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700261 private LockdownVpnTracker mLockdownTracker;
262
junyulai05986c62018-08-07 19:50:45 +0800263 /**
264 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
265 * handler thread, they don't need a lock.
266 */
267 private SparseIntArray mUidRules = new SparseIntArray();
268 /** Flag indicating if background data is restricted. */
269 private boolean mRestrictBackground;
270
Erik Klineda4bfa82015-04-30 12:58:40 +0900271 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700272 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700273 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
Luke Huang4e25ec62018-09-27 16:58:23 +0800275 private INetworkManagementService mNMS;
Luke Huang674660f2018-09-27 19:33:11 +0800276 private INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800277 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700278 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900279 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700280
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700281 private String mCurrentTcpBufferSizes;
282
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900283 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900284 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
285 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900286
Paul Jensenb10e37f2014-11-25 12:33:08 -0500287 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400288 // Tear down networks that have no chance (e.g. even if validated) of becoming
289 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500290 // all networks have been rematched against all NetworkRequests.
291 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400292 // Don't reap networks. This should be passed when some networks have not yet been
293 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500294 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900295 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500296
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900297 private enum UnneededFor {
298 LINGER, // Determine whether this network is unneeded and should be lingered.
299 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
300 }
301
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700302 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700303 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700304 * from one net to another. Clear happens when we get a new
305 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
306 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700307 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700308 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700309
Robert Greenwalt434203a2010-10-11 16:00:27 -0700310 /**
311 * used internally to reload global proxy settings
312 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700313 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700314
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700315 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400316 * PAC manager has received new port.
317 */
318 private static final int EVENT_PROXY_HAS_CHANGED = 16;
319
Robert Greenwalte049c232014-04-11 15:53:27 -0700320 /**
321 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700322 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700323 */
324 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
325
Robert Greenwalt7b816022014-04-18 15:25:25 -0700326 /**
327 * used internally when registering NetworkAgents
328 * obj = Messenger
329 */
330 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
331
Robert Greenwalt9258c642014-03-26 16:47:06 -0700332 /**
333 * used to add a network request
334 * includes a NetworkRequestInfo
335 */
336 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
337
338 /**
339 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900340 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700341 * cancel it.
342 * includes a NetworkRequestInfo
343 */
344 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
345
346 /**
347 * used to add a network listener - no request
348 * includes a NetworkRequestInfo
349 */
350 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
351
352 /**
353 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400354 * arg1 = UID of caller
355 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700356 */
357 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
358
Robert Greenwalta67be032014-05-16 15:49:14 -0700359 /**
360 * used internally when registering NetworkFactories
361 * obj = Messenger
362 */
363 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
364
Robert Greenwalt27711812014-06-25 16:45:57 -0700365 /**
366 * used internally to expire a wakelock when transitioning
367 * from one net to another. Expire happens when we fail to find
368 * a new network (typically after 1 minute) -
369 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
370 * a replacement network.
371 */
372 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
373
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700374 /**
375 * Used internally to indicate the system is ready.
376 */
377 private static final int EVENT_SYSTEM_READY = 25;
378
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800379 /**
380 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400381 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800382 */
383 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
384
385 /**
386 * used to remove a pending intent and its associated network request.
387 * arg1 = UID of caller
388 * obj = PendingIntent
389 */
390 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
391
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900392 /**
393 * used to specify whether a network should be used even if unvalidated.
394 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
395 * arg2 = whether to remember this choice in the future (1 or 0)
396 * obj = network
397 */
398 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
399
400 /**
401 * used to ask the user to confirm a connection to an unvalidated network.
402 * obj = network
403 */
404 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700405
Erik Klineda4bfa82015-04-30 12:58:40 +0900406 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700407 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900408 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700409 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900410
Paul Jensen694f2b82015-06-17 14:15:39 -0400411 /**
412 * used to add a network listener with a pending intent
413 * obj = NetworkRequestInfo
414 */
415 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
416
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900417 /**
418 * used to specify whether a network should not be penalized when it becomes unvalidated.
419 */
420 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
421
422 /**
423 * used to trigger revalidation of a network.
424 */
425 private static final int EVENT_REVALIDATE_NETWORK = 36;
426
Erik Klinea24d4592018-01-11 21:07:29 +0900427 // Handle changes in Private DNS settings.
428 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
429
dalyk7301aa42018-03-05 12:42:22 -0500430 // Handle private DNS validation status updates.
431 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
432
junyulai05986c62018-08-07 19:50:45 +0800433 /**
434 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
435 */
436 private static final int EVENT_UID_RULES_CHANGED = 39;
437
438 /**
439 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
440 */
441 private static final int EVENT_DATA_SAVER_CHANGED = 40;
442
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900443 private static String eventName(int what) {
444 return sMagicDecoderRing.get(what, Integer.toString(what));
445 }
446
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900447 /** Handler thread used for both of the handlers below. */
448 @VisibleForTesting
449 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700450 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700451 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700452 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700453 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900454 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700455
Mike Lockwood0f79b542009-08-14 14:18:49 -0400456 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800457 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400458
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700459 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700460 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800461 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700462
Chalard Jean52c2aa72018-06-07 16:44:04 +0900463 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
464 // the world when it changes.
Chalard Jeanff5d0052018-06-07 19:20:08 +0900465 private final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400466
Erik Klineda4bfa82015-04-30 12:58:40 +0900467 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700468
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400469 private UserManager mUserManager;
470
Chalard Jean4133a122018-06-04 13:33:12 +0900471 private NetworkConfig[] mNetConfigs;
472 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700473
Robert Greenwalt50393202011-06-21 17:26:14 -0700474 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900475 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700476
Chalard Jean4133a122018-06-04 13:33:12 +0900477 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400478
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900479 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900480 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900481 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900482
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700483 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800484 private static final int MIN_NET_ID = 100; // some reserved marks
485 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700486 private int mNextNetId = MIN_NET_ID;
487
Robert Greenwalt34524f02014-05-18 16:22:10 -0700488 // sequence number of NetworkRequests
489 private int mNextNetworkRequestId = 1;
490
Erik Kline7523eb32015-07-09 18:24:03 +0900491 // NetworkRequest activity String log entries.
492 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
493 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
494
Hugo Benichic2ae2872016-07-11 11:05:12 +0900495 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900496 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900497 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
498
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900499 private static final int MAX_WAKELOCK_LOGS = 20;
500 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900501 private int mTotalWakelockAcquisitions = 0;
502 private int mTotalWakelockReleases = 0;
503 private long mTotalWakelockDurationMs = 0;
504 private long mMaxWakelockDurationMs = 0;
505 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900506
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700507 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
508 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400509 private static class ValidationLog {
510 final Network mNetwork;
Chalard Jeand771aa02018-04-26 16:16:10 +0900511 final String mName;
Paul Jensen0808eb82016-06-03 13:51:21 -0400512 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700513
Chalard Jeand771aa02018-04-26 16:16:10 +0900514 ValidationLog(Network network, String name, ReadOnlyLocalLog log) {
Paul Jensen0808eb82016-06-03 13:51:21 -0400515 mNetwork = network;
Chalard Jeand771aa02018-04-26 16:16:10 +0900516 mName = name;
Paul Jensen0808eb82016-06-03 13:51:21 -0400517 mLog = log;
518 }
519 }
Chalard Jean4133a122018-06-04 13:33:12 +0900520 private final ArrayDeque<ValidationLog> mValidationLogs = new ArrayDeque<>(MAX_VALIDATION_LOGS);
Paul Jensen0808eb82016-06-03 13:51:21 -0400521
Chalard Jeand771aa02018-04-26 16:16:10 +0900522 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String name) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900523 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700524 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
525 mValidationLogs.removeLast();
526 }
Chalard Jeand771aa02018-04-26 16:16:10 +0900527 mValidationLogs.addFirst(new ValidationLog(network, name, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700528 }
529 }
530
Hugo Benichif9fdf872016-07-28 17:53:06 +0900531 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900532
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700533 @GuardedBy("mBandwidthRequests")
534 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
535
Erik Kline065ab6e2016-10-02 18:02:14 +0900536 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900537 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900538
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900539 @VisibleForTesting
540 final MultipathPolicyTracker mMultipathPolicyTracker;
541
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700542 /**
543 * Implements support for the legacy "one network per network type" model.
544 *
545 * We used to have a static array of NetworkStateTrackers, one for each
546 * network type, but that doesn't work any more now that we can have,
547 * for example, more that one wifi network. This class stores all the
548 * NetworkAgentInfo objects that support a given type, but the legacy
549 * API will only see the first one.
550 *
551 * It serves two main purposes:
552 *
553 * 1. Provide information about "the network for a given type" (since this
554 * API only supports one).
555 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
556 * the first network for a given type changes, or if the default network
557 * changes.
558 */
559 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900560
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900561 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900562 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900563
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 /**
565 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
566 * Each list holds references to all NetworkAgentInfos that are used to
567 * satisfy requests for that network type.
568 *
569 * This array is built out at startup such that an unsupported network
570 * doesn't get an ArrayList instance, making this a tristate:
571 * unsupported, supported but not active and active.
572 *
573 * The actual lists are populated when we scan the network types that
574 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900575 *
576 * Threading model:
577 * - addSupportedType() is only called in the constructor
578 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
579 * They are therefore not thread-safe with respect to each other.
580 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
581 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
582 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700583 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900584 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700585
586 public LegacyTypeTracker() {
587 mTypeLists = (ArrayList<NetworkAgentInfo>[])
588 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
589 }
590
591 public void addSupportedType(int type) {
592 if (mTypeLists[type] != null) {
593 throw new IllegalStateException(
594 "legacy list for type " + type + "already initialized");
595 }
Chalard Jean4133a122018-06-04 13:33:12 +0900596 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
598
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700599 public boolean isTypeSupported(int type) {
600 return isNetworkTypeValid(type) && mTypeLists[type] != null;
601 }
602
603 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 synchronized (mTypeLists) {
605 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
606 return mTypeLists[type].get(0);
607 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900609 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 }
611
Robert Greenwalt8d482522015-06-24 13:23:42 -0700612 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900614 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700615 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900617 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619 }
620
621 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700622 public void add(int type, NetworkAgentInfo nai) {
623 if (!isTypeSupported(type)) {
624 return; // Invalid network type.
625 }
626 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
627
628 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
629 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 return;
631 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900632 synchronized (mTypeLists) {
633 list.add(nai);
634 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900635
636 // 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 +0900637 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900638 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700639 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
640 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700642 }
643
Lorenzo Colittia793a672014-07-31 23:20:17 +0900644 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900645 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900646 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
647 if (list == null || list.isEmpty()) {
648 return;
649 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900650 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651
Hugo Benichi78caa2582016-06-21 09:48:07 +0900652 synchronized (mTypeLists) {
653 if (!list.remove(nai)) {
654 return;
655 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900656 }
657
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 final DetailedState state = DetailedState.DISCONNECTED;
659
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900660 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700661 maybeLogBroadcast(nai, state, type, wasDefault);
662 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900663 }
664
665 if (!list.isEmpty() && wasFirstNetwork) {
666 if (DBG) log("Other network available for type " + type +
667 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900668 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700669 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
670 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900671 }
672 }
673
674 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900675 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
676 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700677 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900678 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700679 }
680 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700681
Robert Greenwalt8d482522015-06-24 13:23:42 -0700682 // send out another legacy broadcast - currently only used for suspend/unsuspend
683 // toggle
684 public void update(NetworkAgentInfo nai) {
685 final boolean isDefault = isDefaultNetwork(nai);
686 final DetailedState state = nai.networkInfo.getDetailedState();
687 for (int type = 0; type < mTypeLists.length; type++) {
688 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700689 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900690 final boolean isFirst = contains && (nai == list.get(0));
691 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700692 maybeLogBroadcast(nai, state, type, isDefault);
693 sendLegacyNetworkBroadcast(nai, state, type);
694 }
695 }
696 }
697
Lorenzo Colittia793a672014-07-31 23:20:17 +0900698 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900699 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900700 String state = (nai.networkInfo != null) ?
701 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
702 "???/???";
703 return name + " " + state;
704 }
705
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700706 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900707 pw.println("mLegacyTypeTracker:");
708 pw.increaseIndent();
709 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700710 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900711 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700712 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900713 pw.println();
714 pw.println("Current state:");
715 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900716 synchronized (mTypeLists) {
717 for (int type = 0; type < mTypeLists.length; type++) {
718 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
719 for (NetworkAgentInfo nai : mTypeLists[type]) {
720 pw.println(type + " " + naiToString(nai));
721 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900722 }
723 }
724 pw.decreaseIndent();
725 pw.decreaseIndent();
726 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700727 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700728 }
729 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
730
Vishnu Nair5c010902017-10-26 10:08:50 -0700731 /**
732 * Helper class which parses out priority arguments and dumps sections according to their
733 * priority. If priority arguments are omitted, function calls the legacy dump command.
734 */
735 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
736 @Override
737 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
738 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
739 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
740 }
741
742 @Override
743 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
744 doDump(fd, pw, args, asProto);
745 }
746
747 @Override
748 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
749 doDump(fd, pw, args, asProto);
750 }
751 };
752
Jeff Sharkey899223b2012-08-04 15:24:58 -0700753 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700754 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900755 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
756 }
757
758 @VisibleForTesting
759 protected ConnectivityService(Context context, INetworkManagementService netManager,
760 INetworkStatsService statsService, INetworkPolicyManager policyManager,
761 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800762 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800763
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900764 mSystemProperties = getSystemProperties();
765
Hugo Benichif9fdf872016-07-28 17:53:06 +0900766 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900767 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900768 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900769 mNetworkRequests.put(mDefaultRequest, defaultNRI);
770 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900771
Chalard Jeandda156a2018-01-10 21:19:32 +0900772 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900773 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700774
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700775 // The default WiFi request is a background request so that apps using WiFi are
776 // migrated to a better network (typically ethernet) when one comes up, instead
777 // of staying on WiFi forever.
778 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
779 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
780
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900781 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900782 mHandlerThread.start();
783 mHandler = new InternalHandler(mHandlerThread.getLooper());
784 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700785
Jeremy Joslin79294842014-12-03 17:15:28 -0800786 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
787 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
788
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900789 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900790
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700791 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800792 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800793 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700794 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900795 mPolicyManagerInternal = checkNotNull(
796 LocalServices.getService(NetworkPolicyManagerInternal.class),
797 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900798 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900799
Luke Huang674660f2018-09-27 19:33:11 +0800800 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700801 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700802 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700803
junyulai05986c62018-08-07 19:50:45 +0800804 // To ensure uid rules are synchronized with Network Policy, register for
805 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
806 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700807 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900808 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700809 } catch (RemoteException e) {
810 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700811 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700812 }
813
814 final PowerManager powerManager = (PowerManager) context.getSystemService(
815 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700816 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
817 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
818 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800819 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700820
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700821 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700822
Wink Saville51f456f2013-04-23 14:26:51 -0700823 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900824 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700825 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700826 String[] naStrings = context.getResources().getStringArray(
827 com.android.internal.R.array.networkAttributes);
828 for (String naString : naStrings) {
829 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700830 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700831 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700832 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800833 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700834 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700835 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700836 }
Wink Saville51f456f2013-04-23 14:26:51 -0700837 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
838 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
839 n.type);
840 continue;
841 }
Wink Saville975c8482011-04-07 14:23:45 -0700842 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800843 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700844 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700845 continue;
846 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700847 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700848
Wink Saville975c8482011-04-07 14:23:45 -0700849 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700850 mNetworksDefined++;
851 } catch(Exception e) {
852 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700853 }
854 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700855
856 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
857 if (mNetConfigs[TYPE_VPN] == null) {
858 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
859 // don't need to add TYPE_VPN to mNetConfigs.
860 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
861 mNetworksDefined++; // used only in the log() statement below.
862 }
863
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900864 // Do the same for Ethernet, since it's often not specified in the configs, although many
865 // devices can use it via USB host adapters.
866 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
867 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
868 mNetworksDefined++;
869 }
870
Wink Saville5e56bc52013-07-29 15:00:57 -0700871 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700872
Robert Greenwalt50393202011-06-21 17:26:14 -0700873 mProtectedNetworks = new ArrayList<Integer>();
874 int[] protectedNetworks = context.getResources().getIntArray(
875 com.android.internal.R.array.config_protectedNetworks);
876 for (int p : protectedNetworks) {
877 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
878 mProtectedNetworks.add(p);
879 } else {
880 if (DBG) loge("Ignoring protectedNetwork " + p);
881 }
882 }
883
Erik Kline47222fc2017-04-30 19:36:15 +0900884 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800885
Luke Huang4e25ec62018-09-27 16:58:23 +0800886 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700887
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700888 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700889 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100890 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700891 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700892 intentFilter.addAction(Intent.ACTION_USER_ADDED);
893 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000894 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700895 mContext.registerReceiverAsUser(
896 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000897 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
898 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900899
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700900 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800901 mNMS.registerObserver(mTethering);
902 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700903 } catch (RemoteException e) {
904 loge("Error registering observer :" + e);
905 }
906
Erik Klineda4bfa82015-04-30 12:58:40 +0900907 mSettingsObserver = new SettingsObserver(mContext, mHandler);
908 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800909
Chalard Jean4133a122018-06-04 13:33:12 +0900910 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
911 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400912
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400913 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900914
915 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900916 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
917 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900918
919 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
920 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
921 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
922 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
923 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
924 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
925 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900926
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900927 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900928 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900929 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900930
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900931 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
932
Luke Huang4e25ec62018-09-27 16:58:23 +0800933 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900934 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700936
Erik Kline47222fc2017-04-30 19:36:15 +0900937 private Tethering makeTethering() {
938 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900939 final TetheringDependencies deps = new TetheringDependencies() {
940 @Override
941 public boolean isTetheringSupported() {
942 return ConnectivityService.this.isTetheringSupported();
943 }
Erik Kline72302902018-06-14 17:36:40 +0900944 @Override
945 public NetworkRequest getDefaultNetworkRequest() {
946 return mDefaultRequest;
947 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900948 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800949 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900950 IoThread.get().getLooper(), new MockableSystemProperties(),
951 deps);
952 }
953
Chalard Jean26400492018-04-18 20:18:38 +0900954 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
955 final NetworkCapabilities netCap = new NetworkCapabilities();
956 netCap.addCapability(NET_CAPABILITY_INTERNET);
957 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
958 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
959 netCap.setSingleUid(uid);
960 return netCap;
961 }
962
Chalard Jeandda156a2018-01-10 21:19:32 +0900963 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900964 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +0900965 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900966 netCap.addCapability(NET_CAPABILITY_INTERNET);
967 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900968 if (transportType > -1) {
969 netCap.addTransportType(transportType);
970 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900971 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900972 }
973
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900974 // Used only for testing.
975 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700976 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900977 // changing ContentResolver to make registerContentObserver non-final).
978 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
979 // by subclassing SettingsObserver.
980 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700981 void updateAlwaysOnNetworks() {
982 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900983 }
984
Erik Kline736353a2018-03-21 07:18:33 -0700985 // See FakeSettingsProvider comment above.
986 @VisibleForTesting
987 void updatePrivateDnsSettings() {
988 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
989 }
990
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700991 private void handleAlwaysOnNetworkRequest(
992 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900993 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700994 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
995 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +0900996 if (enable == isEnabled) {
997 return; // Nothing to do.
998 }
999
1000 if (enable) {
1001 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001002 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001003 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001004 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +09001005 }
1006 }
1007
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001008 private void handleConfigureAlwaysOnNetworks() {
1009 handleAlwaysOnNetworkRequest(
1010 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1011 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1012 false);
1013 }
1014
Erik Klineda4bfa82015-04-30 12:58:40 +09001015 private void registerSettingsCallbacks() {
1016 // Watch for global HTTP proxy changes.
1017 mSettingsObserver.observe(
1018 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1019 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1020
1021 // Watch for whether or not to keep mobile data always on.
1022 mSettingsObserver.observe(
1023 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001024 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1025
1026 // Watch for whether or not to keep wifi always on.
1027 mSettingsObserver.observe(
1028 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1029 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001030 }
1031
Erik Klinea24d4592018-01-11 21:07:29 +09001032 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001033 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1034 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001035 }
1036 }
1037
Robert Greenwalt34524f02014-05-18 16:22:10 -07001038 private synchronized int nextNetworkRequestId() {
1039 return mNextNetworkRequestId++;
1040 }
1041
Paul Jensen67b0b072015-06-10 11:22:17 -04001042 @VisibleForTesting
1043 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001044 synchronized (mNetworkForNetId) {
1045 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1046 int netId = mNextNetId;
1047 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1048 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001049 if (!mNetIdInUse.get(netId)) {
1050 mNetIdInUse.put(netId, true);
1051 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001052 }
1053 }
1054 }
1055 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001056 }
1057
Chalard Jeanc0982912018-06-07 16:11:34 +09001058 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001059 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001060 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1061 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001062 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001063 state = nai.getNetworkState();
1064 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001065 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001066 final NetworkInfo info = new NetworkInfo(networkType, 0,
1067 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001068 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1069 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001070 final NetworkCapabilities capabilities = new NetworkCapabilities();
1071 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1072 !info.isRoaming());
1073 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001074 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001075 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001076 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001077 return state;
1078 } else {
1079 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001080 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001081 }
1082
junyulai4a192e22018-06-13 15:00:37 +08001083 @VisibleForTesting
1084 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 if (network == null) {
1086 return null;
1087 }
Erik Kline736353a2018-03-21 07:18:33 -07001088 return getNetworkAgentInfoForNetId(network.netId);
1089 }
1090
1091 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001092 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001093 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001094 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001095 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001096
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001097 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001098 synchronized (mVpns) {
1099 if (!mLockdownEnabled) {
1100 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001101 Vpn vpn = mVpns.get(user);
1102 if (vpn != null && vpn.appliesToUid(uid)) {
1103 return vpn.getUnderlyingNetworks();
1104 }
1105 }
1106 }
1107 return null;
1108 }
1109
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001110 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001111 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001112
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001113 final Network[] networks = getVpnUnderlyingNetworks(uid);
1114 if (networks != null) {
1115 // getUnderlyingNetworks() returns:
1116 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1117 // empty array => the VPN explicitly said "no default network".
1118 // non-empty array => the VPN specified one or more default networks; we use the
1119 // first one.
1120 if (networks.length > 0) {
1121 nai = getNetworkAgentInfoForNetwork(networks[0]);
1122 } else {
1123 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001124 }
1125 }
1126
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001127 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001128 return nai.getNetworkState();
1129 } else {
1130 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001131 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001132 }
1133
1134 /**
1135 * Check if UID should be blocked from using the network with the given LinkProperties.
1136 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1138 boolean ignoreBlocked) {
1139 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001140 if (ignoreBlocked) {
1141 return false;
1142 }
Robin Lee17e61832016-05-09 13:46:28 +01001143 synchronized (mVpns) {
1144 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1145 if (vpn != null && vpn.isBlockingUid(uid)) {
1146 return true;
1147 }
1148 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001149 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001150 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 }
1152
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001153 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001154 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1155 return;
1156 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001157 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001158 synchronized (mBlockedAppUids) {
1159 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001160 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001161 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001162 blocked = false;
1163 } else {
1164 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001165 }
1166 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001167 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1168 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1169 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001170 }
1171
junyulai05986c62018-08-07 19:50:45 +08001172 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1173 boolean blocked) {
1174 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1175 return;
1176 }
1177 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1178 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1179 nri.mUid, nri.request.requestId, net.netId));
1180 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1181 }
1182
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001183 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1185 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001186 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001187 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001188 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001189 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1190
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001191 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001192 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001193 }
Hugo Benichi69744342017-11-27 10:57:16 +09001194 synchronized (mVpns) {
1195 if (mLockdownTracker != null) {
1196 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1197 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001198 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001199 }
1200
1201 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 * Return NetworkInfo for the active (i.e., connected) network interface.
1203 * It is assumed that at most one network is active at a time. If more
1204 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001205 * @return the info for the active network, or {@code null} if none is
1206 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001208 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001210 enforceAccessPermission();
1211 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001212 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001213 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001214 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1215 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
1217
Paul Jensen31a94f42015-02-13 14:18:39 -05001218 @Override
1219 public Network getActiveNetwork() {
1220 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001221 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001222 }
1223
1224 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001225 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001226 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001227 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001228 }
1229
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001230 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001231 final int user = UserHandle.getUserId(uid);
1232 int vpnNetId = NETID_UNSET;
1233 synchronized (mVpns) {
1234 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001235 // TODO : now that capabilities contain the UID, the appliesToUid test should
1236 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001237 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1238 }
1239 NetworkAgentInfo nai;
1240 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001241 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001242 if (nai != null) {
1243 final NetworkCapabilities requiredCaps =
1244 createDefaultNetworkCapabilitiesForUid(uid);
1245 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1246 return nai.network;
1247 }
1248 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001249 }
1250 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001251 if (nai != null
1252 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1253 nai = null;
1254 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001255 return nai != null ? nai.network : null;
1256 }
1257
Lorenzo Colitti18660282016-07-04 12:55:44 +09001258 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001259 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1260 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001261 final int uid = Binder.getCallingUid();
1262 NetworkState state = getUnfilteredActiveNetworkState(uid);
1263 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001264 }
1265
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001266 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001267 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001268 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001269 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001270 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001271 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001272 }
1273
1274 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 public NetworkInfo getNetworkInfo(int networkType) {
1276 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001277 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001278 if (getVpnUnderlyingNetworks(uid) != null) {
1279 // A VPN is active, so we may need to return one of its underlying networks. This
1280 // information is not available in LegacyTypeTracker, so we have to get it from
1281 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001282 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001283 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001284 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001285 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001286 }
1287 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001288 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001289 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001292 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001293 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001294 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001295 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001296 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001297 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001298 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001299 return state.networkInfo;
1300 } else {
1301 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001302 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001303 }
1304
1305 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 public NetworkInfo[] getAllNetworkInfo() {
1307 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001308 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001309 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1310 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001311 NetworkInfo info = getNetworkInfo(networkType);
1312 if (info != null) {
1313 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001316 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
1318
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001319 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001320 public Network getNetworkForType(int networkType) {
1321 enforceAccessPermission();
1322 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001323 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001324 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001325 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001326 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001327 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001328 }
1329
1330 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001331 public Network[] getAllNetworks() {
1332 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001334 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001335 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001336 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001337 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001338 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001339 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001340 }
1341
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001342 @Override
1343 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1344 // The basic principle is: if an app's traffic could possibly go over a
1345 // network, without the app doing anything multinetwork-specific,
1346 // (hence, by "default"), then include that network's capabilities in
1347 // the array.
1348 //
1349 // In the normal case, app traffic only goes over the system's default
1350 // network connection, so that's the only network returned.
1351 //
1352 // With a VPN in force, some app traffic may go into the VPN, and thus
1353 // over whatever underlying networks the VPN specifies, while other app
1354 // traffic may go over the system default network (e.g.: a split-tunnel
1355 // VPN, or an app disallowed by the VPN), so the set of networks
1356 // returned includes the VPN's underlying networks and the system
1357 // default.
1358 enforceAccessPermission();
1359
Chalard Jean4133a122018-06-04 13:33:12 +09001360 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001361
1362 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001363 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001364 if (nc != null) {
1365 result.put(nai.network, nc);
1366 }
1367
Hugo Benichi69744342017-11-27 10:57:16 +09001368 synchronized (mVpns) {
1369 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001370 Vpn vpn = mVpns.get(userId);
1371 if (vpn != null) {
1372 Network[] networks = vpn.getUnderlyingNetworks();
1373 if (networks != null) {
1374 for (Network network : networks) {
1375 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001376 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001377 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001378 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001379 }
1380 }
1381 }
1382 }
1383 }
1384 }
1385
1386 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1387 out = result.values().toArray(out);
1388 return out;
1389 }
1390
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001391 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001392 public boolean isNetworkSupported(int networkType) {
1393 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001394 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001395 }
1396
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001397 /**
1398 * Return LinkProperties for the active (i.e., connected) default
1399 * network interface. It is assumed that at most one default network
1400 * is active at a time. If more than one is active, it is indeterminate
1401 * which will be returned.
1402 * @return the ip properties for the active network, or {@code null} if
1403 * none is active
1404 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001405 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001406 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001407 enforceAccessPermission();
1408 final int uid = Binder.getCallingUid();
1409 NetworkState state = getUnfilteredActiveNetworkState(uid);
1410 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001411 }
1412
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001413 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001414 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001415 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001416 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1417 if (nai != null) {
1418 synchronized (nai) {
1419 return new LinkProperties(nai.linkProperties);
1420 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001421 }
1422 return null;
1423 }
1424
Robert Greenwalt12e67352014-05-13 21:41:06 -07001425 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001426 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001427 public LinkProperties getLinkProperties(Network network) {
1428 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001429 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1430 }
1431
1432 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1433 if (nai == null) {
1434 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001435 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001436 synchronized (nai) {
1437 return new LinkProperties(nai.linkProperties);
1438 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001439 }
1440
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001441 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001442 if (nai != null) {
1443 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001444 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001445 return networkCapabilitiesRestrictedForCallerPermissions(
1446 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001447 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001448 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001449 }
1450 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001451 return null;
1452 }
1453
1454 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001455 public NetworkCapabilities getNetworkCapabilities(Network network) {
1456 enforceAccessPermission();
1457 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1458 }
1459
Chalard Jeanb03a6222018-04-11 21:09:10 +09001460 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001461 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001462 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001463 if (!checkSettingsPermission(callerPid, callerUid)) {
1464 newNc.setUids(null);
1465 newNc.setSSID(null);
1466 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001467 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001468 }
1469
Chalard Jeanb552c462018-02-21 18:43:54 +09001470 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1471 if (!checkSettingsPermission()) {
1472 nc.setSingleUid(Binder.getCallingUid());
1473 }
1474 }
1475
Chalard Jean26aa91a2018-03-20 19:13:57 +09001476 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1477 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1478 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1479 }
1480 }
1481
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001482 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001483 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001484 // Require internal since we're handing out IMSI details
1485 enforceConnectivityInternalPermission();
1486
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001487 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001488 for (Network network : getAllNetworks()) {
1489 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1490 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001491 // TODO (b/73321673) : NetworkState contains a copy of the
1492 // NetworkCapabilities, which may contain UIDs of apps to which the
1493 // network applies. Should the UIDs be cleared so as not to leak or
1494 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001495 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001496 }
1497 }
1498 return result.toArray(new NetworkState[result.size()]);
1499 }
1500
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001501 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001502 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001503 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001504 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1505 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1506 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001507 }
1508
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001509 @Override
1510 public boolean isActiveNetworkMetered() {
1511 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001512
Eric Enslenc81ef192018-02-07 18:03:53 -08001513 final int uid = Binder.getCallingUid();
1514 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001515 if (caps != null) {
1516 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1517 } else {
1518 // Always return the most conservative value
1519 return true;
1520 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001521 }
1522
Jeff Sharkey216c1812012-08-05 14:29:23 -07001523 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1524 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001525 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001526 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001527 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001528 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001529 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001530
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001531 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001532 * Ensures that the system cannot call a particular method.
1533 */
1534 private boolean disallowedBecauseSystemCaller() {
1535 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1536 // requestRouteToHost.
1537 if (isSystem(Binder.getCallingUid())) {
1538 log("This method exists only for app backwards compatibility"
1539 + " and must not be called by system services.");
1540 return true;
1541 }
1542 return false;
1543 }
1544
1545 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 * Ensure that a network route exists to deliver traffic to the specified
1547 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001548 * @param networkType the type of the network over which traffic to the
1549 * specified host is to be routed
1550 * @param hostAddress the IP address of the host to which the route is
1551 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 * @return {@code true} on success, {@code false} on failure
1553 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001554 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001555 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001556 if (disallowedBecauseSystemCaller()) {
1557 return false;
1558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001560 if (mProtectedNetworks.contains(networkType)) {
1561 enforceConnectivityInternalPermission();
1562 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001563
Chad Brubakerc0234532014-02-14 13:24:29 -08001564 InetAddress addr;
1565 try {
1566 addr = InetAddress.getByAddress(hostAddress);
1567 } catch (UnknownHostException e) {
1568 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1569 return false;
1570 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001573 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 return false;
1575 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001576
1577 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1578 if (nai == null) {
1579 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1580 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1581 } else {
1582 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1583 }
1584 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001585 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001586
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001587 DetailedState netState;
1588 synchronized (nai) {
1589 netState = nai.networkInfo.getDetailedState();
1590 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001591
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001592 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001593 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001594 log("requestRouteToHostAddress on down network "
1595 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001596 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001597 }
1598 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001600
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001601 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001602 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001603 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001604 LinkProperties lp;
1605 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001606 synchronized (nai) {
1607 lp = nai.linkProperties;
1608 netId = nai.network.netId;
1609 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001610 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001611 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1612 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001613 } finally {
1614 Binder.restoreCallingIdentity(token);
1615 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001616 }
1617
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001618 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001619 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001620 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001621 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001622 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001623 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001624 if (bestRoute.getGateway().equals(addr)) {
1625 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001626 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001627 } else {
1628 // if we will connect to this through another route, add a direct route
1629 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001630 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001631 }
1632 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001633 if (DBG) log("Adding legacy route " + bestRoute +
1634 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001635 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001636 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001637 } catch (Exception e) {
1638 // never crash - catch them all
1639 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001640 return false;
1641 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001642 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644
dalyk7301aa42018-03-05 12:42:22 -05001645 @VisibleForTesting
1646 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1647 @Override
1648 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1649 String hostname, boolean validated) {
1650 try {
1651 mHandler.sendMessage(mHandler.obtainMessage(
1652 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1653 new PrivateDnsValidationUpdate(netId,
1654 InetAddress.parseNumericAddress(ipAddress),
1655 hostname, validated)));
1656 } catch (IllegalArgumentException e) {
1657 loge("Error parsing ip address in validation event");
1658 }
1659 }
1660 };
1661
1662 @VisibleForTesting
1663 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001664 final IIpConnectivityMetrics ipConnectivityMetrics =
1665 IIpConnectivityMetrics.Stub.asInterface(
1666 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1667 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001668 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001669 return;
dalyk7301aa42018-03-05 12:42:22 -05001670 }
1671
1672 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001673 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001674 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1675 mNetdEventCallback);
1676 } catch (Exception e) {
1677 loge("Error registering netd callback: " + e);
1678 }
1679 }
1680
Jeff Sharkey75d31892018-01-18 22:01:59 +09001681 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001682 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001683 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001684 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001685 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001686 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001687 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001688 // caller is NPMS, since we only register with them
1689 if (LOGD_BLOCKED_NETWORKINFO) {
1690 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1691 }
1692 mHandler.sendMessage(mHandler.obtainMessage(
1693 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1694
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001695 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001696 if (restrictBackground) {
1697 log("onRestrictBackgroundChanged(true): disabling tethering");
1698 mTethering.untetherAll();
1699 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001700 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001701 };
1702
junyulai05986c62018-08-07 19:50:45 +08001703 void handleUidRulesChanged(int uid, int newRules) {
1704 // skip update when we've already applied rules
1705 final int oldRules = mUidRules.get(uid, RULE_NONE);
1706 if (oldRules == newRules) return;
1707
1708 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1709
1710 if (newRules == RULE_NONE) {
1711 mUidRules.delete(uid);
1712 } else {
1713 mUidRules.put(uid, newRules);
1714 }
1715 }
1716
1717 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1718 if (mRestrictBackground == restrictBackground) return;
1719
1720 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1721 final boolean curMetered = nai.networkCapabilities.isMetered();
1722 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1723 restrictBackground);
1724 }
1725
1726 mRestrictBackground = restrictBackground;
1727 }
1728
1729 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1730 boolean isBackgroundRestricted) {
1731 synchronized (mVpns) {
1732 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1733 // Because the return value of this function depends on the list of UIDs the
1734 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1735 // list all state depending on the return value of this function has to be recomputed.
1736 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1737 // send the necessary onBlockedStatusChanged callbacks.
1738 if (vpn != null && vpn.isBlockingUid(uid)) {
1739 return true;
1740 }
1741 }
1742
1743 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1744 isNetworkMetered, isBackgroundRestricted);
1745 }
1746
Robin Lee3b3dd942015-05-12 18:14:58 +01001747 /**
1748 * Require that the caller is either in the same user or has appropriate permission to interact
1749 * across users.
1750 *
1751 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1752 */
1753 private void enforceCrossUserPermission(int userId) {
1754 if (userId == UserHandle.getCallingUserId()) {
1755 // Not a cross-user call.
1756 return;
1757 }
1758 mContext.enforceCallingOrSelfPermission(
1759 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1760 "ConnectivityService");
1761 }
1762
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001763 private void enforceInternetPermission() {
1764 mContext.enforceCallingOrSelfPermission(
1765 android.Manifest.permission.INTERNET,
1766 "ConnectivityService");
1767 }
1768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001770 mContext.enforceCallingOrSelfPermission(
1771 android.Manifest.permission.ACCESS_NETWORK_STATE,
1772 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774
1775 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001776 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
1778
Charles He36738632017-05-15 17:07:18 +01001779 private void enforceSettingsPermission() {
1780 mContext.enforceCallingOrSelfPermission(
1781 android.Manifest.permission.NETWORK_SETTINGS,
1782 "ConnectivityService");
1783 }
1784
Chalard Jeanb552c462018-02-21 18:43:54 +09001785 private boolean checkSettingsPermission() {
1786 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1787 android.Manifest.permission.NETWORK_SETTINGS);
1788 }
1789
1790 private boolean checkSettingsPermission(int pid, int uid) {
1791 return PERMISSION_GRANTED == mContext.checkPermission(
1792 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1793 }
1794
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001795 private void enforceTetherAccessPermission() {
1796 mContext.enforceCallingOrSelfPermission(
1797 android.Manifest.permission.ACCESS_NETWORK_STATE,
1798 "ConnectivityService");
1799 }
1800
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001801 private void enforceConnectivityInternalPermission() {
1802 mContext.enforceCallingOrSelfPermission(
1803 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1804 "ConnectivityService");
1805 }
1806
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001807 private boolean checkNetworkStackPermission() {
1808 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1809 android.Manifest.permission.NETWORK_STACK);
1810 }
1811
Hugo Benichi514da602016-07-19 15:59:27 +09001812 private void enforceConnectivityRestrictedNetworksPermission() {
1813 try {
1814 mContext.enforceCallingOrSelfPermission(
1815 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1816 "ConnectivityService");
1817 return;
1818 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1819 enforceConnectivityInternalPermission();
1820 }
1821
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001822 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001823 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001824 }
1825
Lorenzo Colitti18660282016-07-04 12:55:44 +09001826 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001827 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001828 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001829 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001830 }
1831
1832 private void sendInetConditionBroadcast(NetworkInfo info) {
1833 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1834 }
1835
Wink Saville628b0852011-08-04 15:01:58 -07001836 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001837 synchronized (mVpns) {
1838 if (mLockdownTracker != null) {
1839 info = new NetworkInfo(info);
1840 mLockdownTracker.augmentNetworkInfo(info);
1841 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001842 }
1843
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001844 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001845 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001846 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 if (info.isFailover()) {
1848 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1849 info.setFailover(false);
1850 }
1851 if (info.getReason() != null) {
1852 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1853 }
1854 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001855 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1856 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001858 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001859 return intent;
1860 }
1861
1862 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1863 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1864 }
1865
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001866 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001867 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1868 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1869 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001870 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001871 final long ident = Binder.clearCallingIdentity();
1872 try {
1873 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1874 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1875 } finally {
1876 Binder.restoreCallingIdentity(ident);
1877 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001878 }
1879
Mike Lockwood0f79b542009-08-14 14:18:49 -04001880 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001881 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001882 if (!mSystemReady) {
1883 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001884 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001885 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001886 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001887 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001888 }
1889
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001890 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001891 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001892 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001893 final NetworkInfo ni = intent.getParcelableExtra(
1894 ConnectivityManager.EXTRA_NETWORK_INFO);
1895 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1896 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1897 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001898 } else {
1899 BroadcastOptions opts = BroadcastOptions.makeBasic();
1900 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1901 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001902 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001903 final IBatteryStats bs = BatteryStatsService.getService();
1904 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001905 bs.noteConnectivityChanged(intent.getIntExtra(
1906 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001907 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001908 } catch (RemoteException e) {
1909 }
Chad Brubakerac925012018-03-08 10:37:09 -08001910 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001911 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001912 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001913 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001914 } finally {
1915 Binder.restoreCallingIdentity(ident);
1916 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001917 }
1918 }
1919
1920 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09001921 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001922 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001923
Hugo Benichi20035e02017-04-26 14:53:28 +09001924 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001925 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001926 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001927 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001928 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001929 }
1930 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001931 // load the global proxy at startup
1932 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001933
Robin Lee244ce8e2016-01-05 18:03:46 +00001934 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1935 // for user to unlock device too.
1936 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001937
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001938 // Create network requests for always-on networks.
1939 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09001940
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001941 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001942
1943 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001947 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001948 *
1949 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001950 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001951 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001952 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1953 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001954
1955 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001956 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001957
Robert Greenwalt7b816022014-04-18 15:25:25 -07001958 if (networkAgent.networkCapabilities.hasTransport(
1959 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001960 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1961 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001962 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001963 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001964 } else if (networkAgent.networkCapabilities.hasTransport(
1965 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001966 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1967 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001968 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001969 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001970 } else {
1971 // do not track any other networks
1972 timeout = 0;
1973 }
1974
Robert Greenwalt7b816022014-04-18 15:25:25 -07001975 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001976 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001977 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001978 } catch (Exception e) {
1979 // You shall not crash!
1980 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001981 }
1982 }
1983 }
1984
1985 /**
1986 * Remove data activity tracking when network disconnects.
1987 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001988 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1989 final String iface = networkAgent.linkProperties.getInterfaceName();
1990 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001991
Robert Greenwalt7b816022014-04-18 15:25:25 -07001992 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1993 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001994 try {
Chalard Jean4d660112018-06-04 16:52:49 +09001995 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08001996 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001997 } catch (Exception e) {
1998 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001999 }
2000 }
2001 }
2002
2003 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002004 * Update data activity tracking when network state is updated.
2005 */
2006 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2007 NetworkAgentInfo oldNetwork) {
2008 if (newNetwork != null) {
2009 setupDataActivityTracking(newNetwork);
2010 }
2011 if (oldNetwork != null) {
2012 removeDataActivityTracking(oldNetwork);
2013 }
2014 }
2015 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002016 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002017 * and set it on it's iface.
2018 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002019 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2020 final String iface = newLp.getInterfaceName();
2021 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002022 if (oldLp == null && mtu == 0) {
2023 // Silently ignore unset MTU value.
2024 return;
2025 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002026 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2027 if (VDBG) log("identical MTU - not setting");
2028 return;
2029 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002030 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002031 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 return;
2033 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002034
w1997615afd812014-08-05 15:18:11 -07002035 // Cannot set MTU without interface name
2036 if (TextUtils.isEmpty(iface)) {
2037 loge("Setting MTU size with null iface.");
2038 return;
2039 }
2040
Robert Greenwalt7b816022014-04-18 15:25:25 -07002041 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002042 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002043 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002044 } catch (Exception e) {
2045 Slog.e(TAG, "exception in setMtu()" + e);
2046 }
2047 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002048
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002049 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002050 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2051
2052 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002053 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002054 protected MockableSystemProperties getSystemProperties() {
2055 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002056 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002057
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002058 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
2059 if (isDefaultNetwork(nai) == false) {
2060 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002061 }
2062
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002063 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
2064 String[] values = null;
2065 if (tcpBufferSizes != null) {
2066 values = tcpBufferSizes.split(",");
2067 }
2068
2069 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002070 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002071 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2072 values = tcpBufferSizes.split(",");
2073 }
2074
2075 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2076
2077 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002078 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002079
2080 final String prefix = "/sys/kernel/ipv4/tcp_";
2081 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2082 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2083 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2084 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2085 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2086 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2087 mCurrentTcpBufferSizes = tcpBufferSizes;
2088 } catch (IOException e) {
2089 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002090 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002091
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002092 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002093 Settings.Global.TCP_DEFAULT_INIT_RWND,
2094 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002095 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2096 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002097 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002098 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002099 }
2100
Robert Greenwalt562cc542014-05-15 18:07:26 -07002101 @Override
2102 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002103 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002104 NETWORK_RESTORE_DELAY_PROP_NAME);
2105 if(restoreDefaultNetworkDelayStr != null &&
2106 restoreDefaultNetworkDelayStr.length() != 0) {
2107 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002108 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002109 } catch (NumberFormatException e) {
2110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002112 // if the system property isn't set, use the value for the apn type
2113 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2114
2115 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2116 (mNetConfigs[networkType] != null)) {
2117 ret = mNetConfigs[networkType].restoreTime;
2118 }
2119 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002122 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2123 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2124 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002125 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002126 // Start gathering diagnostic information.
2127 netDiags.add(new NetworkDiagnostics(
2128 nai.network,
2129 new LinkProperties(nai.linkProperties), // Must be a copy.
2130 DIAG_TIME_MS));
2131 }
2132
2133 for (NetworkDiagnostics netDiag : netDiags) {
2134 pw.println();
2135 netDiag.waitForMeasurements();
2136 netDiag.dump(pw);
2137 }
2138 }
2139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002141 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002142 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2143 }
2144
2145 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002146 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002147 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002148 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002149
Erik Kline3f8306b2018-05-01 16:51:44 +09002150 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002151 dumpNetworkDiagnostics(pw);
2152 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002153 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002154 mTethering.dump(fd, pw, args);
2155 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002156 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2157 dumpNetworks(pw);
2158 return;
2159 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2160 dumpNetworkRequests(pw);
2161 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002162 }
Erik Kline379747a2015-06-05 17:47:34 +09002163
Lorenzo Colittie3805462015-06-03 11:18:24 +09002164 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002165 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002166 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002167 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002168 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002169 pw.println();
2170
Paul Jensen85cf78e2015-06-25 13:25:07 -04002171 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002172 pw.print("Active default network: ");
2173 if (defaultNai == null) {
2174 pw.println("none");
2175 } else {
2176 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002178 pw.println();
2179
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002180 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002181 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002182 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002183 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002184 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002185
junyulai05986c62018-08-07 19:50:45 +08002186 pw.print("Restrict background: ");
2187 pw.println(mRestrictBackground);
2188 pw.println();
2189
2190 pw.println("Status for known UIDs:");
2191 pw.increaseIndent();
2192 final int size = mUidRules.size();
2193 for (int i = 0; i < size; i++) {
2194 // Don't crash if the array is modified while dumping in bugreports.
2195 try {
2196 final int uid = mUidRules.keyAt(i);
2197 final int uidRules = mUidRules.get(uid, RULE_NONE);
2198 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2199 } catch (ArrayIndexOutOfBoundsException e) {
2200 pw.println(" ArrayIndexOutOfBoundsException");
2201 } catch (ConcurrentModificationException e) {
2202 pw.println(" ConcurrentModificationException");
2203 }
2204 }
2205 pw.println();
2206 pw.decreaseIndent();
2207
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002208 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002209 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002210 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002211 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002212 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002213
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002214 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002215
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002216 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002217 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002218
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002219 pw.println();
2220 mKeepaliveTracker.dump(pw);
2221
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002222 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002223 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002224
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002225 pw.println();
2226 mMultipathPolicyTracker.dump(pw);
2227
Erik Kline3f8306b2018-05-01 16:51:44 +09002228 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002229 pw.println();
2230 synchronized (mValidationLogs) {
2231 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002232 for (ValidationLog p : mValidationLogs) {
Chalard Jeand771aa02018-04-26 16:16:10 +09002233 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002234 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002235 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002236 pw.decreaseIndent();
2237 }
2238 }
Erik Kline7523eb32015-07-09 18:24:03 +09002239
2240 pw.println();
2241 pw.println("mNetworkRequestInfoLogs (most recent first):");
2242 pw.increaseIndent();
2243 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2244 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002245
2246 pw.println();
2247 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2248 pw.increaseIndent();
2249 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2250 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002251
2252 pw.println();
2253 pw.println("NetTransition WakeLock activity (most recent first):");
2254 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002255 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2256 pw.println("total releases: " + mTotalWakelockReleases);
2257 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2258 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2259 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2260 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2261 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2262 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002263 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002264
2265 pw.println();
2266 pw.println("bandwidth update requests (by uid):");
2267 pw.increaseIndent();
2268 synchronized (mBandwidthRequests) {
2269 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2270 pw.println("[" + mBandwidthRequests.keyAt(i)
2271 + "]: " + mBandwidthRequests.valueAt(i));
2272 }
2273 }
2274 pw.decreaseIndent();
2275
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002276 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 }
2279
Hugo Benichi14683812018-09-03 08:32:56 +09002280 private void dumpNetworks(IndentingPrintWriter pw) {
2281 for (NetworkAgentInfo nai : networksSortedById()) {
2282 pw.println(nai.toString());
2283 pw.increaseIndent();
2284 pw.println(String.format(
2285 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2286 nai.numForegroundNetworkRequests(),
2287 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2288 nai.numBackgroundNetworkRequests(),
2289 nai.numNetworkRequests()));
2290 pw.increaseIndent();
2291 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2292 pw.println(nai.requestAt(i).toString());
2293 }
2294 pw.decreaseIndent();
2295 pw.println("Lingered:");
2296 pw.increaseIndent();
2297 nai.dumpLingerTimers(pw);
2298 pw.decreaseIndent();
2299 pw.decreaseIndent();
2300 }
2301 }
2302
2303 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2304 for (NetworkRequestInfo nri : requestsSortedById()) {
2305 pw.println(nri.toString());
2306 }
2307 }
2308
Hugo Benichia2a917c2018-09-03 08:19:02 +09002309 /**
2310 * Return an array of all current NetworkAgentInfos sorted by network id.
2311 */
2312 private NetworkAgentInfo[] networksSortedById() {
2313 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2314 networks = mNetworkAgentInfos.values().toArray(networks);
2315 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2316 return networks;
2317 }
2318
2319 /**
2320 * Return an array of all current NetworkRequest sorted by request id.
2321 */
2322 private NetworkRequestInfo[] requestsSortedById() {
2323 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2324 requests = mNetworkRequests.values().toArray(requests);
2325 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2326 return requests;
2327 }
2328
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002329 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002330 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002331 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002332 if (officialNai != null && officialNai.equals(nai)) return true;
2333 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002334 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002335 " - " + nai);
2336 }
2337 return false;
2338 }
2339
Robert Greenwalt42acef32009-08-12 16:08:25 -07002340 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002341 private class NetworkStateTrackerHandler extends Handler {
2342 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002343 super(looper);
2344 }
2345
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002346 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002348 default:
2349 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002350 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002351 handleAsyncChannelHalfConnect(msg);
2352 break;
2353 }
2354 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2355 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2356 if (nai != null) nai.asyncChannel.disconnect();
2357 break;
2358 }
2359 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2360 handleAsyncChannelDisconnected(msg);
2361 break;
2362 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002363 }
2364 return true;
2365 }
2366
2367 private void maybeHandleNetworkAgentMessage(Message msg) {
2368 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2369 if (nai == null) {
2370 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002371 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002372 }
2373 return;
2374 }
2375
2376 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002377 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002378 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2379 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002380 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2381 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002382 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002383 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002384 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002385 break;
2386 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002387 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002388 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002389 break;
2390 }
2391 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002392 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002393 updateNetworkInfo(nai, info);
2394 break;
2395 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002396 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002397 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002398 break;
2399 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002400 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002401 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2402 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002403 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002404 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002405 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002406 break;
2407 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002408 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002409 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2410 break;
2411 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002412 }
2413 }
2414
2415 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2416 switch (msg.what) {
2417 default:
2418 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002419 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002420 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002421 if (nai == null) break;
2422
2423 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2424 final boolean wasValidated = nai.lastValidated;
2425 final boolean wasDefault = isDefaultNetwork(nai);
2426
Erik Klinea24d4592018-01-11 21:07:29 +09002427 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2428
Erik Klinea24d4592018-01-11 21:07:29 +09002429 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002430 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2431 ? " with redirect to " + redirectUrl
2432 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002433 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2434 }
Erik Klinea24d4592018-01-11 21:07:29 +09002435 if (valid != nai.lastValidated) {
2436 if (wasDefault) {
2437 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2438 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002439 }
Erik Klinea24d4592018-01-11 21:07:29 +09002440 final int oldScore = nai.getCurrentScore();
2441 nai.lastValidated = valid;
2442 nai.everValidated |= valid;
2443 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2444 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2445 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Erik Klinec6d00222018-06-26 18:53:43 +09002446 if (valid) handleFreshlyValidatedNetwork(nai);
Erik Klinea24d4592018-01-11 21:07:29 +09002447 }
2448 updateInetCondition(nai);
2449 // Let the NetworkAgent know the state of its network
2450 Bundle redirectUrlBundle = new Bundle();
2451 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2452 nai.asyncChannel.sendMessage(
2453 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2454 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2455 0, redirectUrlBundle);
2456 if (wasValidated && !nai.lastValidated) {
2457 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002458 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002459 break;
2460 }
Paul Jensen869868be2014-05-15 10:33:05 -04002461 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002462 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002463 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002464 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002465 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002466 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002467 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002468 nai.lastCaptivePortalDetected = visible;
2469 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002470 if (nai.lastCaptivePortalDetected &&
2471 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2472 if (DBG) log("Avoiding captive portal network: " + nai.name());
2473 nai.asyncChannel.sendMessage(
2474 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2475 teardownUnneededNetwork(nai);
2476 break;
2477 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002478 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002479 }
2480 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002481 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002482 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002483 if (nai == null) {
2484 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2485 break;
2486 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002487 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002488 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002489 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002490 }
Paul Jensen869868be2014-05-15 10:33:05 -04002491 }
Paul Jensen869868be2014-05-15 10:33:05 -04002492 break;
2493 }
Erik Klinea24d4592018-01-11 21:07:29 +09002494 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002495 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002496 if (nai == null) break;
2497
Erik Kline736353a2018-03-21 07:18:33 -07002498 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002499 break;
2500 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002501 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002502 return true;
2503 }
2504
Calvin Onbe96da12016-10-11 15:10:46 -07002505 private int getCaptivePortalMode() {
2506 return Settings.Global.getInt(mContext.getContentResolver(),
2507 Settings.Global.CAPTIVE_PORTAL_MODE,
2508 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2509 }
2510
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002511 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2512 switch (msg.what) {
2513 default:
2514 return false;
2515 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2516 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2517 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2518 handleLingerComplete(nai);
2519 }
2520 break;
2521 }
2522 }
2523 return true;
2524 }
2525
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002526 @Override
2527 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002528 if (!maybeHandleAsyncChannelMessage(msg) &&
2529 !maybeHandleNetworkMonitorMessage(msg) &&
2530 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002531 maybeHandleNetworkAgentMessage(msg);
2532 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002533 }
2534 }
2535
Erik Kline736353a2018-03-21 07:18:33 -07002536 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2537 return NetworkMonitor.isValidationRequired(
2538 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2539 }
2540
Erik Klinec6d00222018-06-26 18:53:43 +09002541 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2542 if (nai == null) return;
2543 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2544 // in order to restart a validation pass from within netd.
2545 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2546 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2547 updateDnses(nai.linkProperties, null, nai.network.netId);
2548 }
2549 }
2550
Erik Klinea24d4592018-01-11 21:07:29 +09002551 private void handlePrivateDnsSettingsChanged() {
2552 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2553
2554 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002555 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002556 if (networkRequiresValidation(nai)) {
2557 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2558 }
Erik Klinea24d4592018-01-11 21:07:29 +09002559 }
2560 }
2561
Erik Kline736353a2018-03-21 07:18:33 -07002562 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2563 // Private DNS only ever applies to networks that might provide
2564 // Internet access and therefore also require validation.
2565 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002566
Erik Kline736353a2018-03-21 07:18:33 -07002567 // Notify the NetworkMonitor thread in case it needs to cancel or
2568 // schedule DNS resolutions. If a DNS resolution is required the
2569 // result will be sent back to us.
2570 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2571
2572 // With Private DNS bypass support, we can proceed to update the
2573 // Private DNS config immediately, even if we're in strict mode
2574 // and have not yet resolved the provider name into a set of IPs.
2575 updatePrivateDns(nai, cfg);
2576 }
2577
2578 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2579 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002580 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002581 }
2582
dalyk7301aa42018-03-05 12:42:22 -05002583 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2584 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2585 if (nai == null) {
2586 return;
2587 }
2588 mDnsManager.updatePrivateDnsValidation(update);
2589 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2590 }
2591
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002592 private void updateLingerState(NetworkAgentInfo nai, long now) {
2593 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2594 // 2. If the network was lingering and there are now requests, unlinger it.
2595 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2596 // one lingered request, start lingering.
2597 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002598 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002599 if (DBG) log("Unlingering " + nai.name());
2600 nai.unlinger();
2601 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002602 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002603 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002604 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002605 nai.linger();
2606 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2607 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2608 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002609 }
2610
Robert Greenwalt7b816022014-04-18 15:25:25 -07002611 private void handleAsyncChannelHalfConnect(Message msg) {
2612 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002613 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002614 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2615 if (VDBG) log("NetworkFactory connected");
2616 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002617 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002618 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002619 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002620 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002621 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002622 }
2623 } else {
2624 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002625 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002626 }
2627 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2628 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2629 if (VDBG) log("NetworkAgent connected");
2630 // A network agent has requested a connection. Establish the connection.
2631 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2632 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2633 } else {
2634 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002635 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002636 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002637 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002638 synchronized (mNetworkForNetId) {
2639 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002640 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002641 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002642 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002643 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002644 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002645 }
2646 }
2647 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002648
Chalard Jean392971c2018-05-11 20:19:20 +09002649 // This is a no-op if it's called with a message designating a network that has
2650 // already been destroyed, because its reference will not be found in the relevant
2651 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002652 private void handleAsyncChannelDisconnected(Message msg) {
2653 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2654 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002655 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002656 } else {
2657 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2658 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002659 }
2660 }
2661
Chalard Jean392971c2018-05-11 20:19:20 +09002662 // Destroys a network, remove references to it from the internal state managed by
2663 // ConnectivityService, free its interfaces and clean up.
2664 // Must be called on the Handler thread.
2665 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2666 if (DBG) {
2667 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2668 }
2669 // A network agent has disconnected.
2670 // TODO - if we move the logic to the network agent (have them disconnect
2671 // because they lost all their requests or because their score isn't good)
2672 // then they would disconnect organically, report their new state and then
2673 // disconnect the channel.
2674 if (nai.networkInfo.isConnected()) {
2675 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2676 null, null);
2677 }
2678 final boolean wasDefault = isDefaultNetwork(nai);
2679 if (wasDefault) {
2680 mDefaultInetConditionPublished = 0;
2681 // Log default network disconnection before required book-keeping.
2682 // Let rematchAllNetworksAndRequests() below record a new default network event
2683 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2684 // whose timestamps tell how long it takes to recover a default network.
2685 long now = SystemClock.elapsedRealtime();
2686 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2687 }
2688 notifyIfacesChangedForNetworkStats();
2689 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2690 // by other networks that are already connected. Perhaps that can be done by
2691 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2692 // of rematchAllNetworksAndRequests
2693 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2694 mKeepaliveTracker.handleStopAllKeepalives(nai,
2695 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2696 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2697 // Disable wakeup packet monitoring for each interface.
2698 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2699 }
2700 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2701 mNetworkAgentInfos.remove(nai.messenger);
2702 nai.maybeStopClat();
2703 synchronized (mNetworkForNetId) {
2704 // Remove the NetworkAgent, but don't mark the netId as
2705 // available until we've told netd to delete it below.
2706 mNetworkForNetId.remove(nai.network.netId);
2707 }
2708 // Remove all previously satisfied requests.
2709 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2710 NetworkRequest request = nai.requestAt(i);
2711 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2712 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2713 clearNetworkForRequest(request.requestId);
2714 sendUpdatedScoreToFactories(request, 0);
2715 }
2716 }
2717 nai.clearLingerState();
2718 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002719 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002720 notifyLockdownVpn(nai);
2721 ensureNetworkTransitionWakelock(nai.name());
2722 }
2723 mLegacyTypeTracker.remove(nai, wasDefault);
2724 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2725 updateAllVpnsCapabilities();
2726 }
2727 rematchAllNetworksAndRequests(null, 0);
2728 mLingerMonitor.noteDisconnect(nai);
2729 if (nai.created) {
2730 // Tell netd to clean up the configuration for this network
2731 // (routing rules, DNS, etc).
2732 // This may be slow as it requires a lot of netd shelling out to ip and
2733 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2734 // after we've rematched networks with requests which should make a potential
2735 // fallback network the default or requested a new network from the
2736 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2737 // long time.
2738 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002739 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002740 } catch (Exception e) {
2741 loge("Exception removing network: " + e);
2742 }
2743 mDnsManager.removeNetwork(nai.network);
2744 }
2745 synchronized (mNetworkForNetId) {
2746 mNetIdInUse.delete(nai.network.netId);
2747 }
2748 }
2749
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002750 // If this method proves to be too slow then we can maintain a separate
2751 // pendingIntent => NetworkRequestInfo map.
2752 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2753 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2754 Intent intent = pendingIntent.getIntent();
2755 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2756 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2757 if (existingPendingIntent != null &&
2758 existingPendingIntent.getIntent().filterEquals(intent)) {
2759 return entry.getValue();
2760 }
2761 }
2762 return null;
2763 }
2764
2765 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2766 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2767
2768 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2769 if (existingRequest != null) { // remove the existing request.
2770 if (DBG) log("Replacing " + existingRequest.request + " with "
2771 + nri.request + " because their intents matched.");
2772 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2773 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002774 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002775 }
2776
Erik Klineda4bfa82015-04-30 12:58:40 +09002777 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002778 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002779 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002780 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002781 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002782 if (nri.request.networkCapabilities.hasSignalStrength() &&
2783 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2784 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002785 }
2786 }
2787 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002788 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002789 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002790 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002791 }
2792 }
2793
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002794 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2795 int callingUid) {
2796 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2797 if (nri != null) {
2798 handleReleaseNetworkRequest(nri.request, callingUid);
2799 }
2800 }
2801
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002802 // Determines whether the network is the best (or could become the best, if it validated), for
2803 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2804 // on the value of reason:
2805 //
2806 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2807 // then it should be torn down.
2808 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2809 // then it should be lingered.
2810 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2811 final int numRequests;
2812 switch (reason) {
2813 case TEARDOWN:
2814 numRequests = nai.numRequestNetworkRequests();
2815 break;
2816 case LINGER:
2817 numRequests = nai.numForegroundNetworkRequests();
2818 break;
2819 default:
2820 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2821 return true;
2822 }
2823
2824 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002825 return false;
2826 }
Paul Jensene0988542015-06-25 15:30:08 -04002827 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002828 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2829 // Background requests don't affect lingering.
2830 continue;
2831 }
2832
Paul Jensene0988542015-06-25 15:30:08 -04002833 // If this Network is already the highest scoring Network for a request, or if
2834 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002835 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002836 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002837 // Note that this catches two important cases:
2838 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2839 // is currently satisfying the request. This is desirable when
2840 // cellular ends up validating but WiFi does not.
2841 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002842 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002843 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002844 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002845 nai.getCurrentScoreAsValidated())) {
2846 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002847 }
2848 }
Paul Jensene0988542015-06-25 15:30:08 -04002849 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002850 }
2851
Erik Klineacdd6392016-07-07 16:50:58 +09002852 private NetworkRequestInfo getNriForAppRequest(
2853 NetworkRequest request, int callingUid, String requestedOperation) {
2854 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2855
Robert Greenwalt9258c642014-03-26 16:47:06 -07002856 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002857 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002858 log(String.format("UID %d attempted to %s for unowned request %s",
2859 callingUid, requestedOperation, nri));
2860 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002861 }
Erik Klineacdd6392016-07-07 16:50:58 +09002862 }
2863
2864 return nri;
2865 }
2866
Erik Kline57faba92015-11-25 12:49:38 +09002867 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002868 if (mNetworkRequests.get(nri.request) == null) {
2869 return;
Erik Kline57faba92015-11-25 12:49:38 +09002870 }
Hugo Benichicd952782017-09-20 11:20:14 +09002871 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002872 return;
2873 }
2874 if (VDBG || (DBG && nri.request.isRequest())) {
2875 log("releasing " + nri.request + " (timeout)");
2876 }
2877 handleRemoveNetworkRequest(nri);
2878 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002879 }
2880
Erik Klineacdd6392016-07-07 16:50:58 +09002881 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002882 final NetworkRequestInfo nri =
2883 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2884 if (nri == null) {
2885 return;
Erik Kline57faba92015-11-25 12:49:38 +09002886 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002887 if (VDBG || (DBG && nri.request.isRequest())) {
2888 log("releasing " + nri.request + " (release request)");
2889 }
2890 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002891 }
Erik Klineacdd6392016-07-07 16:50:58 +09002892
Hugo Benichidba33db2017-03-23 22:40:44 +09002893 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002894 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002895 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002896
Erik Klineacdd6392016-07-07 16:50:58 +09002897 synchronized (mUidToNetworkRequestCount) {
2898 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2899 if (requests < 1) {
2900 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2901 nri.mUid);
2902 } else if (requests == 1) {
2903 mUidToNetworkRequestCount.removeAt(
2904 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2905 } else {
2906 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2907 }
2908 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002909
Erik Klineacdd6392016-07-07 16:50:58 +09002910 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2911 if (nri.request.isRequest()) {
2912 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002913 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002914 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002915 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002916 nai.removeRequest(nri.request.requestId);
2917 if (VDBG) {
2918 log(" Removing from current network " + nai.name() +
2919 ", leaving " + nai.numNetworkRequests() + " requests.");
2920 }
2921 // If there are still lingered requests on this network, don't tear it down,
2922 // but resume lingering instead.
2923 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002924 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002925 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2926 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002927 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002928 wasKept = true;
2929 }
Hugo Benichicd952782017-09-20 11:20:14 +09002930 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002931 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2932 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002933 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002934 }
Erik Klineacdd6392016-07-07 16:50:58 +09002935 }
2936
Erik Klineacdd6392016-07-07 16:50:58 +09002937 // Maintain the illusion. When this request arrived, we might have pretended
2938 // that a network connected to serve it, even though the network was already
2939 // connected. Now that this request has gone away, we might have to pretend
2940 // that the network disconnected. LegacyTypeTracker will generate that
2941 // phantom disconnect for this type.
2942 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2943 boolean doRemove = true;
2944 if (wasKept) {
2945 // check if any of the remaining requests for this network are for the
2946 // same legacy type - if so, don't remove the nai
2947 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2948 NetworkRequest otherRequest = nai.requestAt(i);
2949 if (otherRequest.legacyType == nri.request.legacyType &&
2950 otherRequest.isRequest()) {
2951 if (DBG) log(" still have other legacy request - leaving");
2952 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002953 }
2954 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002955 }
2956
Erik Klineacdd6392016-07-07 16:50:58 +09002957 if (doRemove) {
2958 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002959 }
2960 }
Erik Klineacdd6392016-07-07 16:50:58 +09002961
2962 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2963 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2964 nri.request);
2965 }
2966 } else {
2967 // listens don't have a singular affectedNetwork. Check all networks to see
2968 // if this listen request applies and remove it.
2969 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2970 nai.removeRequest(nri.request.requestId);
2971 if (nri.request.networkCapabilities.hasSignalStrength() &&
2972 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2973 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2974 }
2975 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002976 }
2977 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002978
Lorenzo Colitti18660282016-07-04 12:55:44 +09002979 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002980 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2981 enforceConnectivityInternalPermission();
2982 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002983 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002984 }
2985
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002986 @Override
2987 public void setAvoidUnvalidated(Network network) {
2988 enforceConnectivityInternalPermission();
2989 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2990 }
2991
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002992 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2993 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2994 " accept=" + accept + " always=" + always);
2995
2996 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2997 if (nai == null) {
2998 // Nothing to do.
2999 return;
3000 }
3001
3002 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003003 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003004 return;
3005 }
3006
3007 if (!nai.networkMisc.explicitlySelected) {
3008 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3009 }
3010
3011 if (accept != nai.networkMisc.acceptUnvalidated) {
3012 int oldScore = nai.getCurrentScore();
3013 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003014 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003015 sendUpdatedScoreToFactories(nai);
3016 }
3017
3018 if (always) {
3019 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003020 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003021 }
3022
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003023 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003024 // Tell the NetworkAgent to not automatically reconnect to the network.
3025 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003026 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003027 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003028 }
3029
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003030 }
3031
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003032 private void handleSetAvoidUnvalidated(Network network) {
3033 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3034 if (nai == null || nai.lastValidated) {
3035 // Nothing to do. The network either disconnected or revalidated.
3036 return;
3037 }
3038 if (!nai.avoidUnvalidated) {
3039 int oldScore = nai.getCurrentScore();
3040 nai.avoidUnvalidated = true;
3041 rematchAllNetworksAndRequests(nai, oldScore);
3042 sendUpdatedScoreToFactories(nai);
3043 }
3044 }
3045
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003046 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003047 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003048 mHandler.sendMessageDelayed(
3049 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3050 PROMPT_UNVALIDATED_DELAY_MS);
3051 }
3052
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003053 @Override
3054 public void startCaptivePortalApp(Network network) {
3055 enforceConnectivityInternalPermission();
3056 mHandler.post(() -> {
3057 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3058 if (nai == null) return;
3059 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
3060 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
3061 });
3062 }
3063
Hugo Benichic8e9e122016-09-14 23:23:08 +00003064 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003065 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003066 }
3067
Erik Kline065ab6e2016-10-02 18:02:14 +09003068 private void rematchForAvoidBadWifiUpdate() {
3069 rematchAllNetworksAndRequests(null, 0);
3070 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3071 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3072 sendUpdatedScoreToFactories(nai);
3073 }
3074 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003075 }
3076
Erik Kline065ab6e2016-10-02 18:02:14 +09003077 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003078 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003079 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003080 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003081 if (!configRestrict) {
3082 pw.println("Bad Wi-Fi avoidance: unrestricted");
3083 return;
3084 }
3085
3086 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3087 pw.increaseIndent();
3088 pw.println("Config restrict: " + configRestrict);
3089
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003090 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003091 String description;
3092 // Can't use a switch statement because strings are legal case labels, but null is not.
3093 if ("0".equals(value)) {
3094 description = "get stuck";
3095 } else if (value == null) {
3096 description = "prompt";
3097 } else if ("1".equals(value)) {
3098 description = "avoid";
3099 } else {
3100 description = value + " (?)";
3101 }
3102 pw.println("User setting: " + description);
3103 pw.println("Network overrides:");
3104 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003105 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003106 if (nai.avoidUnvalidated) {
3107 pw.println(nai.name());
3108 }
3109 }
3110 pw.decreaseIndent();
3111 pw.decreaseIndent();
3112 }
3113
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003114 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
3115 final String action;
3116 switch (type) {
3117 case NO_INTERNET:
3118 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3119 break;
3120 case LOST_INTERNET:
3121 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3122 break;
3123 default:
3124 Slog.wtf(TAG, "Unknown notification type " + type);
3125 return;
3126 }
3127
3128 Intent intent = new Intent(action);
3129 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3130 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3131 intent.setClassName("com.android.settings",
3132 "com.android.settings.wifi.WifiNoInternetDialog");
3133
3134 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3135 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3136 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3137 }
3138
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003139 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003140 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003141 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3142
3143 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3144 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003145 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003146 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003147 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3148 return;
3149 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003150 showValidationNotification(nai, NotificationType.NO_INTERNET);
3151 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003152
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003153 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3154 NetworkCapabilities nc = nai.networkCapabilities;
3155 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003156
Erik Kline065ab6e2016-10-02 18:02:14 +09003157 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003158 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003159 showValidationNotification(nai, NotificationType.LOST_INTERNET);
3160 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003161 }
3162
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003163 @Override
3164 public int getMultipathPreference(Network network) {
3165 enforceAccessPermission();
3166
3167 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003168 if (nai != null && nai.networkCapabilities
3169 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003170 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3171 }
3172
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003173 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3174 if (networkPreference != null) {
3175 return networkPreference;
3176 }
3177
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003178 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3179 }
3180
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003181 private class InternalHandler extends Handler {
3182 public InternalHandler(Looper looper) {
3183 super(looper);
3184 }
3185
3186 @Override
3187 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003188 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003189 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003190 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003191 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003192 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003193 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003194 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003195 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003196 break;
3197 }
Jason Monkdecd2952013-10-10 14:02:51 -04003198 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003199 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003200 break;
3201 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003202 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003203 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3204 break;
3205 }
3206 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3207 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003208 break;
3209 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003210 case EVENT_REGISTER_NETWORK_AGENT: {
3211 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3212 break;
3213 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003214 case EVENT_REGISTER_NETWORK_REQUEST:
3215 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003216 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003217 break;
3218 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003219 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3220 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003221 handleRegisterNetworkRequestWithIntent(msg);
3222 break;
3223 }
Erik Kline57faba92015-11-25 12:49:38 +09003224 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3225 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3226 handleTimedOutNetworkRequest(nri);
3227 break;
3228 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003229 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3230 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3231 break;
3232 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003233 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003234 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003235 break;
3236 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003237 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003238 Network network = (Network) msg.obj;
3239 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003240 break;
3241 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003242 case EVENT_SET_AVOID_UNVALIDATED: {
3243 handleSetAvoidUnvalidated((Network) msg.obj);
3244 break;
3245 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003246 case EVENT_PROMPT_UNVALIDATED: {
3247 handlePromptUnvalidated((Network) msg.obj);
3248 break;
3249 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003250 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3251 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003252 break;
3253 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003254 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3255 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3256 mKeepaliveTracker.handleStartKeepalive(msg);
3257 break;
3258 }
3259 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3260 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3261 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3262 int slot = msg.arg1;
3263 int reason = msg.arg2;
3264 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3265 break;
3266 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003267 case EVENT_SYSTEM_READY: {
3268 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3269 nai.networkMonitor.systemReady = true;
3270 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003271 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003272 break;
3273 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003274 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003275 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003276 break;
3277 }
Erik Klinea24d4592018-01-11 21:07:29 +09003278 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3279 handlePrivateDnsSettingsChanged();
3280 break;
dalyk7301aa42018-03-05 12:42:22 -05003281 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3282 handlePrivateDnsValidationUpdate(
3283 (PrivateDnsValidationUpdate) msg.obj);
3284 break;
junyulai05986c62018-08-07 19:50:45 +08003285 case EVENT_UID_RULES_CHANGED:
3286 handleUidRulesChanged(msg.arg1, msg.arg2);
3287 break;
3288 case EVENT_DATA_SAVER_CHANGED:
3289 handleRestrictBackgroundChanged(toBool(msg.arg1));
3290 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 }
3292 }
3293 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003294
3295 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003296 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003297 public int tether(String iface, String callerPkg) {
3298 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003299 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003300 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003301 } else {
3302 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3303 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003304 }
3305
3306 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003307 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003308 public int untether(String iface, String callerPkg) {
3309 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003310
3311 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003312 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003313 } else {
3314 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3315 }
3316 }
3317
3318 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003319 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003320 public int getLastTetherError(String iface) {
3321 enforceTetherAccessPermission();
3322
3323 if (isTetheringSupported()) {
3324 return mTethering.getLastTetherError(iface);
3325 } else {
3326 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3327 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003328 }
3329
3330 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003331 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003332 public String[] getTetherableUsbRegexs() {
3333 enforceTetherAccessPermission();
3334 if (isTetheringSupported()) {
3335 return mTethering.getTetherableUsbRegexs();
3336 } else {
3337 return new String[0];
3338 }
3339 }
3340
Lorenzo Colitti18660282016-07-04 12:55:44 +09003341 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003342 public String[] getTetherableWifiRegexs() {
3343 enforceTetherAccessPermission();
3344 if (isTetheringSupported()) {
3345 return mTethering.getTetherableWifiRegexs();
3346 } else {
3347 return new String[0];
3348 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003349 }
3350
Lorenzo Colitti18660282016-07-04 12:55:44 +09003351 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003352 public String[] getTetherableBluetoothRegexs() {
3353 enforceTetherAccessPermission();
3354 if (isTetheringSupported()) {
3355 return mTethering.getTetherableBluetoothRegexs();
3356 } else {
3357 return new String[0];
3358 }
3359 }
3360
Lorenzo Colitti18660282016-07-04 12:55:44 +09003361 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003362 public int setUsbTethering(boolean enable, String callerPkg) {
3363 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003364 if (isTetheringSupported()) {
3365 return mTethering.setUsbTethering(enable);
3366 } else {
3367 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3368 }
3369 }
3370
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003371 // TODO - move iface listing, queries, etc to new module
3372 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003373 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003374 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003375 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003376 return mTethering.getTetherableIfaces();
3377 }
3378
Lorenzo Colitti18660282016-07-04 12:55:44 +09003379 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003380 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003381 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003382 return mTethering.getTetheredIfaces();
3383 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003384
Lorenzo Colitti18660282016-07-04 12:55:44 +09003385 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003386 public String[] getTetheringErroredIfaces() {
3387 enforceTetherAccessPermission();
3388 return mTethering.getErroredIfaces();
3389 }
3390
Lorenzo Colitti18660282016-07-04 12:55:44 +09003391 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003392 public String[] getTetheredDhcpRanges() {
3393 enforceConnectivityInternalPermission();
3394 return mTethering.getTetheredDhcpRanges();
3395 }
3396
Udam Saini0e94c362017-06-07 12:06:28 -07003397 @Override
3398 public boolean isTetheringSupported(String callerPkg) {
3399 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3400 return isTetheringSupported();
3401 }
3402
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003403 // if ro.tether.denied = true we default to no tethering
3404 // gservices could set the secure setting to 1 though to enable it on a build where it
3405 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003406 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003407 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3408 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3409 Settings.Global.TETHER_SUPPORTED, defaultVal));
3410 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003411 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003412
3413 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3414 boolean adminUser = false;
3415 final long token = Binder.clearCallingIdentity();
3416 try {
3417 adminUser = mUserManager.isAdminUser();
3418 } finally {
3419 Binder.restoreCallingIdentity(token);
3420 }
3421
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003422 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003423 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003424
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003425 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003426 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3427 String callerPkg) {
3428 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003429 if (!isTetheringSupported()) {
3430 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3431 return;
3432 }
3433 mTethering.startTethering(type, receiver, showProvisioningUi);
3434 }
3435
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003436 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003437 public void stopTethering(int type, String callerPkg) {
3438 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003439 mTethering.stopTethering(type);
3440 }
3441
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003442 // Called when we lose the default network and have no replacement yet.
3443 // This will automatically be cleared after X seconds or a new default network
3444 // becomes CONNECTED, whichever happens first. The timer is started by the
3445 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003446 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003447 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003448 if (mNetTransitionWakeLock.isHeld()) {
3449 return;
3450 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003451 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003452 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3453 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003454 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003455 mWakelockLogs.log("ACQUIRE for " + forWhom);
3456 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3457 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003458 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003459
Hugo Benichi4c31b342017-03-30 23:18:10 +09003460 // Called when we gain a new default network to release the network transition wakelock in a
3461 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3462 // message is cancelled.
3463 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003464 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003465 if (!mNetTransitionWakeLock.isHeld()) {
3466 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003467 }
3468 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003469 // Cancel self timeout on wakelock hold.
3470 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3471 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3472 mHandler.sendMessageDelayed(msg, 1000);
3473 }
3474
3475 // Called when either message of ensureNetworkTransitionWakelock or
3476 // scheduleReleaseNetworkTransitionWakelock is processed.
3477 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3478 String event = eventName(eventId);
3479 synchronized (this) {
3480 if (!mNetTransitionWakeLock.isHeld()) {
3481 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3482 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3483 return;
3484 }
3485 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003486 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3487 mTotalWakelockDurationMs += lockDuration;
3488 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3489 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003490 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003491 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003492 }
3493
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003494 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003495 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003496 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003497 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003498 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003499 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003500 }
3501
Lorenzo Colitti18660282016-07-04 12:55:44 +09003502 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003503 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003504 enforceAccessPermission();
3505 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003506 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003507 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003508 mHandler.sendMessage(
3509 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3510 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003511
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003512 private void handleReportNetworkConnectivity(
3513 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003514 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003515 if (network == null) {
3516 nai = getDefaultNetwork();
3517 } else {
3518 nai = getNetworkAgentInfoForNetwork(network);
3519 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003520 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3521 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3522 return;
3523 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003524 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003525 if (hasConnectivity == nai.lastValidated) {
3526 return;
3527 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003528 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003529 int netid = nai.network.netId;
3530 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003531 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003532 // Validating a network that has not yet connected could result in a call to
3533 // rematchNetworkAndRequests() which is not meant to work on such networks.
3534 if (!nai.everConnected) {
3535 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003536 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003537 LinkProperties lp = getLinkProperties(nai);
3538 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3539 return;
3540 }
Erik Kline736353a2018-03-21 07:18:33 -07003541 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003542 }
3543
Lorenzo Colitti18660282016-07-04 12:55:44 +09003544 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003545 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003546 if (network == null) return mProxyTracker.getDefaultProxy();
3547 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003548 if (globalProxy != null) return globalProxy;
3549 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3550 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3551 // caller may not have.
3552 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3553 if (nai == null) return null;
3554 synchronized (nai) {
3555 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3556 if (proxyInfo == null) return null;
3557 return new ProxyInfo(proxyInfo);
3558 }
3559 }
3560
Chalard Jean3c443fc2018-06-07 18:37:59 +09003561 @Override
3562 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003563 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003564 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003565 }
3566
Chalard Jean5afbc832018-06-07 18:02:37 +09003567 @Override
3568 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003569 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003570 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003571 }
3572
Jason Monk207900c2014-04-25 15:00:09 -04003573 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003574 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003575 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003576 proxy = null;
3577 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003578 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003579 }
3580
Paul Jensene0bef712014-12-10 15:12:18 -05003581 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3582 // This method gets called when any network changes proxy, but the broadcast only ever contains
3583 // the default proxy (even if it hasn't changed).
3584 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3585 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003586 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003587 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3588 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3589
Chalard Jean4949dd72018-06-07 17:41:29 +09003590 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean3319c622018-06-07 19:30:29 +09003591 mProxyTracker.sendProxyBroadcast(mProxyTracker.getDefaultProxy());
Paul Jensene0bef712014-12-10 15:12:18 -05003592 }
3593 }
3594
Robert Greenwalt434203a2010-10-11 16:00:27 -07003595 private void handleDeprecatedGlobalHttpProxy() {
Chalard Jean4133a122018-06-04 13:33:12 +09003596 final String proxy = Settings.Global.getString(mContext.getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -07003597 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003598 if (!TextUtils.isEmpty(proxy)) {
3599 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003600 if (data.length == 0) {
3601 return;
3602 }
3603
Chalard Jean4133a122018-06-04 13:33:12 +09003604 final String proxyHost = data[0];
Robert Greenwalt434203a2010-10-11 16:00:27 -07003605 int proxyPort = 8080;
3606 if (data.length > 1) {
3607 try {
3608 proxyPort = Integer.parseInt(data[1]);
3609 } catch (NumberFormatException e) {
3610 return;
3611 }
3612 }
Chalard Jean4133a122018-06-04 13:33:12 +09003613 final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003614 setGlobalProxy(p);
3615 }
3616 }
3617
Robert Greenwalt434203a2010-10-11 16:00:27 -07003618 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003619 final private HashMap<Uri, Integer> mUriEventMap;
3620 final private Context mContext;
3621 final private Handler mHandler;
3622
3623 SettingsObserver(Context context, Handler handler) {
3624 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003625 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003626 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003627 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003628 }
3629
Erik Klineda4bfa82015-04-30 12:58:40 +09003630 void observe(Uri uri, int what) {
3631 mUriEventMap.put(uri, what);
3632 final ContentResolver resolver = mContext.getContentResolver();
3633 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003634 }
3635
3636 @Override
3637 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003638 Slog.wtf(TAG, "Should never be reached.");
3639 }
3640
3641 @Override
3642 public void onChange(boolean selfChange, Uri uri) {
3643 final Integer what = mUriEventMap.get(uri);
3644 if (what != null) {
3645 mHandler.obtainMessage(what.intValue()).sendToTarget();
3646 } else {
3647 loge("No matching event to send for URI=" + uri);
3648 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003649 }
3650 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003651
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003652 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003653 Slog.d(TAG, s);
3654 }
3655
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003656 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003657 Slog.e(TAG, s);
3658 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003659
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003660 private static void loge(String s, Throwable t) {
3661 Slog.e(TAG, s, t);
3662 }
3663
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003664 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003665 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003666 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3667 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3668 *
3669 * @param oldPackage Package name of the application which currently controls VPN, which will
3670 * be replaced. If there is no such application, this should should either be
3671 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3672 * @param newPackage Package name of the application which should gain control of VPN, or
3673 * {@code null} to disable.
3674 * @param userId User for whom to prepare the new VPN.
3675 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003676 * @hide
3677 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003678 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003679 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3680 int userId) {
3681 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003682
Hugo Benichi20035e02017-04-26 14:53:28 +09003683 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003684 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003685 Vpn vpn = mVpns.get(userId);
3686 if (vpn != null) {
3687 return vpn.prepare(oldPackage, newPackage);
3688 } else {
3689 return false;
3690 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003691 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003692 }
3693
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003694 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003695 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3696 * This method is used by system-privileged apps.
3697 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3698 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3699 *
3700 * @param packageName The package for which authorization state should change.
3701 * @param userId User for whom {@code packageName} is installed.
3702 * @param authorized {@code true} if this app should be able to start a VPN connection without
3703 * explicit user approval, {@code false} if not.
3704 *
Jeff Davidson05542602014-08-11 14:07:27 -07003705 * @hide
3706 */
3707 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003708 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3709 enforceCrossUserPermission(userId);
3710
Hugo Benichi20035e02017-04-26 14:53:28 +09003711 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003712 Vpn vpn = mVpns.get(userId);
3713 if (vpn != null) {
3714 vpn.setPackageAuthorization(packageName, authorized);
3715 }
Jeff Davidson05542602014-08-11 14:07:27 -07003716 }
3717 }
3718
3719 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003720 * Configure a TUN interface and return its file descriptor. Parameters
3721 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003722 * and not available in ConnectivityManager. Permissions are checked in
3723 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003724 * @hide
3725 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003726 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003727 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003728 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003729 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003730 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003731 return mVpns.get(user).establish(config);
3732 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003733 }
3734
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003735 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003736 * Start legacy VPN, controlling native daemons as needed. Creates a
3737 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003738 */
3739 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003740 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003741 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003742 final LinkProperties egress = getActiveLinkProperties();
3743 if (egress == null) {
3744 throw new IllegalStateException("Missing active network connection");
3745 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003746 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003747 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003748 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3749 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003750 }
3751
3752 /**
3753 * Return the information of the ongoing legacy VPN. This method is used
3754 * by VpnSettings and not available in ConnectivityManager. Permissions
3755 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003756 */
3757 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003758 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3759 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003760
Hugo Benichi20035e02017-04-26 14:53:28 +09003761 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003762 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003763 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003764 }
3765
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003766 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003767 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3768 * and not available in ConnectivityManager.
3769 */
3770 @Override
3771 public VpnInfo[] getAllVpnInfo() {
3772 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003773 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003774 if (mLockdownEnabled) {
3775 return new VpnInfo[0];
3776 }
3777
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003778 List<VpnInfo> infoList = new ArrayList<>();
3779 for (int i = 0; i < mVpns.size(); i++) {
3780 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3781 if (info != null) {
3782 infoList.add(info);
3783 }
3784 }
3785 return infoList.toArray(new VpnInfo[infoList.size()]);
3786 }
3787 }
3788
3789 /**
3790 * @return VPN information for accounting, or null if we can't retrieve all required
3791 * information, e.g primary underlying iface.
3792 */
3793 @Nullable
3794 private VpnInfo createVpnInfo(Vpn vpn) {
3795 VpnInfo info = vpn.getVpnInfo();
3796 if (info == null) {
3797 return null;
3798 }
3799 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3800 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3801 // the underlyingNetworks list.
3802 if (underlyingNetworks == null) {
3803 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3804 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3805 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3806 }
3807 } else if (underlyingNetworks.length > 0) {
3808 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3809 if (linkProperties != null) {
3810 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3811 }
3812 }
3813 return info.primaryUnderlyingIface == null ? null : info;
3814 }
3815
3816 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003817 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3818 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003819 * Permissions are checked in Vpn class.
3820 * @hide
3821 */
3822 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003823 public VpnConfig getVpnConfig(int userId) {
3824 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003825 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003826 Vpn vpn = mVpns.get(userId);
3827 if (vpn != null) {
3828 return vpn.getVpnConfig();
3829 } else {
3830 return null;
3831 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003832 }
3833 }
3834
Chalard Jean6b65ec72018-05-18 22:02:56 +09003835 /**
3836 * Ask all VPN objects to recompute and update their capabilities.
3837 *
3838 * When underlying networks change, VPNs may have to update capabilities to reflect things
3839 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3840 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3841 * handler thread through their agent, this is asynchronous. When the capabilities objects
3842 * are computed they will be up-to-date as they are computed synchronously from here and
3843 * this is running on the ConnectivityService thread.
3844 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3845 */
3846 private void updateAllVpnsCapabilities() {
3847 synchronized (mVpns) {
3848 for (int i = 0; i < mVpns.size(); i++) {
3849 final Vpn vpn = mVpns.valueAt(i);
3850 vpn.updateCapabilities();
3851 }
3852 }
3853 }
3854
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003855 @Override
3856 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003857 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3858 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3859 return false;
3860 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003861
Hugo Benichi69744342017-11-27 10:57:16 +09003862 synchronized (mVpns) {
3863 // Tear down existing lockdown if profile was removed
3864 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3865 if (mLockdownEnabled) {
3866 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3867 if (profileTag == null) {
3868 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3869 return false;
3870 }
3871 String profileName = new String(profileTag);
3872 final VpnProfile profile = VpnProfile.decode(
3873 profileName, mKeyStore.get(Credentials.VPN + profileName));
3874 if (profile == null) {
3875 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3876 setLockdownTracker(null);
3877 return true;
3878 }
3879 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003880 Vpn vpn = mVpns.get(user);
3881 if (vpn == null) {
3882 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3883 return false;
3884 }
Luke Huang4e25ec62018-09-27 16:58:23 +08003885 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003886 } else {
3887 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003888 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003889 }
3890
3891 return true;
3892 }
3893
3894 /**
3895 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3896 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3897 */
Hugo Benichi69744342017-11-27 10:57:16 +09003898 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003899 private void setLockdownTracker(LockdownVpnTracker tracker) {
3900 // Shutdown any existing tracker
3901 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08003902 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
3903 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003904 mLockdownTracker = null;
3905 if (existing != null) {
3906 existing.shutdown();
3907 }
3908
Robin Leec3736bc2017-03-10 16:19:54 +00003909 if (tracker != null) {
3910 mLockdownTracker = tracker;
3911 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003912 }
3913 }
3914
Hugo Benichi69744342017-11-27 10:57:16 +09003915 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003916 private void throwIfLockdownEnabled() {
3917 if (mLockdownEnabled) {
3918 throw new IllegalStateException("Unavailable in lockdown mode");
3919 }
3920 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003921
Robin Lee244ce8e2016-01-05 18:03:46 +00003922 /**
Robin Lee17e61832016-05-09 13:46:28 +01003923 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3924 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003925 *
Robin Lee17e61832016-05-09 13:46:28 +01003926 * @return {@code true} if the service was started, the service was already connected, or there
3927 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003928 */
Robin Lee17e61832016-05-09 13:46:28 +01003929 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003930 synchronized (mVpns) {
3931 Vpn vpn = mVpns.get(userId);
3932 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09003933 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01003934 // exists already.
3935 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3936 return false;
3937 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003938
Robin Lee812800c2016-05-13 15:38:08 +01003939 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003940 }
3941 }
3942
3943 @Override
Charles He36738632017-05-15 17:07:18 +01003944 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3945 enforceSettingsPermission();
3946 enforceCrossUserPermission(userId);
3947
3948 synchronized (mVpns) {
3949 Vpn vpn = mVpns.get(userId);
3950 if (vpn == null) {
3951 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3952 return false;
3953 }
3954 return vpn.isAlwaysOnPackageSupported(packageName);
3955 }
3956 }
3957
3958 @Override
Robin Leedc679712016-05-03 13:23:03 +01003959 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003960 enforceConnectivityInternalPermission();
3961 enforceCrossUserPermission(userId);
3962
Robin Lee244ce8e2016-01-05 18:03:46 +00003963 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003964 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3965 if (LockdownVpnTracker.isEnabled()) {
3966 return false;
3967 }
3968
Robin Lee244ce8e2016-01-05 18:03:46 +00003969 Vpn vpn = mVpns.get(userId);
3970 if (vpn == null) {
3971 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3972 return false;
3973 }
Robin Lee17e61832016-05-09 13:46:28 +01003974 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003975 return false;
3976 }
Robin Lee17e61832016-05-09 13:46:28 +01003977 if (!startAlwaysOnVpn(userId)) {
3978 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003979 return false;
3980 }
3981 }
3982 return true;
3983 }
3984
3985 @Override
3986 public String getAlwaysOnVpnPackage(int userId) {
3987 enforceConnectivityInternalPermission();
3988 enforceCrossUserPermission(userId);
3989
3990 synchronized (mVpns) {
3991 Vpn vpn = mVpns.get(userId);
3992 if (vpn == null) {
3993 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3994 return null;
3995 }
3996 return vpn.getAlwaysOnPackage();
3997 }
3998 }
3999
Wink Savilleab9321d2013-06-29 21:10:57 -07004000 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004001 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004002 // TODO: Remove? Any reason to trigger a provisioning check?
4003 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004004 }
4005
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004006 /** Location to an updatable file listing carrier provisioning urls.
4007 * An example:
4008 *
4009 * <?xml version="1.0" encoding="utf-8"?>
4010 * <provisioningUrls>
4011 * <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 -07004012 * </provisioningUrls>
4013 */
4014 private static final String PROVISIONING_URL_PATH =
4015 "/data/misc/radio/provisioning_urls.xml";
4016 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004017
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004018 /** XML tag for root element. */
4019 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4020 /** XML tag for individual url */
4021 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004022 /** XML attribute for mcc */
4023 private static final String ATTR_MCC = "mcc";
4024 /** XML attribute for mnc */
4025 private static final String ATTR_MNC = "mnc";
4026
Paul Jensen434dde82015-06-11 09:43:30 -04004027 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004028 FileReader fileReader = null;
4029 XmlPullParser parser = null;
4030 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004031
4032 try {
4033 fileReader = new FileReader(mProvisioningUrlFile);
4034 parser = Xml.newPullParser();
4035 parser.setInput(fileReader);
4036 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4037
4038 while (true) {
4039 XmlUtils.nextElement(parser);
4040
4041 String element = parser.getName();
4042 if (element == null) break;
4043
Paul Jensen434dde82015-06-11 09:43:30 -04004044 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004045 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4046 try {
4047 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4048 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4049 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4050 parser.next();
4051 if (parser.getEventType() == XmlPullParser.TEXT) {
4052 return parser.getText();
4053 }
4054 }
4055 }
4056 } catch (NumberFormatException e) {
4057 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4058 }
4059 }
4060 }
4061 return null;
4062 } catch (FileNotFoundException e) {
4063 loge("Carrier Provisioning Urls file not found");
4064 } catch (XmlPullParserException e) {
4065 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4066 } catch (IOException e) {
4067 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4068 } finally {
4069 if (fileReader != null) {
4070 try {
4071 fileReader.close();
4072 } catch (IOException e) {}
4073 }
4074 }
4075 return null;
4076 }
4077
Wink Saville42d4f082013-07-20 20:31:59 -07004078 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004079 public String getMobileProvisioningUrl() {
4080 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004081 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004082 if (TextUtils.isEmpty(url)) {
4083 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004084 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004085 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004086 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004087 }
Wink Saville8cf35602013-07-10 23:00:07 -07004088 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004089 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004090 String phoneNumber = mTelephonyManager.getLine1Number();
4091 if (TextUtils.isEmpty(phoneNumber)) {
4092 phoneNumber = "0000000000";
4093 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004094 url = String.format(url,
4095 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4096 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004097 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004098 }
4099
Wink Savilleab9321d2013-06-29 21:10:57 -07004100 return url;
4101 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004102
Wink Saville948282b2013-08-29 08:55:16 -07004103 @Override
4104 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004105 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004106 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004107 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4108 return;
4109 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004110 final long ident = Binder.clearCallingIdentity();
4111 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004112 // Concatenate the range of types onto the range of NetIDs.
4113 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4114 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004115 } finally {
4116 Binder.restoreCallingIdentity(ident);
4117 }
Wink Saville948282b2013-08-29 08:55:16 -07004118 }
Wink Saville7788c612013-08-29 14:57:08 -07004119
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004120 @Override
4121 public void setAirplaneMode(boolean enable) {
4122 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004123 final long ident = Binder.clearCallingIdentity();
4124 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004125 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004126 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004127 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4128 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004129 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004130 } finally {
4131 Binder.restoreCallingIdentity(ident);
4132 }
4133 }
4134
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004135 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004136 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004137 Vpn userVpn = mVpns.get(userId);
4138 if (userVpn != null) {
4139 loge("Starting user already has a VPN");
4140 return;
4141 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004142 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004143 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004144 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4145 updateLockdownVpn();
4146 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004147 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004148 }
4149
4150 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004151 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004152 Vpn userVpn = mVpns.get(userId);
4153 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004154 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004155 return;
4156 }
Robin Lee17e61832016-05-09 13:46:28 +01004157 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004158 mVpns.delete(userId);
4159 }
4160 }
4161
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004162 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004163 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004164 final int vpnsSize = mVpns.size();
4165 for (int i = 0; i < vpnsSize; i++) {
4166 Vpn vpn = mVpns.valueAt(i);
4167 vpn.onUserAdded(userId);
4168 }
4169 }
4170 }
4171
4172 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004173 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004174 final int vpnsSize = mVpns.size();
4175 for (int i = 0; i < vpnsSize; i++) {
4176 Vpn vpn = mVpns.valueAt(i);
4177 vpn.onUserRemoved(userId);
4178 }
4179 }
4180 }
4181
Robin Lee89e7a692016-02-29 14:38:17 +00004182 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004183 synchronized (mVpns) {
4184 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4185 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4186 updateLockdownVpn();
4187 } else {
4188 startAlwaysOnVpn(userId);
4189 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004190 }
4191 }
4192
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004193 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4194 @Override
4195 public void onReceive(Context context, Intent intent) {
4196 final String action = intent.getAction();
4197 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4198 if (userId == UserHandle.USER_NULL) return;
4199
Robin Lee323f29d2016-05-04 16:38:06 +01004200 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004201 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004202 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004203 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004204 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4205 onUserAdded(userId);
4206 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4207 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004208 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4209 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004210 }
4211 }
4212 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004213
Robin Lee95204e02017-01-27 11:59:22 +00004214 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4215 @Override
4216 public void onReceive(Context context, Intent intent) {
4217 // Try creating lockdown tracker, since user present usually means
4218 // unlocked keystore.
4219 updateLockdownVpn();
4220 mContext.unregisterReceiver(this);
4221 }
4222 };
4223
Chalard Jean4133a122018-06-04 13:33:12 +09004224 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4225 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004226
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004227 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4228 // Map from UID to number of NetworkRequests that UID has filed.
4229 @GuardedBy("mUidToNetworkRequestCount")
4230 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4231
Robert Greenwalta67be032014-05-16 15:49:14 -07004232 private static class NetworkFactoryInfo {
4233 public final String name;
4234 public final Messenger messenger;
4235 public final AsyncChannel asyncChannel;
4236
4237 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4238 this.name = name;
4239 this.messenger = messenger;
4240 this.asyncChannel = asyncChannel;
4241 }
4242 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004243
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004244 private void ensureNetworkRequestHasType(NetworkRequest request) {
4245 if (request.type == NetworkRequest.Type.NONE) {
4246 throw new IllegalArgumentException(
4247 "All NetworkRequests in ConnectivityService must have a type");
4248 }
4249 }
4250
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004251 /**
4252 * Tracks info about the requester.
4253 * Also used to notice when the calling process dies so we can self-expire
4254 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004255 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004256 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004257 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004258 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004259 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004260 final int mPid;
4261 final int mUid;
4262 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004263
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004264 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004265 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004266 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004267 mPendingIntent = pi;
4268 messenger = null;
4269 mBinder = null;
4270 mPid = getCallingPid();
4271 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004272 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004273 }
4274
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004275 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004276 super();
4277 messenger = m;
4278 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004279 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004280 mBinder = binder;
4281 mPid = getCallingPid();
4282 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004283 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004284 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004285
4286 try {
4287 mBinder.linkToDeath(this, 0);
4288 } catch (RemoteException e) {
4289 binderDied();
4290 }
4291 }
4292
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004293 private void enforceRequestCountLimit() {
4294 synchronized (mUidToNetworkRequestCount) {
4295 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4296 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004297 throw new ServiceSpecificException(
4298 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004299 }
4300 mUidToNetworkRequestCount.put(mUid, networkRequests);
4301 }
4302 }
4303
Robert Greenwalt9258c642014-03-26 16:47:06 -07004304 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004305 if (mBinder != null) {
4306 mBinder.unlinkToDeath(this, 0);
4307 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004308 }
4309
4310 public void binderDied() {
4311 log("ConnectivityService NetworkRequestInfo binderDied(" +
4312 request + ", " + mBinder + ")");
4313 releaseNetworkRequest(request);
4314 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004315
4316 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004317 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004318 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004319 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004320 }
4321
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004322 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4323 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4324 if (badCapability != null) {
4325 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004326 }
4327 }
4328
Chalard Jeanb03a6222018-04-11 21:09:10 +09004329 // This checks that the passed capabilities either do not request a specific SSID, or the
4330 // calling app has permission to do so.
4331 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4332 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004333 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004334 throw new SecurityException("Insufficient permissions to request a specific SSID");
4335 }
4336 }
4337
Erik Kline9d598e12015-07-13 16:37:51 +09004338 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004339 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004340 synchronized (nai) {
4341 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4342 if (nri.request.networkCapabilities.hasSignalStrength() &&
4343 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4344 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4345 }
4346 }
4347 }
Chalard Jean4133a122018-06-04 13:33:12 +09004348 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004349 }
4350
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004351 private void updateSignalStrengthThresholds(
4352 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4353 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004354 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004355 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4356
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004357 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004358 String detail;
4359 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4360 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4361 } else {
4362 detail = reason;
4363 }
4364 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4365 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4366 }
4367
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004368 nai.asyncChannel.sendMessage(
4369 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004370 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004371 }
4372
Etan Cohen859748f2017-04-03 17:42:34 -07004373 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4374 if (nc == null) {
4375 return;
4376 }
4377 NetworkSpecifier ns = nc.getNetworkSpecifier();
4378 if (ns == null) {
4379 return;
4380 }
4381 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4382 ns.assertValidFromUid(Binder.getCallingUid());
4383 }
4384
Robert Greenwalt9258c642014-03-26 16:47:06 -07004385 @Override
4386 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004387 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004388 final NetworkRequest.Type type = (networkCapabilities == null)
4389 ? NetworkRequest.Type.TRACK_DEFAULT
4390 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004391 // If the requested networkCapabilities is null, take them instead from
4392 // the default network request. This allows callers to keep track of
4393 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004394 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004395 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004396 enforceAccessPermission();
4397 } else {
4398 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4399 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004400 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4401 // of the app when the request is filed, but we never change the request if the app
4402 // changes network state. http://b/29964605
4403 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004404 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004405 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004406 ensureSufficientPermissionsForRequest(networkCapabilities,
4407 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004408 // Set the UID range for this request to the single UID of the requester, or to an empty
4409 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004410 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4411 // are no visible methods to set the UIDs, an app could use reflection to try and get
4412 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004413 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004414
Etan Cohenba07c8c2017-02-05 10:42:27 -08004415 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004416 throw new IllegalArgumentException("Bad timeout specified");
4417 }
Etan Cohen859748f2017-04-03 17:42:34 -07004418 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004419
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004420 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004421 nextNetworkRequestId(), type);
4422 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004423 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004424
4425 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004426 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004427 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004428 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004429 }
4430 return networkRequest;
4431 }
4432
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004433 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004434 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004435 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004436 } else {
4437 enforceChangePermission();
4438 }
4439 }
4440
fenglub15e72b2015-03-20 11:29:56 -07004441 @Override
fengludb571472015-04-21 17:12:05 -07004442 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004443 enforceAccessPermission();
4444 NetworkAgentInfo nai = null;
4445 if (network == null) {
4446 return false;
4447 }
4448 synchronized (mNetworkForNetId) {
4449 nai = mNetworkForNetId.get(network.netId);
4450 }
4451 if (nai != null) {
4452 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004453 synchronized (mBandwidthRequests) {
4454 final int uid = Binder.getCallingUid();
4455 Integer uidReqs = mBandwidthRequests.get(uid);
4456 if (uidReqs == null) {
4457 uidReqs = new Integer(0);
4458 }
4459 mBandwidthRequests.put(uid, ++uidReqs);
4460 }
fenglub15e72b2015-03-20 11:29:56 -07004461 return true;
4462 }
4463 return false;
4464 }
4465
Felipe Lemeee27cab2016-06-20 16:36:29 -07004466 private boolean isSystem(int uid) {
4467 return uid < Process.FIRST_APPLICATION_UID;
4468 }
fenglub15e72b2015-03-20 11:29:56 -07004469
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004470 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004471 final int uid = Binder.getCallingUid();
4472 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004473 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004474 return;
4475 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004476 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4477 // Policy already enforced.
4478 return;
4479 }
4480 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4481 // If UID is restricted, don't allow them to bring up metered APNs.
4482 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004483 }
4484 }
4485
Robert Greenwalt9258c642014-03-26 16:47:06 -07004486 @Override
4487 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4488 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004489 checkNotNull(operation, "PendingIntent cannot be null.");
4490 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4491 enforceNetworkRequestPermissions(networkCapabilities);
4492 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004493 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004494 ensureSufficientPermissionsForRequest(networkCapabilities,
4495 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004496 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004497 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004498
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004499 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004500 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4501 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004502 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004503 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4504 nri));
4505 return networkRequest;
4506 }
4507
Jeremy Joslin79294842014-12-03 17:15:28 -08004508 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4509 mHandler.sendMessageDelayed(
4510 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4511 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4512 }
4513
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004514 @Override
4515 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004516 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004517 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4518 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519 }
4520
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004521 // In order to implement the compatibility measure for pre-M apps that call
4522 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4523 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4524 // This ensures it has permission to do so.
4525 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4526 if (nc == null) {
4527 return false;
4528 }
4529 int[] transportTypes = nc.getTransportTypes();
4530 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4531 return false;
4532 }
4533 try {
4534 mContext.enforceCallingOrSelfPermission(
4535 android.Manifest.permission.ACCESS_WIFI_STATE,
4536 "ConnectivityService");
4537 } catch (SecurityException e) {
4538 return false;
4539 }
4540 return true;
4541 }
4542
Robert Greenwalt9258c642014-03-26 16:47:06 -07004543 @Override
4544 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4545 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004546 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4547 enforceAccessPermission();
4548 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004549
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004550 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004551 ensureSufficientPermissionsForRequest(networkCapabilities,
4552 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004553 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004554 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4555 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4556 // onLost and onAvailable callbacks when networks move in and out of the background.
4557 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4558 // can't request networks.
4559 restrictBackgroundRequestForCaller(nc);
4560 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004561
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004562 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004563 NetworkRequest.Type.LISTEN);
4564 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004565 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004566
4567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4568 return networkRequest;
4569 }
4570
4571 @Override
4572 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4573 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004574 checkNotNull(operation, "PendingIntent cannot be null.");
4575 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4576 enforceAccessPermission();
4577 }
Etan Cohen859748f2017-04-03 17:42:34 -07004578 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004579 ensureSufficientPermissionsForRequest(networkCapabilities,
4580 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004581
Chalard Jeandda156a2018-01-10 21:19:32 +09004582 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004583 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004584
4585 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004586 NetworkRequest.Type.LISTEN);
4587 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004588 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004589
4590 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004591 }
4592
Erik Klineacdd6392016-07-07 16:50:58 +09004593 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004594 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004595 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004596 mHandler.sendMessage(mHandler.obtainMessage(
4597 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004598 }
4599
4600 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004601 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004602 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004603 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4604 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004605 }
4606
Robert Greenwalta67be032014-05-16 15:49:14 -07004607 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004608 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004609 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4610 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4611 }
4612
4613 @Override
4614 public void unregisterNetworkFactory(Messenger messenger) {
4615 enforceConnectivityInternalPermission();
4616 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4617 }
4618
4619 private void handleUnregisterNetworkFactory(Messenger messenger) {
4620 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4621 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004622 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004623 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004624 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004625 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004626 }
4627
Robert Greenwalt7b816022014-04-18 15:25:25 -07004628 /**
4629 * NetworkAgentInfo supporting a request by requestId.
4630 * These have already been vetted (their Capabilities satisfy the request)
4631 * and the are the highest scored network available.
4632 * the are keyed off the Requests requestId.
4633 */
Hugo Benichicd952782017-09-20 11:20:14 +09004634 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4635 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004636 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004637
Paul Jensen31a94f42015-02-13 14:18:39 -05004638 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4639 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004640 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004641 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4642 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4643 // there may not be a strict 1:1 correlation between the two.
4644 @GuardedBy("mNetworkForNetId")
4645 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004646
Robert Greenwalt7b816022014-04-18 15:25:25 -07004647 // NetworkAgentInfo keyed off its connecting messenger
4648 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004649 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004650 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004651
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004652 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004653 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004654
Paul Jensen2c311d62014-11-17 12:34:51 -05004655 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004656 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004657
Erik Klineda4bfa82015-04-30 12:58:40 +09004658 // Request used to optionally keep mobile data active even when higher
4659 // priority networks like Wi-Fi are active.
4660 private final NetworkRequest mDefaultMobileDataRequest;
4661
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004662 // Request used to optionally keep wifi data active even when higher
4663 // priority networks like ethernet are active.
4664 private final NetworkRequest mDefaultWifiRequest;
4665
Hugo Benichicd952782017-09-20 11:20:14 +09004666 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4667 synchronized (mNetworkForRequestId) {
4668 return mNetworkForRequestId.get(requestId);
4669 }
4670 }
4671
4672 private void clearNetworkForRequest(int requestId) {
4673 synchronized (mNetworkForRequestId) {
4674 mNetworkForRequestId.remove(requestId);
4675 }
4676 }
4677
4678 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4679 synchronized (mNetworkForRequestId) {
4680 mNetworkForRequestId.put(requestId, nai);
4681 }
4682 }
4683
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004684 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004685 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004686 }
4687
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004688 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004689 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004690 }
4691
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004692 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4693 return nri.request.requestId == mDefaultRequest.requestId;
4694 }
4695
Paul Jensen31a94f42015-02-13 14:18:39 -05004696 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004697 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004698 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004699 enforceConnectivityInternalPermission();
4700
Rubin Xu1bb5c082017-09-05 18:40:49 +01004701 LinkProperties lp = new LinkProperties(linkProperties);
4702 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004703 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4704 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004705 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004706 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004707 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004708 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004709 // Make sure the network capabilities reflect what the agent info says.
4710 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004711 synchronized (this) {
4712 nai.networkMonitor.systemReady = mSystemReady;
4713 }
Chalard Jeand771aa02018-04-26 16:16:10 +09004714 final String extraInfo = networkInfo.getExtraInfo();
4715 final String name = TextUtils.isEmpty(extraInfo)
4716 ? nai.networkCapabilities.getSSID() : extraInfo;
4717 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004718 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004719 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004720 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004721 }
4722
Erik Klinee5dac902018-03-04 21:01:01 +09004723 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004724 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004725 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004726 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004727 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004728 }
Erik Klinee5dac902018-03-04 21:01:01 +09004729 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4730 NetworkInfo networkInfo = nai.networkInfo;
4731 nai.networkInfo = null;
4732 updateNetworkInfo(nai, networkInfo);
4733 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004734 }
4735
4736 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004737 LinkProperties newLp = new LinkProperties(networkAgent.linkProperties);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 int netId = networkAgent.network.netId;
4739
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004740 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4741 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004742 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004743 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004744 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004745
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004746 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004747 updateMtu(newLp, oldLp);
4748 // TODO - figure out what to do for clat
4749// for (LinkProperties lp : newLp.getStackedLinks()) {
4750// updateMtu(lp, null);
4751// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004752 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004753
Erik Kline94887872016-04-05 13:30:49 +09004754 updateRoutes(newLp, oldLp, netId);
4755 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004756 // Make sure LinkProperties represents the latest private DNS status.
4757 // This does not need to be done before updateDnses because the
4758 // LinkProperties are not the source of the private DNS configuration.
4759 // updateDnses will fetch the private DNS configuration from DnsManager.
4760 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004761
Hugo Benichi6f62b732017-06-27 15:13:20 +09004762 // Start or stop clat accordingly to network state.
Luke Huang4e25ec62018-09-27 16:58:23 +08004763 networkAgent.updateClat(mNMS);
Paul Jensene0bef712014-12-10 15:12:18 -05004764 if (isDefaultNetwork(networkAgent)) {
4765 handleApplyDefaultProxy(newLp.getHttpProxy());
4766 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004767 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004768 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004769 // TODO - move this check to cover the whole function
4770 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09004771 synchronized (networkAgent) {
4772 networkAgent.linkProperties = newLp;
4773 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004774 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004775 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4776 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004777
4778 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004779 }
4780
Joel Scherpelz668370b2017-06-08 15:35:21 +09004781 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09004782 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004783 // marks on unsupported interfaces is harmless.
4784 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4785 return;
4786 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004787
Joel Scherpelz668370b2017-06-08 15:35:21 +09004788 int mark = mContext.getResources().getInteger(
4789 com.android.internal.R.integer.config_networkWakeupPacketMark);
4790 int mask = mContext.getResources().getInteger(
4791 com.android.internal.R.integer.config_networkWakeupPacketMask);
4792
4793 // Mask/mark of zero will not detect anything interesting.
4794 // Don't install rules unless both values are nonzero.
4795 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004796 return;
4797 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004798
4799 final String prefix = "iface:" + iface;
4800 try {
4801 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08004802 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004803 } else {
Luke Huang674660f2018-09-27 19:33:11 +08004804 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004805 }
4806 } catch (Exception e) {
4807 loge("Exception modifying wakeup packet monitoring: " + e);
4808 }
4809
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004810 }
4811
4812 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4813 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09004814 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01004815 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4816 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004817 for (String iface : interfaceDiff.added) {
4818 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004819 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08004820 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004821 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004822 } catch (Exception e) {
4823 loge("Exception adding interface: " + e);
4824 }
4825 }
4826 for (String iface : interfaceDiff.removed) {
4827 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004828 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004829 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08004830 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004831 } catch (Exception e) {
4832 loge("Exception removing interface: " + e);
4833 }
4834 }
4835 }
4836
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004837 /**
4838 * Have netd update routes from oldLp to newLp.
4839 * @return true if routes changed between oldLp and newLp
4840 */
4841 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004842 // Compare the route diff to determine which routes should be added and removed.
4843 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4844 oldLp != null ? oldLp.getAllRoutes() : null,
4845 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004846
4847 // add routes before removing old in case it helps with continuous connectivity
4848
Chalard Jean4d660112018-06-04 16:52:49 +09004849 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07004850 for (RouteInfo route : routeDiff.added) {
4851 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004852 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004853 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004854 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004855 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004856 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4857 loge("Exception in addRoute for non-gateway: " + e);
4858 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004859 }
4860 }
4861 for (RouteInfo route : routeDiff.added) {
4862 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004863 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004864 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004865 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004866 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004867 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4868 loge("Exception in addRoute for gateway: " + e);
4869 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004870 }
4871 }
4872
4873 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004874 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004875 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004876 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004877 } catch (Exception e) {
4878 loge("Exception in removeRoute: " + e);
4879 }
4880 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004881 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004882 }
Erik Kline41368502015-06-17 13:19:54 +09004883
Erik Kline94887872016-04-05 13:30:49 +09004884 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4885 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4886 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004887 }
Erik Kline94887872016-04-05 13:30:49 +09004888
Erik Kline1742fe12017-12-13 19:40:49 +09004889 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4890 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4891
Erik Klinea24d4592018-01-11 21:07:29 +09004892 if (DBG) {
4893 final Collection<InetAddress> dnses = newLp.getDnsServers();
4894 log("Setting DNS servers for network " + netId + " to " + dnses);
4895 }
Erik Kline94887872016-04-05 13:30:49 +09004896 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004897 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004898 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004899 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004900 }
Erik Kline4edba012017-04-07 15:29:29 +09004901 }
4902
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004903 private String getNetworkPermission(NetworkCapabilities nc) {
4904 // TODO: make these permission strings AIDL constants instead.
4905 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4906 return NetworkManagementService.PERMISSION_SYSTEM;
4907 }
4908 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4909 return NetworkManagementService.PERMISSION_NETWORK;
4910 }
4911 return null;
4912 }
4913
Paul Jensen3d194ea2015-06-16 14:27:36 -04004914 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004915 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4916 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4917 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004918 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004919 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004920 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004921 // Don't complain for VPNs since they're not driven by requests and there is no risk of
4922 // causing a connect/teardown loop.
4923 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
4924 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004925 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09004926 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004927 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4928 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004929 // does not cause any request (that is not a listen) currently matching that agent to
4930 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004931 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004932 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004933 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004934 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004935 }
4936
Paul Jensen3d194ea2015-06-16 14:27:36 -04004937 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004938 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004939 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004940 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004941 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004942 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004943 }
Paul Jensene0988542015-06-25 15:30:08 -04004944 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004945 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004946 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004947 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004948 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004949 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004950 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004951 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004952 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004953 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004954 if (nai.isSuspended()) {
4955 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4956 } else {
4957 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4958 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004959
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004960 return newNc;
4961 }
4962
4963 /**
4964 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4965 *
4966 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4967 * capabilities we manage and store in {@code nai}, such as validated status and captive
4968 * portal status)
4969 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4970 * potentially triggers rematches.
4971 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4972 * change.)
4973 *
4974 * @param oldScore score of the network before any of the changes that prompted us
4975 * to call this function.
4976 * @param nai the network having its capabilities updated.
4977 * @param nc the new network capabilities.
4978 */
4979 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4980 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4981
4982 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004983
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004984 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004985 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004986 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004987 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08004988 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004989 } catch (RemoteException e) {
4990 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004991 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004992 }
4993
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004994 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004995 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004996 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004997 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004998 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004999
Chalard Jeanf213ca12018-01-16 18:43:05 +09005000 updateUids(nai, prevNc, newNc);
5001
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005002 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005003 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5004 // the change we're processing can't affect any requests, it can only affect the listens
5005 // on this network. We might have been called by rematchNetworkAndRequests when a
5006 // network changed foreground state.
5007 processListenRequests(nai, true);
5008 } else {
5009 // If the requestable capabilities have changed or the score changed, we can't have been
5010 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005011 rematchAllNetworksAndRequests(nai, oldScore);
5012 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005013 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005014
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005015 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005016 final boolean oldMetered = prevNc.isMetered();
5017 final boolean newMetered = newNc.isMetered();
5018 final boolean meteredChanged = oldMetered != newMetered;
5019
5020 if (meteredChanged) {
5021 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5022 mRestrictBackground);
5023 }
5024
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005025 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005026 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005027
5028 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005029 if (meteredChanged || roamingChanged) {
5030 notifyIfacesChangedForNetworkStats();
5031 }
5032 }
5033
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005034 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005035 // Tell VPNs about updated capabilities, since they may need to
5036 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005037 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005038 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005039 }
5040
Chalard Jeanf213ca12018-01-16 18:43:05 +09005041 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5042 NetworkCapabilities newNc) {
5043 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5044 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5045 if (null == prevRanges) prevRanges = new ArraySet<>();
5046 if (null == newRanges) newRanges = new ArraySet<>();
5047 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5048
5049 prevRanges.removeAll(newRanges);
5050 newRanges.removeAll(prevRangesCopy);
5051
5052 try {
5053 if (!newRanges.isEmpty()) {
5054 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5055 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005056 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005057 }
5058 if (!prevRanges.isEmpty()) {
5059 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5060 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005061 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005062 }
5063 } catch (Exception e) {
5064 // Never crash!
5065 loge("Exception in updateUids: " + e);
5066 }
5067 }
5068
Hugo Benichief502882017-09-01 01:23:32 +00005069 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07005070 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005071 // Ignore updates for disconnected networks
5072 return;
5073 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005074 // newLp is already a defensive copy.
5075 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00005076 if (VDBG) {
5077 log("Update of LinkProperties for " + nai.name() +
5078 "; created=" + nai.created +
5079 "; everConnected=" + nai.everConnected);
5080 }
5081 LinkProperties oldLp = nai.linkProperties;
5082 synchronized (nai) {
5083 nai.linkProperties = newLp;
5084 }
5085 if (nai.everConnected) {
5086 updateLinkProperties(nai, oldLp);
5087 }
5088 }
5089
Paul Jensenc8b9a742014-09-30 15:37:41 -04005090 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005091 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5092 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005093 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005094 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04005095 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
5096 }
5097 }
5098
Robert Greenwalt7b816022014-04-18 15:25:25 -07005099 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
5100 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07005101 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07005102 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5103 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005104 }
5105 }
5106
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005107 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5108 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005109 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005110 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005111 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5112 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005113 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005114 sendIntent(nri.mPendingIntent, intent);
5115 }
5116 // else not handled
5117 }
5118
5119 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5120 mPendingIntentWakeLock.acquire();
5121 try {
5122 if (DBG) log("Sending " + pendingIntent);
5123 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5124 } catch (PendingIntent.CanceledException e) {
5125 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5126 mPendingIntentWakeLock.release();
5127 releasePendingNetworkRequest(pendingIntent);
5128 }
5129 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5130 }
5131
5132 @Override
5133 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5134 String resultData, Bundle resultExtras) {
5135 if (DBG) log("Finished sending " + pendingIntent);
5136 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005137 // Release with a delay so the receiving client has an opportunity to put in its
5138 // own request.
5139 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005140 }
5141
Chalard Jeanf19db372018-01-26 19:24:40 +09005142 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005143 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005144 if (nri.messenger == null) {
5145 return; // Default request has no msgr
5146 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005147 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005148 // TODO: check if defensive copies of data is needed.
5149 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005150 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005151 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5152 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005153 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005154 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005155 case ConnectivityManager.CALLBACK_AVAILABLE: {
5156 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5157 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005158 // For this notification, arg1 contains the blocked status.
5159 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005160 break;
5161 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005162 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005163 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005164 break;
5165 }
5166 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005167 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005168 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005169 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005170 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005171 break;
5172 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005173 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005174 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005175 break;
5176 }
junyulai05986c62018-08-07 19:50:45 +08005177 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
5178 msg.arg1 = arg1;
5179 break;
5180 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005181 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005182 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005183 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005184 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005185 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005186 String notification = ConnectivityManager.getCallbackName(notificationType);
5187 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005188 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005189 nri.messenger.send(msg);
5190 } catch (RemoteException e) {
5191 // may occur naturally in the race of binder death.
5192 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5193 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005194 }
5195
Hugo Benichidba33db2017-03-23 22:40:44 +09005196 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5197 bundle.putParcelable(t.getClass().getSimpleName(), t);
5198 }
5199
Paul Jensenc8b9a742014-09-30 15:37:41 -04005200 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005201 if (nai.numRequestNetworkRequests() != 0) {
5202 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5203 NetworkRequest nr = nai.requestAt(i);
5204 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005205 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005206 loge("Dead network still had at least " + nr);
5207 break;
5208 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005209 }
5210 nai.asyncChannel.disconnect();
5211 }
5212
Robert Greenwalt7b816022014-04-18 15:25:25 -07005213 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5214 if (oldNetwork == null) {
5215 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5216 return;
5217 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005218 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005219
5220 // If we get here it means that the last linger timeout for this network expired. So there
5221 // must be no other active linger timers, and we must stop lingering.
5222 oldNetwork.clearLingerState();
5223
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005224 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005225 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005226 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005227 } else {
5228 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005229 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5230 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005231 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005232 }
5233
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005234 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005235 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005236
Paul Jensen27b02b72014-07-14 12:03:33 -04005237 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005238 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005239 } catch (Exception e) {
5240 loge("Exception setting default network :" + e);
5241 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005242
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005243 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005244 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005245 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005246 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005247 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005248 }
5249
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005250 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005251 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5252 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5253 NetworkRequest nr = nri.request;
5254 if (!nr.isListen()) continue;
5255 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5256 nai.removeRequest(nri.request.requestId);
5257 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5258 }
5259 }
5260
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005261 if (capabilitiesChanged) {
5262 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5263 }
5264
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005265 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5266 NetworkRequest nr = nri.request;
5267 if (!nr.isListen()) continue;
5268 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5269 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005270 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005271 }
5272 }
5273 }
5274
Paul Jensen2161a8e2014-09-11 11:00:39 -04005275 // Handles a network appearing or improving its score.
5276 //
5277 // - Evaluates all current NetworkRequests that can be
5278 // satisfied by newNetwork, and reassigns to newNetwork
5279 // any such requests for which newNetwork is the best.
5280 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005281 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005282 // needed. A network is needed if it is the best network for
5283 // one or more NetworkRequests, or if it is a VPN.
5284 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005285 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005286 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005287 //
5288 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5289 // networks that have no chance (i.e. even if validated)
5290 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005291 //
5292 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5293 // it does not remove NetworkRequests that other Networks could better satisfy.
5294 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5295 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5296 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005297 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005298 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005299 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5300 // performed to tear down unvalidated networks that have no chance (i.e. even if
5301 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005302 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005303 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005304 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005305 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005306 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005307 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005308
5309 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5310 final int score = newNetwork.getCurrentScore();
5311
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005312 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005313
Paul Jensen2161a8e2014-09-11 11:00:39 -04005314 // Find and migrate to this Network any NetworkRequests for
5315 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005316 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5317 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005318 NetworkCapabilities nc = newNetwork.networkCapabilities;
5319 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005320 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005321 // Process requests in the first pass and listens in the second pass. This allows us to
5322 // change a network's capabilities depending on which requests it has. This is only
5323 // correct if the change in capabilities doesn't affect whether the network satisfies
5324 // requests or not, and doesn't affect the network's score.
5325 if (nri.request.isListen()) continue;
5326
Hugo Benichicd952782017-09-20 11:20:14 +09005327 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005328 final boolean satisfies = newNetwork.satisfies(nri.request);
5329 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005330 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005331 log("Network " + newNetwork.name() + " was already satisfying" +
5332 " request " + nri.request.requestId + ". No change.");
5333 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005334 keep = true;
5335 continue;
5336 }
5337
5338 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005339 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005340 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005341 // next check if it's better than any current network we're using for
5342 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005343 if (VDBG) {
5344 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005345 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005346 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005347 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005348 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005349 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005350 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005351 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005352 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005353 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005354 affectedNetworks.add(currentNetwork);
5355 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005356 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005357 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005358 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005359 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005360 if (!newNetwork.addRequest(nri.request)) {
5361 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5362 }
5363 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005364 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005365 // Tell NetworkFactories about the new score, so they can stop
5366 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005367 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005368 // network. Think about if there is a way to reduce this. Push
5369 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005370 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005371 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005372 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005373 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005374 if (currentNetwork != null) {
5375 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5376 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005377 }
5378 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005379 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005380 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5381 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005382 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005383 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5384 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5385 // This means this code doesn't have to handle the case where "currentNetwork" no
5386 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5387 if (DBG) {
5388 log("Network " + newNetwork.name() + " stopped satisfying" +
5389 " request " + nri.request.requestId);
5390 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005391 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005392 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005393 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005394 sendUpdatedScoreToFactories(nri.request, 0);
5395 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005396 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5397 newNetwork.name() +
5398 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005399 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005400 // TODO: Technically, sending CALLBACK_LOST here is
5401 // incorrect if there is a replacement network currently
5402 // connected that can satisfy nri, which is a request
5403 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005404 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5405 // so this code is only incorrect for a network that loses
5406 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005407 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005408 }
5409 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005410 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005411 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005412 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005413 makeDefault(newNetwork);
5414 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005415 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005416 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005417 // Have a new default network, release the transition wakelock in
5418 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005419 }
5420
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005421 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5422 Slog.wtf(TAG, String.format(
5423 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005424 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005425 }
5426 if (newNetwork.getCurrentScore() != score) {
5427 Slog.wtf(TAG, String.format(
5428 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005429 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005430 }
5431
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005432 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005433 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5434 // If the network went from background to foreground or vice versa, we need to update
5435 // its foreground state. It is safe to do this after rematching the requests because
5436 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5437 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005438 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005439 } else {
5440 processListenRequests(newNetwork, false);
5441 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005442
Paul Jensencf4c2c62015-07-01 14:16:32 -04005443 // do this after the default net is switched, but
5444 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005445 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005446
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005447 // Linger any networks that are no longer needed. This should be done after sending the
5448 // available callback for newNetwork.
5449 for (NetworkAgentInfo nai : affectedNetworks) {
5450 updateLingerState(nai, now);
5451 }
5452 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5453 // does not need to be done in any particular order.
5454 updateLingerState(newNetwork, now);
5455
Paul Jensencf4c2c62015-07-01 14:16:32 -04005456 if (isNewDefault) {
5457 // Maintain the illusion: since the legacy API only
5458 // understands one network at a time, we must pretend
5459 // that the current default network disconnected before
5460 // the new one connected.
5461 if (oldDefaultNetwork != null) {
5462 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5463 oldDefaultNetwork, true);
5464 }
5465 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5466 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5467 notifyLockdownVpn(newNetwork);
5468 }
5469
Robert Greenwalt7b816022014-04-18 15:25:25 -07005470 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005471 // Notify battery stats service about this network, both the normal
5472 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005473 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005474 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005475 final IBatteryStats bs = BatteryStatsService.getService();
5476 final int type = newNetwork.networkInfo.getType();
5477
5478 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5479 bs.noteNetworkInterfaceType(baseIface, type);
5480 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5481 final String stackedIface = stacked.getInterfaceName();
5482 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005483 }
5484 } catch (RemoteException ignored) {
5485 }
5486
Robert Greenwalt152ed372014-12-17 17:19:53 -08005487 // This has to happen after the notifyNetworkCallbacks as that tickles each
5488 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005489 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005490 // and will generally do a dns request so they can ensureRouteToHost and if
5491 // they do that before the callbacks happen they'll use the default network.
5492 //
5493 // TODO: Is there still a race here? We send the broadcast
5494 // after sending the callback, but if the app can receive the
5495 // broadcast before the callback, it might still break.
5496 //
5497 // This *does* introduce a race where if the user uses the new api
5498 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5499 // they may get old info. Reverse this after the old startUsing api is removed.
5500 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005501 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5502 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005503 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005504 // legacy type tracker filters out repeat adds
5505 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5506 }
5507 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005508
5509 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5510 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5511 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5512 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5513 if (newNetwork.isVPN()) {
5514 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5515 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005516 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005517 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5518 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005519 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005520 if (nai.getLingerExpiry() > 0) {
5521 // This network has active linger timers and no requests, but is not
5522 // lingering. Linger it.
5523 //
5524 // One way (the only way?) this can happen if this network is unvalidated
5525 // and became unneeded due to another network improving its score to the
5526 // point where this network will no longer be able to satisfy any requests
5527 // even if it validates.
5528 updateLingerState(nai, now);
5529 } else {
5530 if (DBG) log("Reaping " + nai.name());
5531 teardownUnneededNetwork(nai);
5532 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005533 }
5534 }
5535 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005536 }
5537
Paul Jensen1c7ba022015-06-16 14:27:36 -04005538 /**
5539 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5540 * being disconnected.
5541 * @param changed If only one Network's score or capabilities have been modified since the last
5542 * time this function was called, pass this Network in this argument, otherwise pass
5543 * null.
5544 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5545 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5546 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5547 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5548 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005549 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005550 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005551 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5552 // to avoid the slowness. It is not simply enough to process just "changed", for
5553 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005554 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005555
5556 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5557 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5558 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005559 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005560 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005561 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005562 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005563 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5564 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5565 // Rematch higher scoring networks first to prevent requests first matching a lower
5566 // scoring network and then a higher scoring network, which could produce multiple
5567 // callbacks and inadvertently unlinger networks.
5568 Arrays.sort(nais);
5569 for (NetworkAgentInfo nai : nais) {
5570 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005571 // Only reap the last time through the loop. Reaping before all rematching
5572 // is complete could incorrectly teardown a network that hasn't yet been
5573 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005574 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005575 : ReapUnvalidatedNetworks.REAP,
5576 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005577 }
5578 }
5579 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005580
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005581 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005582 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005583 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005584 // For now only update icons for default connection.
5585 // TODO: Update WiFi and cellular icons separately. b/17237507
5586 if (!isDefaultNetwork(nai)) return;
5587
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005588 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005589 // Don't repeat publish.
5590 if (newInetCondition == mDefaultInetConditionPublished) return;
5591
5592 mDefaultInetConditionPublished = newInetCondition;
5593 sendInetConditionBroadcast(nai.networkInfo);
5594 }
5595
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005596 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005597 synchronized (mVpns) {
5598 if (mLockdownTracker != null) {
5599 if (nai != null && nai.isVPN()) {
5600 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5601 } else {
5602 mLockdownTracker.onNetworkInfoChanged();
5603 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005604 }
5605 }
5606 }
5607
Robert Greenwalt7b816022014-04-18 15:25:25 -07005608 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005609 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005610 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005611 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005612 synchronized (networkAgent) {
5613 oldInfo = networkAgent.networkInfo;
5614 networkAgent.networkInfo = newInfo;
5615 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005616 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005617
Robert Greenwalt7b816022014-04-18 15:25:25 -07005618 if (DBG) {
5619 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5620 (oldInfo == null ? "null" : oldInfo.getState()) +
5621 " to " + state);
5622 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005623
Robin Lee585e2482016-05-01 23:00:00 +01005624 if (!networkAgent.created
5625 && (state == NetworkInfo.State.CONNECTED
5626 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005627
5628 // A network that has just connected has zero requests and is thus a foreground network.
5629 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5630
Robert Greenwalt7b816022014-04-18 15:25:25 -07005631 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005632 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005633 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08005634 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005635 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5636 (networkAgent.networkMisc == null ||
5637 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005638 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08005639 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005640 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005641 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005642 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005643 loge("Error creating network " + networkAgent.network.netId + ": "
5644 + e.getMessage());
5645 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005646 }
Paul Jenseneec75412014-08-04 12:21:19 -04005647 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005648 }
5649
5650 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5651 networkAgent.everConnected = true;
5652
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005653 if (networkAgent.linkProperties == null) {
5654 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5655 }
5656
Erik Kline736353a2018-03-21 07:18:33 -07005657 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005658 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005659
Paul Jensenca8f16a2014-05-09 12:47:55 -04005660 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005661 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005662
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005663 if (networkAgent.isVPN()) {
5664 // Temporarily disable the default proxy (not global).
Chalard Jean52c2aa72018-06-07 16:44:04 +09005665 synchronized (mProxyTracker.mProxyLock) {
5666 if (!mProxyTracker.mDefaultProxyDisabled) {
5667 mProxyTracker.mDefaultProxyDisabled = true;
5668 if (mProxyTracker.mGlobalProxy == null
5669 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005670 mProxyTracker.sendProxyBroadcast(null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005671 }
5672 }
5673 }
5674 // TODO: support proxy per network.
5675 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005676
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005677 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5678 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5679 // capabilities, so it only needs to be done once on initial connect, not every time the
5680 // network's capabilities change. Note that we do this before rematching the network,
5681 // so we could decide to tear it down immediately afterwards. That's fine though - on
5682 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5683 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005684 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005685
Paul Jensen2161a8e2014-09-11 11:00:39 -04005686 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005687 final long now = SystemClock.elapsedRealtime();
5688 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005689
5690 // This has to happen after matching the requests, because callbacks are just requests.
5691 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005692 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005693 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005694 if (networkAgent.isVPN()) {
Chalard Jean52c2aa72018-06-07 16:44:04 +09005695 synchronized (mProxyTracker.mProxyLock) {
5696 if (mProxyTracker.mDefaultProxyDisabled) {
5697 mProxyTracker.mDefaultProxyDisabled = false;
5698 if (mProxyTracker.mGlobalProxy == null
5699 && mProxyTracker.mDefaultProxy != null) {
Chalard Jean3319c622018-06-07 19:30:29 +09005700 mProxyTracker.sendProxyBroadcast(mProxyTracker.mDefaultProxy);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005701 }
5702 }
5703 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005704 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005705 }
Chalard Jean392971c2018-05-11 20:19:20 +09005706 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005707 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5708 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09005709 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07005710 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005711 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005712 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005713 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5714 networkAgent.networkCapabilities);
5715 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5716 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005717 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5718 ConnectivityManager.CALLBACK_SUSPENDED :
5719 ConnectivityManager.CALLBACK_RESUMED));
5720 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005721 }
5722 }
5723
Robert Greenwaltac96c522014-06-03 16:43:57 -07005724 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005725 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005726 if (score < 0) {
5727 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5728 "). Bumping score to min of 0");
5729 score = 0;
5730 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005731
Paul Jensen2161a8e2014-09-11 11:00:39 -04005732 final int oldScore = nai.getCurrentScore();
5733 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005734
Paul Jensen85cf78e2015-06-25 13:25:07 -04005735 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005736
Paul Jensenc8b9a742014-09-30 15:37:41 -04005737 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005738 }
5739
Erik Klinec75d4fa2017-02-15 19:59:17 +09005740 // Notify only this one new request of the current state. Transfer all the
5741 // current state by calling NetworkCapabilities and LinkProperties callbacks
5742 // so that callers can be guaranteed to have as close to atomicity in state
5743 // transfer as can be supported by this current API.
5744 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005745 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005746 if (nri.mPendingIntent != null) {
5747 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5748 // Attempt no subsequent state pushes where intents are involved.
5749 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005750 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005751
junyulai05986c62018-08-07 19:50:45 +08005752 final boolean metered = nai.networkCapabilities.isMetered();
5753 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
5754 metered, mRestrictBackground);
5755 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
5756 }
5757
5758 /**
5759 * Notify of the blocked state apps with a registered callback matching a given NAI.
5760 *
5761 * Unlike other callbacks, blocked status is different between each individual uid. So for
5762 * any given nai, all requests need to be considered according to the uid who filed it.
5763 *
5764 * @param nai The target NetworkAgentInfo.
5765 * @param oldMetered True if the previous network capabilities is metered.
5766 * @param newRestrictBackground True if data saver is enabled.
5767 */
5768 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
5769 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
5770
5771 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5772 NetworkRequest nr = nai.requestAt(i);
5773 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5774 final int uidRules = mUidRules.get(nri.mUid);
5775 final boolean oldBlocked, newBlocked;
5776 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
5777 // between these two calls.
5778 synchronized (mVpns) {
5779 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
5780 oldRestrictBackground);
5781 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
5782 newRestrictBackground);
5783 }
5784 if (oldBlocked != newBlocked) {
5785 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
5786 encodeBool(newBlocked));
5787 }
5788 }
5789 }
5790
5791 /**
5792 * Notify apps with a given UID of the new blocked state according to new uid rules.
5793 * @param uid The uid for which the rules changed.
5794 * @param newRules The new rules to apply.
5795 */
5796 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
5797 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5798 final boolean metered = nai.networkCapabilities.isMetered();
5799 final boolean oldBlocked, newBlocked;
5800 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
5801 // rules changed event. And this function actually loop through all connected nai and
5802 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
5803 // Reduce the number of locking or optimize the use of lock are likely needed in future.
5804 synchronized (mVpns) {
5805 oldBlocked = isUidNetworkingWithVpnBlocked(
5806 uid, mUidRules.get(uid), metered, mRestrictBackground);
5807 newBlocked = isUidNetworkingWithVpnBlocked(
5808 uid, newRules, metered, mRestrictBackground);
5809 }
5810 if (oldBlocked == newBlocked) {
5811 return;
5812 }
5813 final int arg = encodeBool(newBlocked);
5814 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5815 NetworkRequest nr = nai.requestAt(i);
5816 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5817 if (nri != null && nri.mUid == uid) {
5818 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
5819 }
5820 }
5821 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005822 }
5823
Robert Greenwalt8d482522015-06-24 13:23:42 -07005824 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005825 // The NetworkInfo we actually send out has no bearing on the real
5826 // state of affairs. For example, if the default connection is mobile,
5827 // and a request for HIPRI has just gone away, we need to pretend that
5828 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5829 // the state to DISCONNECTED, even though the network is of type MOBILE
5830 // and is still connected.
5831 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5832 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005833 if (state != DetailedState.DISCONNECTED) {
5834 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005835 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005836 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005837 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005838 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5839 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5840 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5841 if (info.isFailover()) {
5842 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5843 nai.networkInfo.setFailover(false);
5844 }
5845 if (info.getReason() != null) {
5846 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5847 }
5848 if (info.getExtraInfo() != null) {
5849 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5850 }
5851 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005852 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005853 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005854 if (newDefaultAgent != null) {
5855 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5856 newDefaultAgent.networkInfo);
5857 } else {
5858 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5859 }
5860 }
5861 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5862 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005863 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005864 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005865 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005866 }
5867 }
5868 }
5869
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005870 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005871 if (VDBG) {
5872 String notification = ConnectivityManager.getCallbackName(notifyType);
5873 log("notifyType " + notification + " for " + networkAgent.name());
5874 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005875 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5876 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005877 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5878 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005879 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5880 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005881 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005882 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005883 } else {
5884 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5885 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005886 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005887 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005888
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005889 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5890 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5891 }
5892
Jeff Sharkey69736342014-12-08 14:50:12 -08005893 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005894 * Returns the list of all interfaces that could be used by network traffic that does not
5895 * explicitly specify a network. This includes the default network, but also all VPNs that are
5896 * currently connected.
5897 *
5898 * Must be called on the handler thread.
5899 */
5900 private Network[] getDefaultNetworks() {
5901 ArrayList<Network> defaultNetworks = new ArrayList<>();
5902 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5903 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5904 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5905 defaultNetworks.add(nai.network);
5906 }
5907 }
5908 return defaultNetworks.toArray(new Network[0]);
5909 }
5910
5911 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005912 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5913 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005914 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005915 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005916 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005917 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005918 } catch (Exception ignored) {
5919 }
5920 }
5921
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005922 @Override
5923 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005924 int user = UserHandle.getUserId(Binder.getCallingUid());
5925 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005926 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005927 return mVpns.get(user).addAddress(address, prefixLength);
5928 }
5929 }
5930
5931 @Override
5932 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005933 int user = UserHandle.getUserId(Binder.getCallingUid());
5934 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005935 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005936 return mVpns.get(user).removeAddress(address, prefixLength);
5937 }
5938 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005939
5940 @Override
5941 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005942 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005943 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005944 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005945 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005946 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005947 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005948 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005949 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005950 }
5951 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005952 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005953
5954 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005955 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005956 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005957 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005958 }
5959
5960 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005961 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5962 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5963 enforceKeepalivePermission();
5964 mKeepaliveTracker.startNattKeepalive(
5965 getNetworkAgentInfoForNetwork(network),
5966 intervalSeconds, messenger, binder,
5967 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5968 }
5969
5970 @Override
5971 public void stopKeepalive(Network network, int slot) {
5972 mHandler.sendMessage(mHandler.obtainMessage(
5973 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5974 }
5975
5976 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005977 public void factoryReset() {
5978 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005979
5980 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5981 return;
5982 }
5983
Robin Lee3b3dd942015-05-12 18:14:58 +01005984 final int userId = UserHandle.getCallingUserId();
5985
Stuart Scottf1fb3972015-04-02 18:00:02 -07005986 // Turn airplane mode off
5987 setAirplaneMode(false);
5988
Stuart Scotte3e314d2015-04-20 14:07:45 -07005989 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5990 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005991 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005992 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005993 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005994 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005995 }
5996
Stuart Scotte3e314d2015-04-20 14:07:45 -07005997 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005998 // Remove always-on package
5999 synchronized (mVpns) {
6000 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6001 if (alwaysOnPackage != null) {
6002 setAlwaysOnVpnPackage(userId, null, false);
6003 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6004 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006005
Hugo Benichi69744342017-11-27 10:57:16 +09006006 // Turn Always-on VPN off
6007 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6008 final long ident = Binder.clearCallingIdentity();
6009 try {
6010 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6011 mLockdownEnabled = false;
6012 setLockdownTracker(null);
6013 } finally {
6014 Binder.restoreCallingIdentity(ident);
6015 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006016 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006017
Hugo Benichi69744342017-11-27 10:57:16 +09006018 // Turn VPN off
6019 VpnConfig vpnConfig = getVpnConfig(userId);
6020 if (vpnConfig != null) {
6021 if (vpnConfig.legacy) {
6022 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6023 } else {
6024 // Prevent this app (packagename = vpnConfig.user) from initiating
6025 // VPN connections in the future without user intervention.
6026 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006027
Hugo Benichi69744342017-11-27 10:57:16 +09006028 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6029 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006030 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006031 }
6032 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006033
6034 Settings.Global.putString(mContext.getContentResolver(),
6035 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006036 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006037
Ricky Wai44dcbde2018-01-23 04:09:45 +00006038 @Override
6039 public byte[] getNetworkWatchlistConfigHash() {
6040 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6041 if (nwm == null) {
6042 loge("Unable to get NetworkWatchlistManager");
6043 return null;
6044 }
6045 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6046 return nwm.getWatchlistConfigHash();
6047 }
6048
Paul Jensencf4c2c62015-07-01 14:16:32 -04006049 @VisibleForTesting
6050 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
6051 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
6052 return new NetworkMonitor(context, handler, nai, defaultRequest);
6053 }
Erik Kline48f12f22016-04-14 17:30:59 +09006054
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006055 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006056 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6057 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006058 }
6059
6060 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006061 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6062 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6063 }
6064
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006065 @VisibleForTesting
6066 public boolean hasService(String name) {
6067 return ServiceManager.checkService(name) != null;
6068 }
6069
Hugo Benichi64901e52017-10-19 14:42:40 +09006070 @VisibleForTesting
6071 protected IpConnectivityMetrics.Logger metricsLogger() {
6072 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6073 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006074 }
6075
6076 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006077 int[] transports = nai.networkCapabilities.getTransportTypes();
6078 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006079 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006080
6081 private static boolean toBool(int encodedBoolean) {
6082 return encodedBoolean != 0; // Only 0 means false.
6083 }
6084
6085 private static int encodeBool(boolean b) {
6086 return b ? 1 : 0;
6087 }
mswest46386886f2018-03-12 10:34:34 -07006088
6089 @Override
6090 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6091 FileDescriptor err, String[] args, ShellCallback callback,
6092 ResultReceiver resultReceiver) {
6093 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6094 }
6095
6096 private class ShellCmd extends ShellCommand {
6097
6098 @Override
6099 public int onCommand(String cmd) {
6100 if (cmd == null) {
6101 return handleDefaultCommands(cmd);
6102 }
6103 final PrintWriter pw = getOutPrintWriter();
6104 try {
6105 switch (cmd) {
6106 case "airplane-mode":
6107 final String action = getNextArg();
6108 if ("enable".equals(action)) {
6109 setAirplaneMode(true);
6110 return 0;
6111 } else if ("disable".equals(action)) {
6112 setAirplaneMode(false);
6113 return 0;
6114 } else if (action == null) {
6115 final ContentResolver cr = mContext.getContentResolver();
6116 final int enabled = Settings.Global.getInt(cr,
6117 Settings.Global.AIRPLANE_MODE_ON);
6118 pw.println(enabled == 0 ? "disabled" : "enabled");
6119 return 0;
6120 } else {
6121 onHelp();
6122 return -1;
6123 }
6124 default:
6125 return handleDefaultCommands(cmd);
6126 }
6127 } catch (Exception e) {
6128 pw.println(e);
6129 }
6130 return -1;
6131 }
6132
6133 @Override
6134 public void onHelp() {
6135 PrintWriter pw = getOutPrintWriter();
6136 pw.println("Connectivity service commands:");
6137 pw.println(" help");
6138 pw.println(" Print this help text.");
6139 pw.println(" airplane-mode [enable|disable]");
6140 pw.println(" Turn airplane mode on or off.");
6141 pw.println(" airplane-mode");
6142 pw.println(" Get airplane mode.");
6143 }
6144 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006145
6146 /**
6147 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6148 * for testing.
6149 */
6150 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6151 if (checkNetworkStackPermission()) {
6152 return null;
6153 }
6154 final int uid = Binder.getCallingUid();
6155 final int user = UserHandle.getUserId(uid);
6156 synchronized (mVpns) {
6157 Vpn vpn = mVpns.get(user);
6158 try {
6159 if (vpn.getVpnInfo().ownerUid == uid) return vpn;
6160 } catch (NullPointerException e) {
6161 /* vpn is null, or VPN is not connected and getVpnInfo() is null. */
6162 }
6163 }
6164 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6165 + "permission");
6166 }
6167
6168 /**
6169 * @param connectionInfo the connection to resolve.
6170 * @return {@code uid} if the connection is found and the app has permission to observe it
6171 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6172 * connection is not found.
6173 */
6174 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6175 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6176 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6177 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6178 }
6179
6180 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6181 connectionInfo.local, connectionInfo.remote);
6182
6183 /* Filter out Uids not associated with the VPN. */
6184 if (vpn != null && !vpn.appliesToUid(uid)) {
6185 return INVALID_UID;
6186 }
6187
6188 return uid;
6189 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006190}