blob: b767915ed10294757f03f5ca46f01a6819ca2ecd [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
lucasline252a742019-03-12 13:08:03 +080028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090029import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040030import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090032import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
34import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
lucasline252a742019-03-12 13:08:03 +080038import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090039import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060040import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080041import static android.net.NetworkPolicyManager.RULE_NONE;
42import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090043import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070044import static android.os.Process.INVALID_UID;
45import static android.system.OsConstants.IPPROTO_TCP;
46import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060047
Hugo Benichia0385682017-03-22 17:07:57 +090048import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060049
Wenchao Tongf5ea3402015-03-04 13:26:38 -080050import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080051import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090052import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070053import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070054import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.ContentResolver;
56import android.content.Context;
57import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070058import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070059import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070060import android.database.ContentObserver;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090061import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070062import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.ConnectivityManager;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090064import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.IConnectivityManager;
Luke Huang65914772019-03-16 00:31:46 +080066import android.net.IDnsResolver;
dalyk7301aa42018-03-05 12:42:22 -050067import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080068import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050069import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070070import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090071import android.net.INetworkMonitor;
72import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070073import android.net.INetworkPolicyListener;
74import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070075import android.net.INetworkStatsService;
junyulai7c469172019-01-16 20:23:34 +080076import android.net.ISocketKeepaliveCallback;
markchien26299ed2019-02-27 14:56:11 +080077import android.net.ITetheringEventCallback;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090078import android.net.InetAddresses;
79import android.net.IpPrefix;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080080import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070081import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010082import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080083import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070084import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070085import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070086import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070087import android.net.NetworkConfig;
Chalard Jean05ab6812018-05-02 21:14:54 +090088import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070090import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070091import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090092import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070093import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070094import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070095import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090096import android.net.NetworkStack;
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +090097import android.net.NetworkStackClient;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070098import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070099import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +0000100import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900101import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -0400102import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -0700103import android.net.RouteInfo;
junyulai06835112019-01-03 18:50:15 +0800104import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400105import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -0400106import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600107import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900108import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900109import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700110import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900111import android.net.shared.NetworkMonitorUtils;
112import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900113import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900114import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800116import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700117import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700119import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700120import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700121import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.os.Looper;
123import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700124import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700125import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900126import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700127import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700128import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700129import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800130import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900131import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900132import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700133import android.os.ShellCallback;
134import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900135import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700136import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400137import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700139import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700140import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700141import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700142import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900143import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700144import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600145import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900146import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800147import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700148import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500149import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700150import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700151import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Wink Savilleab9321d2013-06-29 21:10:57 -0700153import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400154import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400155import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700156import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANde602212019-01-30 15:22:01 +0900157import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700158import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700159import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800160import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700161import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900162import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700163import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600164import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700165import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900166import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900167import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700168import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700169import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400170import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900171import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500172import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900173import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900174import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100175import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700176import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900177import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700178import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600179import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900180import com.android.server.connectivity.NetworkNotificationManager;
181import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700182import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900183import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800184import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700185import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100186import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500187import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700188import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700189import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900190import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700191import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600192
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700193import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700194
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700195import org.xmlpull.v1.XmlPullParser;
196import org.xmlpull.v1.XmlPullParserException;
197
198import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700200import java.io.FileNotFoundException;
201import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700202import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700204import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700205import java.net.InetAddress;
206import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700207import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700208import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700209import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900210import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800211import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700212import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700213import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700214import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700215import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700216import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900217import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600218import java.util.SortedSet;
219import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
221/**
222 * @hide
223 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800224public class ConnectivityService extends IConnectivityManager.Stub
225 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900226 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
Chalard Jean4133a122018-06-04 13:33:12 +0900228 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900229 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900230 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900231 private static final String NETWORK_ARG = "networks";
232 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900233
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900234 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900235 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
236 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900238 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700239
Jeff Sharkey899223b2012-08-04 15:24:58 -0700240 // TODO: create better separation between radio types and network types
241
Robert Greenwalt42acef32009-08-12 16:08:25 -0700242 // how long to wait before switching back to a radio's default network
243 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
244 // system property that can override the above value
245 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
246 "android.telephony.apn-restore";
247
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900248 // How long to wait before putting up a "This network doesn't have an Internet connection,
249 // connect anyway?" dialog after the user selects a network that doesn't validate.
250 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
251
lucaslind2e045e02019-01-24 15:55:30 +0800252 // How long to dismiss network notification.
253 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
254
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900255 // Default to 30s linger time-out. Modifiable only for testing.
256 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
257 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
258 @VisibleForTesting
259 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
260
Jeremy Joslin79294842014-12-03 17:15:28 -0800261 // How long to delay to removal of a pending intent based request.
262 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
263 private final int mReleasePendingIntentDelayMs;
264
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900265 private MockableSystemProperties mSystemProperties;
266
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800267 private Tethering mTethering;
268
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700269 private final PermissionMonitor mPermissionMonitor;
270
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700271 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700272
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900273 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700274 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900275 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700276
Hugo Benichi69744342017-11-27 10:57:16 +0900277 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
278 // a direct call to LockdownVpnTracker.isEnabled().
279 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700280 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900281 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700282 private LockdownVpnTracker mLockdownTracker;
283
junyulai05986c62018-08-07 19:50:45 +0800284 /**
285 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
286 * handler thread, they don't need a lock.
287 */
288 private SparseIntArray mUidRules = new SparseIntArray();
289 /** Flag indicating if background data is restricted. */
290 private boolean mRestrictBackground;
291
Erik Klineda4bfa82015-04-30 12:58:40 +0900292 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700293 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700294 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
Luke Huang4e25ec62018-09-27 16:58:23 +0800296 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800297 @VisibleForTesting
Luke Huang65914772019-03-16 00:31:46 +0800298 protected IDnsResolver mDnsResolver;
299 @VisibleForTesting
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800300 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800301 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700302 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900303 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700304
Benedict Wonga341fbc2018-11-09 14:45:34 -0800305 /**
306 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
307 * instances.
308 */
309 @GuardedBy("mTNSLock")
310 private TestNetworkService mTNS;
311
312 private final Object mTNSLock = new Object();
313
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700314 private String mCurrentTcpBufferSizes;
315
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900316 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900317 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
318 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900319
Paul Jensenb10e37f2014-11-25 12:33:08 -0500320 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400321 // Tear down networks that have no chance (e.g. even if validated) of becoming
322 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500323 // all networks have been rematched against all NetworkRequests.
324 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400325 // Don't reap networks. This should be passed when some networks have not yet been
326 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500327 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900328 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500329
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900330 private enum UnneededFor {
331 LINGER, // Determine whether this network is unneeded and should be lingered.
332 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
333 }
334
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700335 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700336 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700337 * from one net to another. Clear happens when we get a new
338 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
339 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700340 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700341 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700342
Robert Greenwalt434203a2010-10-11 16:00:27 -0700343 /**
344 * used internally to reload global proxy settings
345 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700346 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700347
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700348 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400349 * PAC manager has received new port.
350 */
351 private static final int EVENT_PROXY_HAS_CHANGED = 16;
352
Robert Greenwalte049c232014-04-11 15:53:27 -0700353 /**
354 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700355 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700356 */
357 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
358
Robert Greenwalt7b816022014-04-18 15:25:25 -0700359 /**
360 * used internally when registering NetworkAgents
361 * obj = Messenger
362 */
363 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
364
Robert Greenwalt9258c642014-03-26 16:47:06 -0700365 /**
366 * used to add a network request
367 * includes a NetworkRequestInfo
368 */
369 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
370
371 /**
372 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900373 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700374 * cancel it.
375 * includes a NetworkRequestInfo
376 */
377 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
378
379 /**
380 * used to add a network listener - no request
381 * includes a NetworkRequestInfo
382 */
383 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
384
385 /**
386 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400387 * arg1 = UID of caller
388 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700389 */
390 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
391
Robert Greenwalta67be032014-05-16 15:49:14 -0700392 /**
393 * used internally when registering NetworkFactories
394 * obj = Messenger
395 */
396 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
397
Robert Greenwalt27711812014-06-25 16:45:57 -0700398 /**
399 * used internally to expire a wakelock when transitioning
400 * from one net to another. Expire happens when we fail to find
401 * a new network (typically after 1 minute) -
402 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
403 * a replacement network.
404 */
405 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
406
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700407 /**
408 * Used internally to indicate the system is ready.
409 */
410 private static final int EVENT_SYSTEM_READY = 25;
411
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800412 /**
413 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400414 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800415 */
416 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
417
418 /**
419 * used to remove a pending intent and its associated network request.
420 * arg1 = UID of caller
421 * obj = PendingIntent
422 */
423 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
424
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900425 /**
426 * used to specify whether a network should be used even if unvalidated.
427 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
428 * arg2 = whether to remember this choice in the future (1 or 0)
429 * obj = network
430 */
431 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
432
433 /**
434 * used to ask the user to confirm a connection to an unvalidated network.
435 * obj = network
436 */
437 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700438
Erik Klineda4bfa82015-04-30 12:58:40 +0900439 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700440 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900441 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700442 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900443
Paul Jensen694f2b82015-06-17 14:15:39 -0400444 /**
445 * used to add a network listener with a pending intent
446 * obj = NetworkRequestInfo
447 */
448 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
449
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900450 /**
451 * used to specify whether a network should not be penalized when it becomes unvalidated.
452 */
453 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
454
455 /**
456 * used to trigger revalidation of a network.
457 */
458 private static final int EVENT_REVALIDATE_NETWORK = 36;
459
Erik Klinea24d4592018-01-11 21:07:29 +0900460 // Handle changes in Private DNS settings.
461 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
462
dalyk7301aa42018-03-05 12:42:22 -0500463 // Handle private DNS validation status updates.
464 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
465
junyulai05986c62018-08-07 19:50:45 +0800466 /**
467 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
468 */
469 private static final int EVENT_UID_RULES_CHANGED = 39;
470
471 /**
472 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
473 */
474 private static final int EVENT_DATA_SAVER_CHANGED = 40;
475
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900476 /**
477 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
478 * been tested.
479 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
480 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
481 * arg2 = NetID.
482 */
483 public static final int EVENT_NETWORK_TESTED = 41;
484
485 /**
486 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
487 * config was resolved.
488 * obj = PrivateDnsConfig
489 * arg2 = netid
490 */
491 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
492
493 /**
494 * Request ConnectivityService display provisioning notification.
495 * arg1 = Whether to make the notification visible.
496 * arg2 = NetID.
497 * obj = Intent to be launched when notification selected by user, null if !arg1.
498 */
499 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
500
501 /**
lucaslind2e045e02019-01-24 15:55:30 +0800502 * This event can handle dismissing notification by given network id.
503 */
504 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
505
506 /**
lucasline252a742019-03-12 13:08:03 +0800507 * Used to specify whether a network should be used even if connectivity is partial.
508 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
509 * false)
510 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
511 * obj = network
512 */
513 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
514
515 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900516 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
517 * should be shown.
518 */
519 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
520
521 /**
522 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
523 * should be hidden.
524 */
525 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
526
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900527 private static String eventName(int what) {
528 return sMagicDecoderRing.get(what, Integer.toString(what));
529 }
530
Luke Huang65914772019-03-16 00:31:46 +0800531 private static IDnsResolver getDnsResolver() {
532 return IDnsResolver.Stub
533 .asInterface(ServiceManager.getService("dnsresolver"));
534 }
535
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900536 /** Handler thread used for both of the handlers below. */
537 @VisibleForTesting
538 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700539 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700540 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700541 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700542 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900543 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700544
Mike Lockwood0f79b542009-08-14 14:18:49 -0400545 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800546 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400547
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700548 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700549 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800550 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700551
Chalard Jean52c2aa72018-06-07 16:44:04 +0900552 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
553 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000554 @VisibleForTesting
555 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400556
Erik Klineda4bfa82015-04-30 12:58:40 +0900557 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700558
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400559 private UserManager mUserManager;
560
Chalard Jean4133a122018-06-04 13:33:12 +0900561 private NetworkConfig[] mNetConfigs;
562 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700563
Robert Greenwalt50393202011-06-21 17:26:14 -0700564 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900565 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700566
Chalard Jean4133a122018-06-04 13:33:12 +0900567 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400568
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900569 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900570 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900571 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900572
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700573 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800574 private static final int MIN_NET_ID = 100; // some reserved marks
575 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700576 private int mNextNetId = MIN_NET_ID;
577
Robert Greenwalt34524f02014-05-18 16:22:10 -0700578 // sequence number of NetworkRequests
579 private int mNextNetworkRequestId = 1;
580
Erik Kline7523eb32015-07-09 18:24:03 +0900581 // NetworkRequest activity String log entries.
582 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
583 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
584
Hugo Benichic2ae2872016-07-11 11:05:12 +0900585 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900586 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900587 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
588
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900589 private static final int MAX_WAKELOCK_LOGS = 20;
590 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900591 private int mTotalWakelockAcquisitions = 0;
592 private int mTotalWakelockReleases = 0;
593 private long mTotalWakelockDurationMs = 0;
594 private long mMaxWakelockDurationMs = 0;
595 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900596
Hugo Benichif9fdf872016-07-28 17:53:06 +0900597 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900598
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700599 @GuardedBy("mBandwidthRequests")
600 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
601
Erik Kline065ab6e2016-10-02 18:02:14 +0900602 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900603 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900604
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900605 @VisibleForTesting
606 final MultipathPolicyTracker mMultipathPolicyTracker;
607
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 /**
609 * Implements support for the legacy "one network per network type" model.
610 *
611 * We used to have a static array of NetworkStateTrackers, one for each
612 * network type, but that doesn't work any more now that we can have,
613 * for example, more that one wifi network. This class stores all the
614 * NetworkAgentInfo objects that support a given type, but the legacy
615 * API will only see the first one.
616 *
617 * It serves two main purposes:
618 *
619 * 1. Provide information about "the network for a given type" (since this
620 * API only supports one).
621 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
622 * the first network for a given type changes, or if the default network
623 * changes.
624 */
625 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900626
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900627 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900628 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900629
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 /**
631 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
632 * Each list holds references to all NetworkAgentInfos that are used to
633 * satisfy requests for that network type.
634 *
635 * This array is built out at startup such that an unsupported network
636 * doesn't get an ArrayList instance, making this a tristate:
637 * unsupported, supported but not active and active.
638 *
639 * The actual lists are populated when we scan the network types that
640 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900641 *
642 * Threading model:
643 * - addSupportedType() is only called in the constructor
644 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
645 * They are therefore not thread-safe with respect to each other.
646 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
647 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
648 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700649 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900650 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700651
652 public LegacyTypeTracker() {
653 mTypeLists = (ArrayList<NetworkAgentInfo>[])
654 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
655 }
656
657 public void addSupportedType(int type) {
658 if (mTypeLists[type] != null) {
659 throw new IllegalStateException(
660 "legacy list for type " + type + "already initialized");
661 }
Chalard Jean4133a122018-06-04 13:33:12 +0900662 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700663 }
664
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700665 public boolean isTypeSupported(int type) {
666 return isNetworkTypeValid(type) && mTypeLists[type] != null;
667 }
668
669 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900670 synchronized (mTypeLists) {
671 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
672 return mTypeLists[type].get(0);
673 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700674 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900675 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700676 }
677
Robert Greenwalt8d482522015-06-24 13:23:42 -0700678 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900679 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900680 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700681 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900682 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900683 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900684 }
685 }
686
687 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700688 public void add(int type, NetworkAgentInfo nai) {
689 if (!isTypeSupported(type)) {
690 return; // Invalid network type.
691 }
692 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
693
694 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
695 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700696 return;
697 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900698 synchronized (mTypeLists) {
699 list.add(nai);
700 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900701
702 // 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 +0900703 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900704 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700705 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
706 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700707 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700708 }
709
Lorenzo Colittia793a672014-07-31 23:20:17 +0900710 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900711 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900712 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
713 if (list == null || list.isEmpty()) {
714 return;
715 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900716 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900717
Hugo Benichi78caa2582016-06-21 09:48:07 +0900718 synchronized (mTypeLists) {
719 if (!list.remove(nai)) {
720 return;
721 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900722 }
723
Robert Greenwalt8d482522015-06-24 13:23:42 -0700724 final DetailedState state = DetailedState.DISCONNECTED;
725
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900726 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700727 maybeLogBroadcast(nai, state, type, wasDefault);
728 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900729 }
730
731 if (!list.isEmpty() && wasFirstNetwork) {
732 if (DBG) log("Other network available for type " + type +
733 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900734 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700735 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
736 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900737 }
738 }
739
740 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900741 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
742 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700743 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900744 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700745 }
746 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700747
Robert Greenwalt8d482522015-06-24 13:23:42 -0700748 // send out another legacy broadcast - currently only used for suspend/unsuspend
749 // toggle
750 public void update(NetworkAgentInfo nai) {
751 final boolean isDefault = isDefaultNetwork(nai);
752 final DetailedState state = nai.networkInfo.getDetailedState();
753 for (int type = 0; type < mTypeLists.length; type++) {
754 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700755 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900756 final boolean isFirst = contains && (nai == list.get(0));
757 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700758 maybeLogBroadcast(nai, state, type, isDefault);
759 sendLegacyNetworkBroadcast(nai, state, type);
760 }
761 }
762 }
763
Lorenzo Colittia793a672014-07-31 23:20:17 +0900764 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900765 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900766 String state = (nai.networkInfo != null) ?
767 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
768 "???/???";
769 return name + " " + state;
770 }
771
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700772 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900773 pw.println("mLegacyTypeTracker:");
774 pw.increaseIndent();
775 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700776 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900777 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700778 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900779 pw.println();
780 pw.println("Current state:");
781 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900782 synchronized (mTypeLists) {
783 for (int type = 0; type < mTypeLists.length; type++) {
784 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
785 for (NetworkAgentInfo nai : mTypeLists[type]) {
786 pw.println(type + " " + naiToString(nai));
787 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900788 }
789 }
790 pw.decreaseIndent();
791 pw.decreaseIndent();
792 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700793 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700794 }
795 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
796
Vishnu Nair5c010902017-10-26 10:08:50 -0700797 /**
798 * Helper class which parses out priority arguments and dumps sections according to their
799 * priority. If priority arguments are omitted, function calls the legacy dump command.
800 */
801 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
802 @Override
803 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
804 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
805 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
806 }
807
808 @Override
809 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
810 doDump(fd, pw, args, asProto);
811 }
812
813 @Override
814 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
815 doDump(fd, pw, args, asProto);
816 }
817 };
818
Jeff Sharkey899223b2012-08-04 15:24:58 -0700819 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700820 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Luke Huang65914772019-03-16 00:31:46 +0800821 this(context, netManager, statsService, policyManager,
822 getDnsResolver(), new IpConnectivityLog());
Hugo Benichif9fdf872016-07-28 17:53:06 +0900823 }
824
825 @VisibleForTesting
826 protected ConnectivityService(Context context, INetworkManagementService netManager,
827 INetworkStatsService statsService, INetworkPolicyManager policyManager,
Luke Huang65914772019-03-16 00:31:46 +0800828 IDnsResolver dnsresolver, IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800829 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800830
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900831 mSystemProperties = getSystemProperties();
832
Hugo Benichif9fdf872016-07-28 17:53:06 +0900833 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900834 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900835 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900836 mNetworkRequests.put(mDefaultRequest, defaultNRI);
837 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900838
Chalard Jeandda156a2018-01-10 21:19:32 +0900839 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900840 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700841
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700842 // The default WiFi request is a background request so that apps using WiFi are
843 // migrated to a better network (typically ethernet) when one comes up, instead
844 // of staying on WiFi forever.
845 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
846 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
847
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900848 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900849 mHandlerThread.start();
850 mHandler = new InternalHandler(mHandlerThread.getLooper());
851 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700852
Jeremy Joslin79294842014-12-03 17:15:28 -0800853 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
854 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
855
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900856 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900857
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700858 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800859 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800860 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700861 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900862 mPolicyManagerInternal = checkNotNull(
863 LocalServices.getService(NetworkPolicyManagerInternal.class),
864 "missing NetworkPolicyManagerInternal");
Luke Huang65914772019-03-16 00:31:46 +0800865 mDnsResolver = checkNotNull(dnsresolver, "missing IDnsResolver");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000866 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900867
Luke Huang674660f2018-09-27 19:33:11 +0800868 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700869 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700870 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700871
junyulai05986c62018-08-07 19:50:45 +0800872 // To ensure uid rules are synchronized with Network Policy, register for
873 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
874 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700875 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900876 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700877 } catch (RemoteException e) {
878 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700879 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700880 }
881
882 final PowerManager powerManager = (PowerManager) context.getSystemService(
883 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700884 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
885 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
886 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800887 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700888
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700889 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700890
Wink Saville51f456f2013-04-23 14:26:51 -0700891 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900892 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700893 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700894 String[] naStrings = context.getResources().getStringArray(
895 com.android.internal.R.array.networkAttributes);
896 for (String naString : naStrings) {
897 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700898 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700899 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700900 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800901 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700902 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700903 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700904 }
Wink Saville51f456f2013-04-23 14:26:51 -0700905 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
906 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
907 n.type);
908 continue;
909 }
Wink Saville975c8482011-04-07 14:23:45 -0700910 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800911 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700912 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700913 continue;
914 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700915 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700916
Wink Saville975c8482011-04-07 14:23:45 -0700917 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700918 mNetworksDefined++;
919 } catch(Exception e) {
920 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700921 }
922 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700923
924 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
925 if (mNetConfigs[TYPE_VPN] == null) {
926 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
927 // don't need to add TYPE_VPN to mNetConfigs.
928 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
929 mNetworksDefined++; // used only in the log() statement below.
930 }
931
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900932 // Do the same for Ethernet, since it's often not specified in the configs, although many
933 // devices can use it via USB host adapters.
934 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
935 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
936 mNetworksDefined++;
937 }
938
Wink Saville5e56bc52013-07-29 15:00:57 -0700939 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700940
Robert Greenwalt50393202011-06-21 17:26:14 -0700941 mProtectedNetworks = new ArrayList<Integer>();
942 int[] protectedNetworks = context.getResources().getIntArray(
943 com.android.internal.R.array.config_protectedNetworks);
944 for (int p : protectedNetworks) {
945 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
946 mProtectedNetworks.add(p);
947 } else {
948 if (DBG) loge("Ignoring protectedNetwork " + p);
949 }
950 }
951
Erik Kline47222fc2017-04-30 19:36:15 +0900952 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800953
Luke Huang4e25ec62018-09-27 16:58:23 +0800954 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700955
Varun Anand4fa80e82019-02-06 10:13:38 -0800956 // Set up the listener for user state for creating user VPNs.
957 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700958 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100959 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700960 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700961 intentFilter.addAction(Intent.ACTION_USER_ADDED);
962 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000963 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700964 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800965 mIntentReceiver,
966 UserHandle.ALL,
967 intentFilter,
968 null /* broadcastPermission */,
969 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000970 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
971 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900972
junyulai2454b692018-11-01 17:16:31 +0800973 // Listen to package add and removal events for all users.
974 intentFilter = new IntentFilter();
975 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800976 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800977 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
978 intentFilter.addDataScheme("package");
979 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800980 mIntentReceiver,
981 UserHandle.ALL,
982 intentFilter,
983 null /* broadcastPermission */,
984 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800985
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700986 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800987 mNMS.registerObserver(mTethering);
988 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700989 } catch (RemoteException e) {
990 loge("Error registering observer :" + e);
991 }
992
Erik Klineda4bfa82015-04-30 12:58:40 +0900993 mSettingsObserver = new SettingsObserver(mContext, mHandler);
994 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800995
Chalard Jean4133a122018-06-04 13:33:12 +0900996 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
997 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400998
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400999 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001000
junyulai0c666972019-03-04 22:45:36 +08001001 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +09001002 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
1003 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +09001004
1005 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1006 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1007 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1008 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1009 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1010 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1011 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09001012
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001013 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +09001014 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001015 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +09001016
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001017 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1018
Luke Huang65914772019-03-16 00:31:46 +08001019 mDnsManager = new DnsManager(mContext, mDnsResolver, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001020 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001022
Mike Yuf9729752018-08-17 15:22:05 +08001023 @VisibleForTesting
1024 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001025 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001026 final TetheringDependencies deps = new TetheringDependencies() {
1027 @Override
1028 public boolean isTetheringSupported() {
1029 return ConnectivityService.this.isTetheringSupported();
1030 }
Erik Kline72302902018-06-14 17:36:40 +09001031 @Override
1032 public NetworkRequest getDefaultNetworkRequest() {
1033 return mDefaultRequest;
1034 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001035 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001036 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001037 IoThread.get().getLooper(), new MockableSystemProperties(),
1038 deps);
1039 }
1040
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001041 @VisibleForTesting
1042 protected ProxyTracker makeProxyTracker() {
1043 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1044 }
1045
Chalard Jean26400492018-04-18 20:18:38 +09001046 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1047 final NetworkCapabilities netCap = new NetworkCapabilities();
1048 netCap.addCapability(NET_CAPABILITY_INTERNET);
1049 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1050 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1051 netCap.setSingleUid(uid);
1052 return netCap;
1053 }
1054
Chalard Jeandda156a2018-01-10 21:19:32 +09001055 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001056 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001057 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001058 netCap.addCapability(NET_CAPABILITY_INTERNET);
1059 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001060 if (transportType > -1) {
1061 netCap.addTransportType(transportType);
1062 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001063 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001064 }
1065
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001066 // Used only for testing.
1067 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001068 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001069 // changing ContentResolver to make registerContentObserver non-final).
1070 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1071 // by subclassing SettingsObserver.
1072 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001073 void updateAlwaysOnNetworks() {
1074 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001075 }
1076
Erik Kline736353a2018-03-21 07:18:33 -07001077 // See FakeSettingsProvider comment above.
1078 @VisibleForTesting
1079 void updatePrivateDnsSettings() {
1080 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1081 }
1082
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001083 private void handleAlwaysOnNetworkRequest(
1084 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001085 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001086 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1087 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001088 if (enable == isEnabled) {
1089 return; // Nothing to do.
1090 }
1091
1092 if (enable) {
1093 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001094 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001095 } else {
Etan Cohenddb720a2019-01-08 12:09:18 -08001096 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1097 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001098 }
1099 }
1100
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001101 private void handleConfigureAlwaysOnNetworks() {
1102 handleAlwaysOnNetworkRequest(
1103 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1104 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1105 false);
1106 }
1107
Erik Klineda4bfa82015-04-30 12:58:40 +09001108 private void registerSettingsCallbacks() {
1109 // Watch for global HTTP proxy changes.
1110 mSettingsObserver.observe(
1111 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1112 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1113
1114 // Watch for whether or not to keep mobile data always on.
1115 mSettingsObserver.observe(
1116 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001117 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1118
1119 // Watch for whether or not to keep wifi always on.
1120 mSettingsObserver.observe(
1121 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1122 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001123 }
1124
Erik Klinea24d4592018-01-11 21:07:29 +09001125 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001126 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1127 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001128 }
1129 }
1130
Robert Greenwalt34524f02014-05-18 16:22:10 -07001131 private synchronized int nextNetworkRequestId() {
1132 return mNextNetworkRequestId++;
1133 }
1134
Paul Jensen67b0b072015-06-10 11:22:17 -04001135 @VisibleForTesting
1136 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001137 synchronized (mNetworkForNetId) {
1138 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1139 int netId = mNextNetId;
1140 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1141 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001142 if (!mNetIdInUse.get(netId)) {
1143 mNetIdInUse.put(netId, true);
1144 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001145 }
1146 }
1147 }
1148 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001149 }
1150
Chalard Jeanc0982912018-06-07 16:11:34 +09001151 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001153 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1154 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001156 state = nai.getNetworkState();
1157 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001159 final NetworkInfo info = new NetworkInfo(networkType, 0,
1160 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1162 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001163 final NetworkCapabilities capabilities = new NetworkCapabilities();
1164 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1165 !info.isRoaming());
1166 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001169 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 return state;
1171 } else {
1172 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001173 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001174 }
1175
junyulai4a192e22018-06-13 15:00:37 +08001176 @VisibleForTesting
1177 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 if (network == null) {
1179 return null;
1180 }
Erik Kline736353a2018-03-21 07:18:33 -07001181 return getNetworkAgentInfoForNetId(network.netId);
1182 }
1183
1184 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001186 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001188 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001189
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001190 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001191 synchronized (mVpns) {
1192 if (!mLockdownEnabled) {
1193 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001194 Vpn vpn = mVpns.get(user);
1195 if (vpn != null && vpn.appliesToUid(uid)) {
1196 return vpn.getUnderlyingNetworks();
1197 }
1198 }
1199 }
1200 return null;
1201 }
1202
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001204 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001205
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001206 final Network[] networks = getVpnUnderlyingNetworks(uid);
1207 if (networks != null) {
1208 // getUnderlyingNetworks() returns:
1209 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1210 // empty array => the VPN explicitly said "no default network".
1211 // non-empty array => the VPN specified one or more default networks; we use the
1212 // first one.
1213 if (networks.length > 0) {
1214 nai = getNetworkAgentInfoForNetwork(networks[0]);
1215 } else {
1216 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001217 }
1218 }
1219
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001221 return nai.getNetworkState();
1222 } else {
1223 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001224 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001225 }
1226
1227 /**
1228 * Check if UID should be blocked from using the network with the given LinkProperties.
1229 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001230 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1231 boolean ignoreBlocked) {
1232 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001233 if (ignoreBlocked) {
1234 return false;
1235 }
Robin Lee17e61832016-05-09 13:46:28 +01001236 synchronized (mVpns) {
1237 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001238 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001239 return true;
1240 }
1241 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001242 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001243 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 }
1245
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001246 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001247 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1248 return;
1249 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001250 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001251 synchronized (mBlockedAppUids) {
1252 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001253 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001254 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001255 blocked = false;
1256 } else {
1257 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001258 }
1259 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001260 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1261 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1262 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001263 }
1264
junyulai05986c62018-08-07 19:50:45 +08001265 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1266 boolean blocked) {
1267 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1268 return;
1269 }
1270 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1271 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1272 nri.mUid, nri.request.requestId, net.netId));
1273 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1274 }
1275
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001276 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001277 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1278 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001279 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001280 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001281 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001282 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1283
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001284 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001285 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001286 }
Hugo Benichi69744342017-11-27 10:57:16 +09001287 synchronized (mVpns) {
1288 if (mLockdownTracker != null) {
1289 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1290 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001291 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001292 }
1293
1294 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 * Return NetworkInfo for the active (i.e., connected) network interface.
1296 * It is assumed that at most one network is active at a time. If more
1297 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001298 * @return the info for the active network, or {@code null} if none is
1299 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001301 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001303 enforceAccessPermission();
1304 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001305 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001306 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001307 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1308 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 }
1310
Paul Jensen31a94f42015-02-13 14:18:39 -05001311 @Override
1312 public Network getActiveNetwork() {
1313 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001314 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001315 }
1316
1317 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001318 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001319 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001320 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001321 }
1322
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001323 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001324 final int user = UserHandle.getUserId(uid);
1325 int vpnNetId = NETID_UNSET;
1326 synchronized (mVpns) {
1327 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001328 // TODO : now that capabilities contain the UID, the appliesToUid test should
1329 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001330 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1331 }
1332 NetworkAgentInfo nai;
1333 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001334 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001335 if (nai != null) {
1336 final NetworkCapabilities requiredCaps =
1337 createDefaultNetworkCapabilitiesForUid(uid);
1338 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1339 return nai.network;
1340 }
1341 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001342 }
1343 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001344 if (nai != null
1345 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1346 nai = null;
1347 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001348 return nai != null ? nai.network : null;
1349 }
1350
Lorenzo Colitti18660282016-07-04 12:55:44 +09001351 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001352 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1353 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001354 final int uid = Binder.getCallingUid();
1355 NetworkState state = getUnfilteredActiveNetworkState(uid);
1356 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001357 }
1358
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001359 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001360 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001361 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001362 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001363 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001364 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001365 }
1366
1367 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 public NetworkInfo getNetworkInfo(int networkType) {
1369 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001370 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001371 if (getVpnUnderlyingNetworks(uid) != null) {
1372 // A VPN is active, so we may need to return one of its underlying networks. This
1373 // information is not available in LegacyTypeTracker, so we have to get it from
1374 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001375 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001376 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001377 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001378 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001379 }
1380 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001381 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001382 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001385 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001386 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001387 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001388 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001389 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001390 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001391 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001392 return state.networkInfo;
1393 } else {
1394 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001395 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001396 }
1397
1398 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 public NetworkInfo[] getAllNetworkInfo() {
1400 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001401 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001402 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1403 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001404 NetworkInfo info = getNetworkInfo(networkType);
1405 if (info != null) {
1406 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001409 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 }
1411
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001412 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001413 public Network getNetworkForType(int networkType) {
1414 enforceAccessPermission();
1415 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001416 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001417 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001418 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001419 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001420 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001421 }
1422
1423 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001424 public Network[] getAllNetworks() {
1425 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001426 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001427 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001428 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001429 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001430 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001431 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001432 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001433 }
1434
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001435 @Override
1436 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1437 // The basic principle is: if an app's traffic could possibly go over a
1438 // network, without the app doing anything multinetwork-specific,
1439 // (hence, by "default"), then include that network's capabilities in
1440 // the array.
1441 //
1442 // In the normal case, app traffic only goes over the system's default
1443 // network connection, so that's the only network returned.
1444 //
1445 // With a VPN in force, some app traffic may go into the VPN, and thus
1446 // over whatever underlying networks the VPN specifies, while other app
1447 // traffic may go over the system default network (e.g.: a split-tunnel
1448 // VPN, or an app disallowed by the VPN), so the set of networks
1449 // returned includes the VPN's underlying networks and the system
1450 // default.
1451 enforceAccessPermission();
1452
Chalard Jean4133a122018-06-04 13:33:12 +09001453 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001454
1455 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001456 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001457 if (nc != null) {
1458 result.put(nai.network, nc);
1459 }
1460
Hugo Benichi69744342017-11-27 10:57:16 +09001461 synchronized (mVpns) {
1462 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001463 Vpn vpn = mVpns.get(userId);
1464 if (vpn != null) {
1465 Network[] networks = vpn.getUnderlyingNetworks();
1466 if (networks != null) {
1467 for (Network network : networks) {
1468 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001469 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001470 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001471 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001472 }
1473 }
1474 }
1475 }
1476 }
1477 }
1478
1479 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1480 out = result.values().toArray(out);
1481 return out;
1482 }
1483
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001484 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001485 public boolean isNetworkSupported(int networkType) {
1486 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001487 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001488 }
1489
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001490 /**
1491 * Return LinkProperties for the active (i.e., connected) default
1492 * network interface. It is assumed that at most one default network
1493 * is active at a time. If more than one is active, it is indeterminate
1494 * which will be returned.
1495 * @return the ip properties for the active network, or {@code null} if
1496 * none is active
1497 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001498 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001499 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001500 enforceAccessPermission();
1501 final int uid = Binder.getCallingUid();
1502 NetworkState state = getUnfilteredActiveNetworkState(uid);
1503 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001504 }
1505
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001506 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001507 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001508 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001509 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1510 if (nai != null) {
1511 synchronized (nai) {
1512 return new LinkProperties(nai.linkProperties);
1513 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001514 }
1515 return null;
1516 }
1517
Robert Greenwalt12e67352014-05-13 21:41:06 -07001518 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001519 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001520 public LinkProperties getLinkProperties(Network network) {
1521 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001522 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1523 }
1524
1525 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1526 if (nai == null) {
1527 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001528 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001529 synchronized (nai) {
1530 return new LinkProperties(nai.linkProperties);
1531 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001532 }
1533
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001534 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001535 if (nai != null) {
1536 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001537 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001538 return networkCapabilitiesRestrictedForCallerPermissions(
1539 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001540 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001541 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001542 }
1543 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001544 return null;
1545 }
1546
1547 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001548 public NetworkCapabilities getNetworkCapabilities(Network network) {
1549 enforceAccessPermission();
1550 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1551 }
1552
Chalard Jeanb03a6222018-04-11 21:09:10 +09001553 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001554 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001555 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001556 if (!checkSettingsPermission(callerPid, callerUid)) {
1557 newNc.setUids(null);
1558 newNc.setSSID(null);
1559 }
Etan Cohen836ad572018-12-30 17:59:59 -08001560 if (newNc.getNetworkSpecifier() != null) {
1561 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1562 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001563 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001564 }
1565
Chalard Jeanb552c462018-02-21 18:43:54 +09001566 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1567 if (!checkSettingsPermission()) {
1568 nc.setSingleUid(Binder.getCallingUid());
1569 }
1570 }
1571
Chalard Jean26aa91a2018-03-20 19:13:57 +09001572 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1573 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1574 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1575 }
1576 }
1577
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001578 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001579 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001580 // Require internal since we're handing out IMSI details
1581 enforceConnectivityInternalPermission();
1582
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001583 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001584 for (Network network : getAllNetworks()) {
1585 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1586 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001587 // TODO (b/73321673) : NetworkState contains a copy of the
1588 // NetworkCapabilities, which may contain UIDs of apps to which the
1589 // network applies. Should the UIDs be cleared so as not to leak or
1590 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001591 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001592 }
1593 }
1594 return result.toArray(new NetworkState[result.size()]);
1595 }
1596
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001597 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001598 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001599 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001600 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1601 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1602 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001603 }
1604
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001605 @Override
1606 public boolean isActiveNetworkMetered() {
1607 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001608
Varun Anandc51b06d2019-02-25 17:22:02 -08001609 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001610 if (caps != null) {
1611 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1612 } else {
1613 // Always return the most conservative value
1614 return true;
1615 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001616 }
1617
Jeff Sharkey216c1812012-08-05 14:29:23 -07001618 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1619 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001620 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001621 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001622 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001623 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001624 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001625
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001626 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001627 * Ensures that the system cannot call a particular method.
1628 */
1629 private boolean disallowedBecauseSystemCaller() {
1630 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1631 // requestRouteToHost.
1632 if (isSystem(Binder.getCallingUid())) {
1633 log("This method exists only for app backwards compatibility"
1634 + " and must not be called by system services.");
1635 return true;
1636 }
1637 return false;
1638 }
1639
1640 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 * Ensure that a network route exists to deliver traffic to the specified
1642 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001643 * @param networkType the type of the network over which traffic to the
1644 * specified host is to be routed
1645 * @param hostAddress the IP address of the host to which the route is
1646 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 * @return {@code true} on success, {@code false} on failure
1648 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001649 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001650 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001651 if (disallowedBecauseSystemCaller()) {
1652 return false;
1653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001655 if (mProtectedNetworks.contains(networkType)) {
1656 enforceConnectivityInternalPermission();
1657 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001658
Chad Brubakerc0234532014-02-14 13:24:29 -08001659 InetAddress addr;
1660 try {
1661 addr = InetAddress.getByAddress(hostAddress);
1662 } catch (UnknownHostException e) {
1663 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1664 return false;
1665 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001668 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 return false;
1670 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001671
1672 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1673 if (nai == null) {
1674 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1675 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1676 } else {
1677 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1678 }
1679 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001680 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001681
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001682 DetailedState netState;
1683 synchronized (nai) {
1684 netState = nai.networkInfo.getDetailedState();
1685 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001686
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001687 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001688 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001689 log("requestRouteToHostAddress on down network "
1690 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001691 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001692 }
1693 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001695
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001696 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001697 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001698 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001699 LinkProperties lp;
1700 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001701 synchronized (nai) {
1702 lp = nai.linkProperties;
1703 netId = nai.network.netId;
1704 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001705 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001706 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1707 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001708 } finally {
1709 Binder.restoreCallingIdentity(token);
1710 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001711 }
1712
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001713 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001714 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001715 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001716 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001717 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001718 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001719 if (bestRoute.getGateway().equals(addr)) {
1720 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001721 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001722 } else {
1723 // if we will connect to this through another route, add a direct route
1724 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001725 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001726 }
1727 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001728 if (DBG) log("Adding legacy route " + bestRoute +
1729 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001730 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001731 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001732 } catch (Exception e) {
1733 // never crash - catch them all
1734 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001735 return false;
1736 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001737 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739
dalyk7301aa42018-03-05 12:42:22 -05001740 @VisibleForTesting
1741 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1742 @Override
1743 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1744 String hostname, boolean validated) {
1745 try {
1746 mHandler.sendMessage(mHandler.obtainMessage(
1747 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1748 new PrivateDnsValidationUpdate(netId,
1749 InetAddress.parseNumericAddress(ipAddress),
1750 hostname, validated)));
1751 } catch (IllegalArgumentException e) {
1752 loge("Error parsing ip address in validation event");
1753 }
1754 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001755
1756 @Override
1757 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1758 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1759 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1760 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1761 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1762 // event callback for certain nai. e.g. cellular. Register here to pass to
1763 // NetworkMonitor instead.
1764 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1765 // registerNetworkAgent to have NetworkMonitor created with system process as design
1766 // expectation. Also, NetdEventListenerService only allow one callback from each
1767 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1768 // NetworkMonitor registrants.
1769 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001770 try {
1771 nai.networkMonitor().notifyDnsResponse(returnCode);
1772 } catch (RemoteException e) {
1773 e.rethrowFromSystemServer();
1774 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001775 }
1776 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001777
1778 @Override
1779 public void onNat64PrefixEvent(int netId, boolean added,
1780 String prefixString, int prefixLength) {
1781 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1782 }
dalyk7301aa42018-03-05 12:42:22 -05001783 };
1784
1785 @VisibleForTesting
1786 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001787 final IIpConnectivityMetrics ipConnectivityMetrics =
1788 IIpConnectivityMetrics.Stub.asInterface(
1789 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1790 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001791 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001792 return;
dalyk7301aa42018-03-05 12:42:22 -05001793 }
1794
1795 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001796 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001797 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1798 mNetdEventCallback);
1799 } catch (Exception e) {
1800 loge("Error registering netd callback: " + e);
1801 }
1802 }
1803
Jeff Sharkey75d31892018-01-18 22:01:59 +09001804 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001805 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001806 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001807 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001808 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001809 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001810 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001811 // caller is NPMS, since we only register with them
1812 if (LOGD_BLOCKED_NETWORKINFO) {
1813 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1814 }
1815 mHandler.sendMessage(mHandler.obtainMessage(
1816 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1817
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001818 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001819 if (restrictBackground) {
1820 log("onRestrictBackgroundChanged(true): disabling tethering");
1821 mTethering.untetherAll();
1822 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001823 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001824 };
1825
junyulai05986c62018-08-07 19:50:45 +08001826 void handleUidRulesChanged(int uid, int newRules) {
1827 // skip update when we've already applied rules
1828 final int oldRules = mUidRules.get(uid, RULE_NONE);
1829 if (oldRules == newRules) return;
1830
1831 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1832
1833 if (newRules == RULE_NONE) {
1834 mUidRules.delete(uid);
1835 } else {
1836 mUidRules.put(uid, newRules);
1837 }
1838 }
1839
1840 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1841 if (mRestrictBackground == restrictBackground) return;
1842
1843 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1844 final boolean curMetered = nai.networkCapabilities.isMetered();
1845 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1846 restrictBackground);
1847 }
1848
1849 mRestrictBackground = restrictBackground;
1850 }
1851
1852 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1853 boolean isBackgroundRestricted) {
1854 synchronized (mVpns) {
1855 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1856 // Because the return value of this function depends on the list of UIDs the
1857 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1858 // list all state depending on the return value of this function has to be recomputed.
1859 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1860 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001861 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001862 return true;
1863 }
1864 }
1865
1866 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1867 isNetworkMetered, isBackgroundRestricted);
1868 }
1869
Robin Lee3b3dd942015-05-12 18:14:58 +01001870 /**
1871 * Require that the caller is either in the same user or has appropriate permission to interact
1872 * across users.
1873 *
1874 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1875 */
1876 private void enforceCrossUserPermission(int userId) {
1877 if (userId == UserHandle.getCallingUserId()) {
1878 // Not a cross-user call.
1879 return;
1880 }
1881 mContext.enforceCallingOrSelfPermission(
1882 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1883 "ConnectivityService");
1884 }
1885
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001886 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001887 for (String permission : permissions) {
1888 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001889 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001890 }
1891 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001892 return false;
1893 }
1894
1895 private void enforceAnyPermissionOf(String... permissions) {
1896 if (!checkAnyPermissionOf(permissions)) {
1897 throw new SecurityException("Requires one of the following permissions: "
1898 + String.join(", ", permissions) + ".");
1899 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001900 }
1901
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001902 private void enforceInternetPermission() {
1903 mContext.enforceCallingOrSelfPermission(
1904 android.Manifest.permission.INTERNET,
1905 "ConnectivityService");
1906 }
1907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001909 mContext.enforceCallingOrSelfPermission(
1910 android.Manifest.permission.ACCESS_NETWORK_STATE,
1911 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 }
1913
1914 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001915 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
1917
Charles He36738632017-05-15 17:07:18 +01001918 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001919 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001920 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001921 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001922 }
1923
Chalard Jeanb552c462018-02-21 18:43:54 +09001924 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001925 return checkAnyPermissionOf(
1926 android.Manifest.permission.NETWORK_SETTINGS,
1927 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001928 }
1929
1930 private boolean checkSettingsPermission(int pid, int uid) {
1931 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001932 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1933 || PERMISSION_GRANTED == mContext.checkPermission(
1934 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001935 }
1936
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001937 private void enforceTetherAccessPermission() {
1938 mContext.enforceCallingOrSelfPermission(
1939 android.Manifest.permission.ACCESS_NETWORK_STATE,
1940 "ConnectivityService");
1941 }
1942
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001943 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001944 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001945 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001946 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001947 }
1948
Pavel Grafova462bcb2019-01-25 08:50:06 +00001949 private void enforceControlAlwaysOnVpnPermission() {
1950 mContext.enforceCallingOrSelfPermission(
1951 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1952 "ConnectivityService");
1953 }
1954
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001955 private void enforceNetworkStackSettingsOrSetup() {
1956 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001957 android.Manifest.permission.NETWORK_SETTINGS,
1958 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001959 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001960 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001961 }
1962
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001963 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001964 return checkAnyPermissionOf(
1965 android.Manifest.permission.NETWORK_STACK,
1966 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001967 }
1968
Hugo Benichi514da602016-07-19 15:59:27 +09001969 private void enforceConnectivityRestrictedNetworksPermission() {
1970 try {
1971 mContext.enforceCallingOrSelfPermission(
1972 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1973 "ConnectivityService");
1974 return;
1975 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1976 enforceConnectivityInternalPermission();
1977 }
1978
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001979 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001980 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001981 }
1982
Lorenzo Colitti18660282016-07-04 12:55:44 +09001983 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001984 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001985 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001986 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001987 }
1988
1989 private void sendInetConditionBroadcast(NetworkInfo info) {
1990 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1991 }
1992
Wink Saville628b0852011-08-04 15:01:58 -07001993 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001994 synchronized (mVpns) {
1995 if (mLockdownTracker != null) {
1996 info = new NetworkInfo(info);
1997 mLockdownTracker.augmentNetworkInfo(info);
1998 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001999 }
2000
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002001 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002002 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002003 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 if (info.isFailover()) {
2005 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2006 info.setFailover(false);
2007 }
2008 if (info.getReason() != null) {
2009 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2010 }
2011 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002012 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2013 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002015 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002016 return intent;
2017 }
2018
2019 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2020 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2021 }
2022
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002023 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002024 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2025 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2026 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002027 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002028 final long ident = Binder.clearCallingIdentity();
2029 try {
2030 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2031 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2032 } finally {
2033 Binder.restoreCallingIdentity(ident);
2034 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002035 }
2036
Mike Lockwood0f79b542009-08-14 14:18:49 -04002037 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002038 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002039 if (!mSystemReady
2040 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002041 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002042 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002043 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002044 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002045 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002046 }
2047
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002048 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002049 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002050 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002051 final NetworkInfo ni = intent.getParcelableExtra(
2052 ConnectivityManager.EXTRA_NETWORK_INFO);
2053 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2054 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2055 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002056 } else {
2057 BroadcastOptions opts = BroadcastOptions.makeBasic();
2058 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2059 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002060 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002061 final IBatteryStats bs = BatteryStatsService.getService();
2062 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002063 bs.noteConnectivityChanged(intent.getIntExtra(
2064 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002065 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002066 } catch (RemoteException e) {
2067 }
Chad Brubakerac925012018-03-08 10:37:09 -08002068 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002069 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002070 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002071 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002072 } finally {
2073 Binder.restoreCallingIdentity(ident);
2074 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002075 }
2076 }
2077
2078 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002079 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002080 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002081 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002082
Hugo Benichi20035e02017-04-26 14:53:28 +09002083 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002084 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002085 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002086 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002087 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002088 }
2089 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002090
Robin Lee244ce8e2016-01-05 18:03:46 +00002091 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2092 // for user to unlock device too.
2093 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002094
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002095 // Create network requests for always-on networks.
2096 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002097
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002098 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002099
2100 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
2102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002104 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002105 *
2106 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002107 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002108 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002109 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2110 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002111
2112 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002114
Robert Greenwalt7b816022014-04-18 15:25:25 -07002115 if (networkAgent.networkCapabilities.hasTransport(
2116 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002117 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2118 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002119 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002120 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 } else if (networkAgent.networkCapabilities.hasTransport(
2122 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002123 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2124 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002125 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002126 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002127 } else {
2128 // do not track any other networks
2129 timeout = 0;
2130 }
2131
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002133 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002134 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002135 } catch (Exception e) {
2136 // You shall not crash!
2137 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002138 }
2139 }
2140 }
2141
2142 /**
2143 * Remove data activity tracking when network disconnects.
2144 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002145 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2146 final String iface = networkAgent.linkProperties.getInterfaceName();
2147 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002148
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2150 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002151 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002152 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002153 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002154 } catch (Exception e) {
2155 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002156 }
2157 }
2158 }
2159
2160 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002161 * Update data activity tracking when network state is updated.
2162 */
2163 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2164 NetworkAgentInfo oldNetwork) {
2165 if (newNetwork != null) {
2166 setupDataActivityTracking(newNetwork);
2167 }
2168 if (oldNetwork != null) {
2169 removeDataActivityTracking(oldNetwork);
2170 }
2171 }
2172 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002173 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002174 * and set it on it's iface.
2175 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002176 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2177 final String iface = newLp.getInterfaceName();
2178 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002179 if (oldLp == null && mtu == 0) {
2180 // Silently ignore unset MTU value.
2181 return;
2182 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002183 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2184 if (VDBG) log("identical MTU - not setting");
2185 return;
2186 }
paulhud9736de2019-03-08 16:35:20 +08002187 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002188 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002189 return;
2190 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002191
w1997615afd812014-08-05 15:18:11 -07002192 // Cannot set MTU without interface name
2193 if (TextUtils.isEmpty(iface)) {
2194 loge("Setting MTU size with null iface.");
2195 return;
2196 }
2197
Robert Greenwalt7b816022014-04-18 15:25:25 -07002198 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002199 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002200 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002201 } catch (Exception e) {
2202 Slog.e(TAG, "exception in setMtu()" + e);
2203 }
2204 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002205
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002206 @VisibleForTesting
2207 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002208 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2209
2210 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002211 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002212 protected MockableSystemProperties getSystemProperties() {
2213 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002214 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002215
lucaslin041a1af2018-11-28 19:27:52 +08002216 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002217 String[] values = null;
2218 if (tcpBufferSizes != null) {
2219 values = tcpBufferSizes.split(",");
2220 }
2221
2222 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002223 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002224 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2225 values = tcpBufferSizes.split(",");
2226 }
2227
2228 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2229
2230 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002231 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002232
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002233 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2234 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2235 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002236 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002237 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002238 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002239 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002240
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002241 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002242 Settings.Global.TCP_DEFAULT_INIT_RWND,
2243 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002244 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2245 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002246 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002247 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002248 }
2249
Robert Greenwalt562cc542014-05-15 18:07:26 -07002250 @Override
2251 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002252 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002253 NETWORK_RESTORE_DELAY_PROP_NAME);
2254 if(restoreDefaultNetworkDelayStr != null &&
2255 restoreDefaultNetworkDelayStr.length() != 0) {
2256 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002257 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002258 } catch (NumberFormatException e) {
2259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002261 // if the system property isn't set, use the value for the apn type
2262 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2263
2264 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2265 (mNetConfigs[networkType] != null)) {
2266 ret = mNetConfigs[networkType].restoreTime;
2267 }
2268 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002271 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2272 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2273 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002274 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002275 // Start gathering diagnostic information.
2276 netDiags.add(new NetworkDiagnostics(
2277 nai.network,
2278 new LinkProperties(nai.linkProperties), // Must be a copy.
2279 DIAG_TIME_MS));
2280 }
2281
2282 for (NetworkDiagnostics netDiag : netDiags) {
2283 pw.println();
2284 netDiag.waitForMeasurements();
2285 netDiag.dump(pw);
2286 }
2287 }
2288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002290 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002291 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2292 }
2293
2294 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002295 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002296 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002297 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002298
Erik Kline3f8306b2018-05-01 16:51:44 +09002299 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002300 dumpNetworkDiagnostics(pw);
2301 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002302 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002303 mTethering.dump(fd, pw, args);
2304 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002305 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2306 dumpNetworks(pw);
2307 return;
2308 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2309 dumpNetworkRequests(pw);
2310 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002311 }
Erik Kline379747a2015-06-05 17:47:34 +09002312
Lorenzo Colittie3805462015-06-03 11:18:24 +09002313 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002314 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002315 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002316 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002317 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002318 pw.println();
2319
Paul Jensen85cf78e2015-06-25 13:25:07 -04002320 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002321 pw.print("Active default network: ");
2322 if (defaultNai == null) {
2323 pw.println("none");
2324 } else {
2325 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002327 pw.println();
2328
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002329 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002330 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002331 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002332 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002333 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002334
junyulai05986c62018-08-07 19:50:45 +08002335 pw.print("Restrict background: ");
2336 pw.println(mRestrictBackground);
2337 pw.println();
2338
2339 pw.println("Status for known UIDs:");
2340 pw.increaseIndent();
2341 final int size = mUidRules.size();
2342 for (int i = 0; i < size; i++) {
2343 // Don't crash if the array is modified while dumping in bugreports.
2344 try {
2345 final int uid = mUidRules.keyAt(i);
2346 final int uidRules = mUidRules.get(uid, RULE_NONE);
2347 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2348 } catch (ArrayIndexOutOfBoundsException e) {
2349 pw.println(" ArrayIndexOutOfBoundsException");
2350 } catch (ConcurrentModificationException e) {
2351 pw.println(" ConcurrentModificationException");
2352 }
2353 }
2354 pw.println();
2355 pw.decreaseIndent();
2356
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002357 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002358 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002359 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002360 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002361 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002362
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002363 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002364
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002365 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002366 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002367
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002368 pw.println();
2369 mKeepaliveTracker.dump(pw);
2370
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002371 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002372 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002373
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002374 pw.println();
2375 mMultipathPolicyTracker.dump(pw);
2376
Erik Kline3f8306b2018-05-01 16:51:44 +09002377 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002378 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002379 pw.println("mNetworkRequestInfoLogs (most recent first):");
2380 pw.increaseIndent();
2381 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2382 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002383
2384 pw.println();
2385 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2386 pw.increaseIndent();
2387 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2388 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002389
2390 pw.println();
2391 pw.println("NetTransition WakeLock activity (most recent first):");
2392 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002393 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2394 pw.println("total releases: " + mTotalWakelockReleases);
2395 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2396 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2397 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2398 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2399 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2400 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002401 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002402
2403 pw.println();
2404 pw.println("bandwidth update requests (by uid):");
2405 pw.increaseIndent();
2406 synchronized (mBandwidthRequests) {
2407 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2408 pw.println("[" + mBandwidthRequests.keyAt(i)
2409 + "]: " + mBandwidthRequests.valueAt(i));
2410 }
2411 }
2412 pw.decreaseIndent();
2413
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002414 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002415 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002416
2417 pw.println();
2418 pw.println("NetworkStackClient logs:");
2419 pw.increaseIndent();
2420 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 }
2422
Hugo Benichi14683812018-09-03 08:32:56 +09002423 private void dumpNetworks(IndentingPrintWriter pw) {
2424 for (NetworkAgentInfo nai : networksSortedById()) {
2425 pw.println(nai.toString());
2426 pw.increaseIndent();
2427 pw.println(String.format(
2428 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2429 nai.numForegroundNetworkRequests(),
2430 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2431 nai.numBackgroundNetworkRequests(),
2432 nai.numNetworkRequests()));
2433 pw.increaseIndent();
2434 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2435 pw.println(nai.requestAt(i).toString());
2436 }
2437 pw.decreaseIndent();
2438 pw.println("Lingered:");
2439 pw.increaseIndent();
2440 nai.dumpLingerTimers(pw);
2441 pw.decreaseIndent();
2442 pw.decreaseIndent();
2443 }
2444 }
2445
2446 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2447 for (NetworkRequestInfo nri : requestsSortedById()) {
2448 pw.println(nri.toString());
2449 }
2450 }
2451
Hugo Benichia2a917c2018-09-03 08:19:02 +09002452 /**
2453 * Return an array of all current NetworkAgentInfos sorted by network id.
2454 */
2455 private NetworkAgentInfo[] networksSortedById() {
2456 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2457 networks = mNetworkAgentInfos.values().toArray(networks);
2458 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2459 return networks;
2460 }
2461
2462 /**
2463 * Return an array of all current NetworkRequest sorted by request id.
2464 */
2465 private NetworkRequestInfo[] requestsSortedById() {
2466 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2467 requests = mNetworkRequests.values().toArray(requests);
2468 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2469 return requests;
2470 }
2471
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002472 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002473 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002474 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002475 if (officialNai != null && officialNai.equals(nai)) return true;
2476 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002477 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002478 " - " + nai);
2479 }
2480 return false;
2481 }
2482
Robert Greenwalt42acef32009-08-12 16:08:25 -07002483 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002484 private class NetworkStateTrackerHandler extends Handler {
2485 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002486 super(looper);
2487 }
2488
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002489 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002491 default:
2492 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002493 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002494 handleAsyncChannelHalfConnect(msg);
2495 break;
2496 }
2497 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2498 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2499 if (nai != null) nai.asyncChannel.disconnect();
2500 break;
2501 }
2502 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2503 handleAsyncChannelDisconnected(msg);
2504 break;
2505 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002506 }
2507 return true;
2508 }
2509
2510 private void maybeHandleNetworkAgentMessage(Message msg) {
2511 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2512 if (nai == null) {
2513 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002514 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002515 }
2516 return;
2517 }
2518
2519 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002520 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002521 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002522 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002523 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002524 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002525 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002526 break;
2527 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002528 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002529 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002530 break;
2531 }
2532 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002533 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002534 updateNetworkInfo(nai, info);
2535 break;
2536 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002537 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002538 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002539 break;
2540 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002541 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002542 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2543 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002544 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002545 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002546 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002547 // Mark the network as temporarily accepting partial connectivity so that it
2548 // will be validated (and possibly become default) even if it only provides
2549 // partial internet access. Note that if user connects to partial connectivity
2550 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2551 // out of wifi coverage) and if the same wifi is available again, the device
2552 // will auto connect to this wifi even though the wifi has "no internet".
2553 // TODO: Evaluate using a separate setting in IpMemoryStore.
2554 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002555 break;
2556 }
junyulai06835112019-01-03 18:50:15 +08002557 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2558 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002559 break;
2560 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002561 }
2562 }
2563
2564 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2565 switch (msg.what) {
2566 default:
2567 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002568 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002569 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002570 if (nai == null) break;
2571
lucasline252a742019-03-12 13:08:03 +08002572 final boolean partialConnectivity =
2573 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
lucasline252a742019-03-12 13:08:03 +08002574 || (nai.networkMisc.acceptPartialConnectivity
2575 && nai.partialConnectivity);
2576 // Once a network is determined to have partial connectivity, it cannot
lucaslin975b7d32019-03-21 11:59:22 +08002577 // go back to full connectivity without a disconnect. This is because
2578 // NetworkMonitor can only communicate either PARTIAL_CONNECTIVITY or VALID,
2579 // but not both.
2580 // TODO: Provide multi-testResult to improve the communication between
2581 // ConnectivityService and NetworkMonitor, so that ConnectivityService could
2582 // know the real status of network.
lucaslin43338992019-03-20 18:21:59 +08002583 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002584 (partialConnectivity && !nai.partialConnectivity);
2585
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002586 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002587 final boolean wasValidated = nai.lastValidated;
2588 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002589 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2590 && valid) {
2591 nai.captivePortalLoginNotified = true;
2592 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2593 }
Erik Klinea24d4592018-01-11 21:07:29 +09002594
Erik Klinea24d4592018-01-11 21:07:29 +09002595 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2596
Erik Klinea24d4592018-01-11 21:07:29 +09002597 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002598 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2599 ? " with redirect to " + redirectUrl
2600 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002601 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2602 }
Erik Klinea24d4592018-01-11 21:07:29 +09002603 if (valid != nai.lastValidated) {
2604 if (wasDefault) {
2605 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2606 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002607 }
Erik Klinea24d4592018-01-11 21:07:29 +09002608 final int oldScore = nai.getCurrentScore();
2609 nai.lastValidated = valid;
2610 nai.everValidated |= valid;
2611 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2612 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2613 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002614 if (valid) {
2615 handleFreshlyValidatedNetwork(nai);
2616 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2617 // valid.
2618 mNotifier.clearNotification(nai.network.netId,
2619 NotificationType.NO_INTERNET);
2620 mNotifier.clearNotification(nai.network.netId,
2621 NotificationType.LOST_INTERNET);
2622 }
lucaslin43338992019-03-20 18:21:59 +08002623 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002624 nai.partialConnectivity = partialConnectivity;
2625 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002626 }
2627 updateInetCondition(nai);
2628 // Let the NetworkAgent know the state of its network
2629 Bundle redirectUrlBundle = new Bundle();
2630 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2631 nai.asyncChannel.sendMessage(
2632 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2633 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2634 0, redirectUrlBundle);
2635 if (wasValidated && !nai.lastValidated) {
2636 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002637 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002638 break;
2639 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002640 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002641 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002642 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002643 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002644 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002645 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002646 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002647 nai.lastCaptivePortalDetected = visible;
2648 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002649 if (visible) {
2650 nai.captivePortalLoginNotified = false;
2651 }
Calvin Onbe96da12016-10-11 15:10:46 -07002652 if (nai.lastCaptivePortalDetected &&
2653 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2654 if (DBG) log("Avoiding captive portal network: " + nai.name());
2655 nai.asyncChannel.sendMessage(
2656 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2657 teardownUnneededNetwork(nai);
2658 break;
2659 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002660 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002661 }
2662 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002663 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002664 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002665 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2666 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002667 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002668 if (nai == null) {
2669 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2670 break;
2671 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002672 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002673 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002674 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002675 }
Paul Jensen869868be2014-05-15 10:33:05 -04002676 }
Paul Jensen869868be2014-05-15 10:33:05 -04002677 break;
2678 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002679 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002680 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002681 if (nai == null) break;
2682
Erik Kline736353a2018-03-21 07:18:33 -07002683 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002684 break;
2685 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002686 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002687 return true;
2688 }
2689
Calvin Onbe96da12016-10-11 15:10:46 -07002690 private int getCaptivePortalMode() {
2691 return Settings.Global.getInt(mContext.getContentResolver(),
2692 Settings.Global.CAPTIVE_PORTAL_MODE,
2693 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2694 }
2695
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002696 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2697 switch (msg.what) {
2698 default:
2699 return false;
2700 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2701 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2702 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2703 handleLingerComplete(nai);
2704 }
2705 break;
2706 }
2707 }
2708 return true;
2709 }
2710
Etan Cohenddb720a2019-01-08 12:09:18 -08002711 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2712 switch (msg.what) {
2713 default:
2714 return false;
2715 case android.net.NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2716 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2717 /* callOnUnavailable */ true);
2718 break;
2719 }
2720 }
2721 return true;
2722 }
2723
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002724 @Override
2725 public void handleMessage(Message msg) {
Etan Cohenddb720a2019-01-08 12:09:18 -08002726 if (!maybeHandleAsyncChannelMessage(msg)
2727 && !maybeHandleNetworkMonitorMessage(msg)
2728 && !maybeHandleNetworkAgentInfoMessage(msg)
2729 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002730 maybeHandleNetworkAgentMessage(msg);
2731 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002732 }
2733 }
2734
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002735 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2736 private final NetworkAgentInfo mNai;
2737
2738 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2739 mNai = nai;
2740 }
2741
2742 @Override
2743 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2744 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2745 new Pair<>(mNai, networkMonitor)));
2746 }
2747
2748 @Override
2749 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2750 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2751 testResult, mNai.network.netId, redirectUrl));
2752 }
2753
2754 @Override
2755 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2756 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2757 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2758 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2759 }
2760
2761 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002762 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002763 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002764 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002765
2766 final PendingIntent pendingIntent;
2767 // Only the system server can register notifications with package "android"
2768 final long token = Binder.clearCallingIdentity();
2769 try {
2770 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2771 } finally {
2772 Binder.restoreCallingIdentity(token);
2773 }
2774 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2775 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2776 mNai.network.netId,
2777 pendingIntent));
2778 }
2779
2780 @Override
2781 public void hideProvisioningNotification() {
2782 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2783 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2784 mNai.network.netId));
2785 }
2786 }
2787
Erik Kline736353a2018-03-21 07:18:33 -07002788 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002789 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002790 }
2791
Erik Klinec6d00222018-06-26 18:53:43 +09002792 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2793 if (nai == null) return;
2794 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2795 // in order to restart a validation pass from within netd.
2796 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2797 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2798 updateDnses(nai.linkProperties, null, nai.network.netId);
2799 }
2800 }
2801
Erik Klinea24d4592018-01-11 21:07:29 +09002802 private void handlePrivateDnsSettingsChanged() {
2803 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2804
2805 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002806 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002807 if (networkRequiresValidation(nai)) {
2808 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2809 }
Erik Klinea24d4592018-01-11 21:07:29 +09002810 }
2811 }
2812
Erik Kline736353a2018-03-21 07:18:33 -07002813 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2814 // Private DNS only ever applies to networks that might provide
2815 // Internet access and therefore also require validation.
2816 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002817
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002818 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002819 // schedule DNS resolutions. If a DNS resolution is required the
2820 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002821 try {
2822 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2823 } catch (RemoteException e) {
2824 e.rethrowFromSystemServer();
2825 }
Erik Kline736353a2018-03-21 07:18:33 -07002826
2827 // With Private DNS bypass support, we can proceed to update the
2828 // Private DNS config immediately, even if we're in strict mode
2829 // and have not yet resolved the provider name into a set of IPs.
2830 updatePrivateDns(nai, cfg);
2831 }
2832
2833 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2834 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002835 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002836 }
2837
dalyk7301aa42018-03-05 12:42:22 -05002838 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2839 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2840 if (nai == null) {
2841 return;
2842 }
2843 mDnsManager.updatePrivateDnsValidation(update);
2844 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2845 }
2846
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002847 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2848 int prefixLength) {
2849 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2850 if (nai == null) return;
2851
2852 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2853 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2854
2855 IpPrefix prefix = null;
2856 if (added) {
2857 try {
2858 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2859 prefixLength);
2860 } catch (IllegalArgumentException e) {
2861 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2862 return;
2863 }
2864 }
2865
2866 nai.clatd.setNat64Prefix(prefix);
2867 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2868 }
2869
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002870 private void updateLingerState(NetworkAgentInfo nai, long now) {
2871 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2872 // 2. If the network was lingering and there are now requests, unlinger it.
2873 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2874 // one lingered request, start lingering.
2875 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002876 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002877 if (DBG) log("Unlingering " + nai.name());
2878 nai.unlinger();
2879 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002880 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002881 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002882 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002883 nai.linger();
2884 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2885 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2886 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002887 }
2888
Robert Greenwalt7b816022014-04-18 15:25:25 -07002889 private void handleAsyncChannelHalfConnect(Message msg) {
2890 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002891 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002892 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2893 if (VDBG) log("NetworkFactory connected");
Etan Cohenddb720a2019-01-08 12:09:18 -08002894 // Finish setting up the full connection
2895 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2896 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002897 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002898 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002899 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002900 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09002901 final int score;
2902 final int serial;
2903 if (nai != null) {
2904 score = nai.getCurrentScore();
2905 serial = nai.factorySerialNumber;
2906 } else {
2907 score = 0;
2908 serial = NetworkFactory.SerialNumber.NONE;
2909 }
2910 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2911 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002912 }
2913 } else {
2914 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002915 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002916 }
2917 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2918 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2919 if (VDBG) log("NetworkAgent connected");
2920 // A network agent has requested a connection. Establish the connection.
2921 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2922 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2923 } else {
2924 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002925 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002926 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002927 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002928 synchronized (mNetworkForNetId) {
2929 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002930 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002931 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002932 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002933 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002934 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002935 }
2936 }
2937 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002938
Chalard Jean392971c2018-05-11 20:19:20 +09002939 // This is a no-op if it's called with a message designating a network that has
2940 // already been destroyed, because its reference will not be found in the relevant
2941 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002942 private void handleAsyncChannelDisconnected(Message msg) {
2943 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2944 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002945 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002946 } else {
2947 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2948 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002949 }
2950 }
2951
Chalard Jean392971c2018-05-11 20:19:20 +09002952 // Destroys a network, remove references to it from the internal state managed by
2953 // ConnectivityService, free its interfaces and clean up.
2954 // Must be called on the Handler thread.
2955 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2956 if (DBG) {
2957 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2958 }
lucaslinf80b83b2019-02-12 15:30:13 +08002959 // Clear all notifications of this network.
2960 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002961 // A network agent has disconnected.
2962 // TODO - if we move the logic to the network agent (have them disconnect
2963 // because they lost all their requests or because their score isn't good)
2964 // then they would disconnect organically, report their new state and then
2965 // disconnect the channel.
2966 if (nai.networkInfo.isConnected()) {
2967 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2968 null, null);
2969 }
2970 final boolean wasDefault = isDefaultNetwork(nai);
2971 if (wasDefault) {
2972 mDefaultInetConditionPublished = 0;
2973 // Log default network disconnection before required book-keeping.
2974 // Let rematchAllNetworksAndRequests() below record a new default network event
2975 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2976 // whose timestamps tell how long it takes to recover a default network.
2977 long now = SystemClock.elapsedRealtime();
2978 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2979 }
2980 notifyIfacesChangedForNetworkStats();
2981 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2982 // by other networks that are already connected. Perhaps that can be done by
2983 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2984 // of rematchAllNetworksAndRequests
2985 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai06835112019-01-03 18:50:15 +08002986 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002987 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2988 // Disable wakeup packet monitoring for each interface.
2989 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2990 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002991 try {
2992 nai.networkMonitor().notifyNetworkDisconnected();
2993 } catch (RemoteException e) {
2994 e.rethrowFromSystemServer();
2995 }
Chalard Jean392971c2018-05-11 20:19:20 +09002996 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09002997 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09002998 synchronized (mNetworkForNetId) {
2999 // Remove the NetworkAgent, but don't mark the netId as
3000 // available until we've told netd to delete it below.
3001 mNetworkForNetId.remove(nai.network.netId);
3002 }
3003 // Remove all previously satisfied requests.
3004 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3005 NetworkRequest request = nai.requestAt(i);
3006 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
3007 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3008 clearNetworkForRequest(request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09003009 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003010 }
3011 }
3012 nai.clearLingerState();
3013 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003014 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003015 notifyLockdownVpn(nai);
3016 ensureNetworkTransitionWakelock(nai.name());
3017 }
3018 mLegacyTypeTracker.remove(nai, wasDefault);
3019 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3020 updateAllVpnsCapabilities();
3021 }
3022 rematchAllNetworksAndRequests(null, 0);
3023 mLingerMonitor.noteDisconnect(nai);
3024 if (nai.created) {
3025 // Tell netd to clean up the configuration for this network
3026 // (routing rules, DNS, etc).
3027 // This may be slow as it requires a lot of netd shelling out to ip and
3028 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3029 // after we've rematched networks with requests which should make a potential
3030 // fallback network the default or requested a new network from the
3031 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3032 // long time.
3033 try {
Luke Huang65914772019-03-16 00:31:46 +08003034 mNetd.networkDestroy(nai.network.netId);
3035 } catch (RemoteException | ServiceSpecificException e) {
3036 loge("Exception destroying network: " + e);
Chalard Jean392971c2018-05-11 20:19:20 +09003037 }
3038 mDnsManager.removeNetwork(nai.network);
3039 }
3040 synchronized (mNetworkForNetId) {
3041 mNetIdInUse.delete(nai.network.netId);
3042 }
3043 }
3044
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003045 // If this method proves to be too slow then we can maintain a separate
3046 // pendingIntent => NetworkRequestInfo map.
3047 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3048 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3049 Intent intent = pendingIntent.getIntent();
3050 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3051 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3052 if (existingPendingIntent != null &&
3053 existingPendingIntent.getIntent().filterEquals(intent)) {
3054 return entry.getValue();
3055 }
3056 }
3057 return null;
3058 }
3059
3060 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3061 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3062
3063 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3064 if (existingRequest != null) { // remove the existing request.
3065 if (DBG) log("Replacing " + existingRequest.request + " with "
3066 + nri.request + " because their intents matched.");
Etan Cohenddb720a2019-01-08 12:09:18 -08003067 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3068 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003069 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003070 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003071 }
3072
Erik Klineda4bfa82015-04-30 12:58:40 +09003073 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003074 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003075 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003076 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003077 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003078 if (nri.request.networkCapabilities.hasSignalStrength() &&
3079 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3080 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003081 }
3082 }
3083 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003084 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003085 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003086 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003087 }
3088 }
3089
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003090 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3091 int callingUid) {
3092 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3093 if (nri != null) {
Etan Cohenddb720a2019-01-08 12:09:18 -08003094 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003095 }
3096 }
3097
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003098 // Determines whether the network is the best (or could become the best, if it validated), for
3099 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3100 // on the value of reason:
3101 //
3102 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3103 // then it should be torn down.
3104 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3105 // then it should be lingered.
3106 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3107 final int numRequests;
3108 switch (reason) {
3109 case TEARDOWN:
3110 numRequests = nai.numRequestNetworkRequests();
3111 break;
3112 case LINGER:
3113 numRequests = nai.numForegroundNetworkRequests();
3114 break;
3115 default:
3116 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3117 return true;
3118 }
3119
3120 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003121 return false;
3122 }
Paul Jensene0988542015-06-25 15:30:08 -04003123 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003124 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3125 // Background requests don't affect lingering.
3126 continue;
3127 }
3128
Paul Jensene0988542015-06-25 15:30:08 -04003129 // If this Network is already the highest scoring Network for a request, or if
3130 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003131 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003132 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003133 // Note that this catches two important cases:
3134 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3135 // is currently satisfying the request. This is desirable when
3136 // cellular ends up validating but WiFi does not.
3137 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003138 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003139 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003140 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003141 nai.getCurrentScoreAsValidated())) {
3142 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003143 }
3144 }
Paul Jensene0988542015-06-25 15:30:08 -04003145 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003146 }
3147
Erik Klineacdd6392016-07-07 16:50:58 +09003148 private NetworkRequestInfo getNriForAppRequest(
3149 NetworkRequest request, int callingUid, String requestedOperation) {
3150 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3151
Robert Greenwalt9258c642014-03-26 16:47:06 -07003152 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003153 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003154 log(String.format("UID %d attempted to %s for unowned request %s",
3155 callingUid, requestedOperation, nri));
3156 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003157 }
Erik Klineacdd6392016-07-07 16:50:58 +09003158 }
3159
3160 return nri;
3161 }
3162
Erik Kline57faba92015-11-25 12:49:38 +09003163 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003164 if (mNetworkRequests.get(nri.request) == null) {
3165 return;
Erik Kline57faba92015-11-25 12:49:38 +09003166 }
Hugo Benichicd952782017-09-20 11:20:14 +09003167 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003168 return;
3169 }
3170 if (VDBG || (DBG && nri.request.isRequest())) {
3171 log("releasing " + nri.request + " (timeout)");
3172 }
3173 handleRemoveNetworkRequest(nri);
3174 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003175 }
3176
Etan Cohenddb720a2019-01-08 12:09:18 -08003177 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3178 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003179 final NetworkRequestInfo nri =
3180 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3181 if (nri == null) {
3182 return;
Erik Kline57faba92015-11-25 12:49:38 +09003183 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003184 if (VDBG || (DBG && nri.request.isRequest())) {
3185 log("releasing " + nri.request + " (release request)");
3186 }
3187 handleRemoveNetworkRequest(nri);
Etan Cohenddb720a2019-01-08 12:09:18 -08003188 if (callOnUnavailable) {
3189 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3190 }
Erik Kline57faba92015-11-25 12:49:38 +09003191 }
Erik Klineacdd6392016-07-07 16:50:58 +09003192
Hugo Benichidba33db2017-03-23 22:40:44 +09003193 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003194 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003195 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003196
Erik Klineacdd6392016-07-07 16:50:58 +09003197 synchronized (mUidToNetworkRequestCount) {
3198 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3199 if (requests < 1) {
3200 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3201 nri.mUid);
3202 } else if (requests == 1) {
3203 mUidToNetworkRequestCount.removeAt(
3204 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3205 } else {
3206 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3207 }
3208 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003209
Erik Klineacdd6392016-07-07 16:50:58 +09003210 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3211 if (nri.request.isRequest()) {
3212 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003213 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003214 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003215 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003216 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003217 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003218 log(" Removing from current network " + nai.name() +
3219 ", leaving " + nai.numNetworkRequests() + " requests.");
3220 }
3221 // If there are still lingered requests on this network, don't tear it down,
3222 // but resume lingering instead.
3223 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003224 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003225 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3226 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003227 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003228 wasKept = true;
3229 }
Hugo Benichicd952782017-09-20 11:20:14 +09003230 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003231 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3232 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003233 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003234 }
Erik Klineacdd6392016-07-07 16:50:58 +09003235 }
3236
Erik Klineacdd6392016-07-07 16:50:58 +09003237 // Maintain the illusion. When this request arrived, we might have pretended
3238 // that a network connected to serve it, even though the network was already
3239 // connected. Now that this request has gone away, we might have to pretend
3240 // that the network disconnected. LegacyTypeTracker will generate that
3241 // phantom disconnect for this type.
3242 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3243 boolean doRemove = true;
3244 if (wasKept) {
3245 // check if any of the remaining requests for this network are for the
3246 // same legacy type - if so, don't remove the nai
3247 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3248 NetworkRequest otherRequest = nai.requestAt(i);
3249 if (otherRequest.legacyType == nri.request.legacyType &&
3250 otherRequest.isRequest()) {
3251 if (DBG) log(" still have other legacy request - leaving");
3252 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003253 }
3254 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003255 }
3256
Erik Klineacdd6392016-07-07 16:50:58 +09003257 if (doRemove) {
3258 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003259 }
3260 }
Erik Klineacdd6392016-07-07 16:50:58 +09003261
3262 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3263 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3264 nri.request);
3265 }
3266 } else {
3267 // listens don't have a singular affectedNetwork. Check all networks to see
3268 // if this listen request applies and remove it.
3269 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3270 nai.removeRequest(nri.request.requestId);
3271 if (nri.request.networkCapabilities.hasSignalStrength() &&
3272 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3273 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3274 }
3275 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003276 }
3277 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003278
Lorenzo Colitti18660282016-07-04 12:55:44 +09003279 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003280 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003281 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003282 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003283 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003284 }
3285
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003286 @Override
lucasline252a742019-03-12 13:08:03 +08003287 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3288 enforceNetworkStackSettingsOrSetup();
3289 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3290 encodeBool(accept), encodeBool(always), network));
3291 }
3292
3293 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003294 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003295 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003296 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3297 }
3298
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003299 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3300 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3301 " accept=" + accept + " always=" + always);
3302
3303 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3304 if (nai == null) {
3305 // Nothing to do.
3306 return;
3307 }
3308
3309 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003310 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003311 return;
3312 }
3313
3314 if (!nai.networkMisc.explicitlySelected) {
3315 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3316 }
3317
3318 if (accept != nai.networkMisc.acceptUnvalidated) {
3319 int oldScore = nai.getCurrentScore();
3320 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003321 // If network becomes partial connectivity and user already accepted to use this
3322 // network, we should respect the user's option and don't need to popup the
3323 // PARTIAL_CONNECTIVITY notification to user again.
3324 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003325 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003326 sendUpdatedScoreToFactories(nai);
3327 }
3328
3329 if (always) {
3330 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003331 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003332 }
3333
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003334 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003335 // Tell the NetworkAgent to not automatically reconnect to the network.
3336 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003337 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003338 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003339 }
3340
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003341 }
3342
lucasline252a742019-03-12 13:08:03 +08003343 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3344 boolean always) {
3345 if (DBG) {
3346 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3347 + " always=" + always);
3348 }
3349
3350 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3351 if (nai == null) {
3352 // Nothing to do.
3353 return;
3354 }
3355
3356 if (nai.lastValidated) {
3357 // The network validated while the dialog box was up. Take no action.
3358 return;
3359 }
3360
3361 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3362 nai.networkMisc.acceptPartialConnectivity = accept;
3363 }
3364
3365 // TODO: Use the current design or save the user choice into IpMemoryStore.
3366 if (always) {
3367 nai.asyncChannel.sendMessage(
3368 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3369 }
3370
3371 if (!accept) {
3372 // Tell the NetworkAgent to not automatically reconnect to the network.
3373 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3374 // Tear down the network.
3375 teardownUnneededNetwork(nai);
3376 } else {
lucaslin43338992019-03-20 18:21:59 +08003377 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3378 // result in a partial connectivity result which will be processed by
3379 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003380 try {
lucaslin43338992019-03-20 18:21:59 +08003381 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003382 } catch (RemoteException e) {
3383 e.rethrowFromSystemServer();
3384 }
3385 }
3386 }
3387
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003388 private void handleSetAvoidUnvalidated(Network network) {
3389 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3390 if (nai == null || nai.lastValidated) {
3391 // Nothing to do. The network either disconnected or revalidated.
3392 return;
3393 }
3394 if (!nai.avoidUnvalidated) {
3395 int oldScore = nai.getCurrentScore();
3396 nai.avoidUnvalidated = true;
3397 rematchAllNetworksAndRequests(nai, oldScore);
3398 sendUpdatedScoreToFactories(nai);
3399 }
3400 }
3401
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003402 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003403 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003404 mHandler.sendMessageDelayed(
3405 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3406 PROMPT_UNVALIDATED_DELAY_MS);
3407 }
3408
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003409 @Override
3410 public void startCaptivePortalApp(Network network) {
3411 enforceConnectivityInternalPermission();
3412 mHandler.post(() -> {
3413 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3414 if (nai == null) return;
3415 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003416 try {
3417 nai.networkMonitor().launchCaptivePortalApp();
3418 } catch (RemoteException e) {
3419 e.rethrowFromSystemServer();
3420 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003421 });
3422 }
3423
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003424 /**
3425 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3426 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003427 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003428 * @param appExtras Bundle to use as intent extras for the captive portal application.
3429 * Must be treated as opaque to avoid preventing the captive portal app to
3430 * update its arguments.
3431 */
3432 @Override
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003433 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003434 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3435
3436 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3437 appIntent.putExtras(appExtras);
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003438 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3439 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003440 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3441
3442 Binder.withCleanCallingIdentity(() ->
3443 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3444 }
3445
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003446 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3447 private final Network mNetwork;
3448
3449 private CaptivePortalImpl(Network network) {
3450 mNetwork = network;
3451 }
3452
3453 @Override
3454 public void appResponse(final int response) throws RemoteException {
3455 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3456 enforceSettingsPermission();
3457 }
3458
3459 // getNetworkAgentInfoForNetwork is thread-safe
3460 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3461 if (nai == null) return;
3462
3463 // nai.networkMonitor() is thread-safe
3464 final INetworkMonitor nm = nai.networkMonitor();
3465 if (nm == null) return;
3466
3467 final long token = Binder.clearCallingIdentity();
3468 try {
3469 nm.notifyCaptivePortalAppFinished(response);
3470 } finally {
3471 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3472 Binder.restoreCallingIdentity(token);
3473 }
3474 }
3475
3476 @Override
3477 public void logEvent(int eventId, String packageName) {
3478 enforceSettingsPermission();
3479
3480 new MetricsLogger().action(eventId, packageName);
3481 }
3482 }
3483
Hugo Benichic8e9e122016-09-14 23:23:08 +00003484 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003485 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003486 }
3487
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09003488 /**
3489 * Return whether the device should maintain continuous, working connectivity by switching away
3490 * from WiFi networks having no connectivity.
3491 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3492 */
3493 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003494 if (!checkNetworkStackPermission()) {
3495 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3496 }
3497 return avoidBadWifi();
3498 }
3499
3500
Erik Kline065ab6e2016-10-02 18:02:14 +09003501 private void rematchForAvoidBadWifiUpdate() {
3502 rematchAllNetworksAndRequests(null, 0);
3503 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3504 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3505 sendUpdatedScoreToFactories(nai);
3506 }
3507 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003508 }
3509
Erik Kline065ab6e2016-10-02 18:02:14 +09003510 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003511 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003512 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003513 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003514 if (!configRestrict) {
3515 pw.println("Bad Wi-Fi avoidance: unrestricted");
3516 return;
3517 }
3518
3519 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3520 pw.increaseIndent();
3521 pw.println("Config restrict: " + configRestrict);
3522
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003523 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003524 String description;
3525 // Can't use a switch statement because strings are legal case labels, but null is not.
3526 if ("0".equals(value)) {
3527 description = "get stuck";
3528 } else if (value == null) {
3529 description = "prompt";
3530 } else if ("1".equals(value)) {
3531 description = "avoid";
3532 } else {
3533 description = value + " (?)";
3534 }
3535 pw.println("User setting: " + description);
3536 pw.println("Network overrides:");
3537 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003538 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003539 if (nai.avoidUnvalidated) {
3540 pw.println(nai.name());
3541 }
3542 }
3543 pw.decreaseIndent();
3544 pw.decreaseIndent();
3545 }
3546
lucaslind2e045e02019-01-24 15:55:30 +08003547 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003548 final String action;
3549 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003550 case LOGGED_IN:
3551 action = Settings.ACTION_WIFI_SETTINGS;
3552 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3553 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3554 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3555 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003556 case NO_INTERNET:
3557 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3558 break;
3559 case LOST_INTERNET:
3560 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3561 break;
lucasline252a742019-03-12 13:08:03 +08003562 case PARTIAL_CONNECTIVITY:
3563 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3564 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003565 default:
3566 Slog.wtf(TAG, "Unknown notification type " + type);
3567 return;
3568 }
3569
3570 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003571 if (type != NotificationType.LOGGED_IN) {
3572 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3573 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3574 intent.setClassName("com.android.settings",
3575 "com.android.settings.wifi.WifiNoInternetDialog");
3576 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003577
3578 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3579 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3580 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3581 }
3582
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003583 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003584 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003585 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3586
lucasline252a742019-03-12 13:08:03 +08003587 // Only prompt if the network is unvalidated or network has partial internet connectivity
3588 // and was explicitly selected by the user, and if we haven't already been told to switch
3589 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3590 // because we're already prompting the user to sign in.
3591 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3592 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003593 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3594 // we should reevaluate how to handle acceptPartialConnectivity when network just
3595 // connected.
lucasline252a742019-03-12 13:08:03 +08003596 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003597 return;
3598 }
lucasline252a742019-03-12 13:08:03 +08003599 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3600 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3601 // popup the notification immediately when the network is partial connectivity.
3602 if (nai.partialConnectivity) {
lucaslin975b7d32019-03-21 11:59:22 +08003603 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucasline252a742019-03-12 13:08:03 +08003604 } else {
3605 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3606 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003607 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003608
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003609 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3610 NetworkCapabilities nc = nai.networkCapabilities;
3611 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003612
lucasline252a742019-03-12 13:08:03 +08003613 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3614 return;
3615 }
3616
3617 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003618 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003619 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003620 }
3621
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003622 @Override
3623 public int getMultipathPreference(Network network) {
3624 enforceAccessPermission();
3625
3626 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003627 if (nai != null && nai.networkCapabilities
3628 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003629 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3630 }
3631
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003632 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3633 if (networkPreference != null) {
3634 return networkPreference;
3635 }
3636
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003637 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3638 }
3639
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003640 @Override
3641 public NetworkRequest getDefaultRequest() {
3642 return mDefaultRequest;
3643 }
3644
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003645 private class InternalHandler extends Handler {
3646 public InternalHandler(Looper looper) {
3647 super(looper);
3648 }
3649
3650 @Override
3651 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003652 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003653 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003654 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003655 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003656 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003657 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003658 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003659 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003660 break;
3661 }
Jason Monkdecd2952013-10-10 14:02:51 -04003662 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003663 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003664 break;
3665 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003666 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003667 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3668 break;
3669 }
3670 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3671 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003672 break;
3673 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003674 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003675 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3676 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3677 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003678 break;
3679 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003680 case EVENT_REGISTER_NETWORK_REQUEST:
3681 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003682 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003683 break;
3684 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003685 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3686 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003687 handleRegisterNetworkRequestWithIntent(msg);
3688 break;
3689 }
Erik Kline57faba92015-11-25 12:49:38 +09003690 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3691 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3692 handleTimedOutNetworkRequest(nri);
3693 break;
3694 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003695 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3696 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3697 break;
3698 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003699 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenddb720a2019-01-08 12:09:18 -08003700 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3701 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003702 break;
3703 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003704 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003705 Network network = (Network) msg.obj;
3706 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003707 break;
3708 }
lucasline252a742019-03-12 13:08:03 +08003709 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3710 Network network = (Network) msg.obj;
3711 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3712 toBool(msg.arg2));
3713 break;
3714 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003715 case EVENT_SET_AVOID_UNVALIDATED: {
3716 handleSetAvoidUnvalidated((Network) msg.obj);
3717 break;
3718 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003719 case EVENT_PROMPT_UNVALIDATED: {
3720 handlePromptUnvalidated((Network) msg.obj);
3721 break;
3722 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003723 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3724 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003725 break;
3726 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003727 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003728 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003729 mKeepaliveTracker.handleStartKeepalive(msg);
3730 break;
3731 }
3732 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003733 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003734 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3735 int slot = msg.arg1;
3736 int reason = msg.arg2;
3737 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3738 break;
3739 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003740 case EVENT_SYSTEM_READY: {
3741 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003742 // Might have been called already in handleRegisterNetworkAgent since
3743 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3744 // this several times is fine.
3745 try {
3746 nai.networkMonitor().notifySystemReady();
3747 } catch (RemoteException e) {
3748 e.rethrowFromSystemServer();
3749 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003750 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003751 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003752 break;
3753 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003754 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003755 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003756 break;
3757 }
Erik Klinea24d4592018-01-11 21:07:29 +09003758 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3759 handlePrivateDnsSettingsChanged();
3760 break;
dalyk7301aa42018-03-05 12:42:22 -05003761 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3762 handlePrivateDnsValidationUpdate(
3763 (PrivateDnsValidationUpdate) msg.obj);
3764 break;
junyulai05986c62018-08-07 19:50:45 +08003765 case EVENT_UID_RULES_CHANGED:
3766 handleUidRulesChanged(msg.arg1, msg.arg2);
3767 break;
3768 case EVENT_DATA_SAVER_CHANGED:
3769 handleRestrictBackgroundChanged(toBool(msg.arg1));
3770 break;
lucaslind2e045e02019-01-24 15:55:30 +08003771 case EVENT_TIMEOUT_NOTIFICATION:
3772 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3773 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 }
3775 }
3776 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003777
3778 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003779 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003780 public int tether(String iface, String callerPkg) {
3781 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003782 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003783 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003784 } else {
3785 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3786 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003787 }
3788
3789 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003790 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003791 public int untether(String iface, String callerPkg) {
3792 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003793
3794 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003795 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003796 } else {
3797 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3798 }
3799 }
3800
3801 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003802 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003803 public int getLastTetherError(String iface) {
3804 enforceTetherAccessPermission();
3805
3806 if (isTetheringSupported()) {
3807 return mTethering.getLastTetherError(iface);
3808 } else {
3809 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3810 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003811 }
3812
3813 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003814 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003815 public String[] getTetherableUsbRegexs() {
3816 enforceTetherAccessPermission();
3817 if (isTetheringSupported()) {
3818 return mTethering.getTetherableUsbRegexs();
3819 } else {
3820 return new String[0];
3821 }
3822 }
3823
Lorenzo Colitti18660282016-07-04 12:55:44 +09003824 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003825 public String[] getTetherableWifiRegexs() {
3826 enforceTetherAccessPermission();
3827 if (isTetheringSupported()) {
3828 return mTethering.getTetherableWifiRegexs();
3829 } else {
3830 return new String[0];
3831 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003832 }
3833
Lorenzo Colitti18660282016-07-04 12:55:44 +09003834 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003835 public String[] getTetherableBluetoothRegexs() {
3836 enforceTetherAccessPermission();
3837 if (isTetheringSupported()) {
3838 return mTethering.getTetherableBluetoothRegexs();
3839 } else {
3840 return new String[0];
3841 }
3842 }
3843
Lorenzo Colitti18660282016-07-04 12:55:44 +09003844 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003845 public int setUsbTethering(boolean enable, String callerPkg) {
3846 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003847 if (isTetheringSupported()) {
3848 return mTethering.setUsbTethering(enable);
3849 } else {
3850 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3851 }
3852 }
3853
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003854 // TODO - move iface listing, queries, etc to new module
3855 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003856 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003857 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003858 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003859 return mTethering.getTetherableIfaces();
3860 }
3861
Lorenzo Colitti18660282016-07-04 12:55:44 +09003862 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003863 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003864 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003865 return mTethering.getTetheredIfaces();
3866 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003867
Lorenzo Colitti18660282016-07-04 12:55:44 +09003868 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003869 public String[] getTetheringErroredIfaces() {
3870 enforceTetherAccessPermission();
3871 return mTethering.getErroredIfaces();
3872 }
3873
Lorenzo Colitti18660282016-07-04 12:55:44 +09003874 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003875 public String[] getTetheredDhcpRanges() {
3876 enforceConnectivityInternalPermission();
3877 return mTethering.getTetheredDhcpRanges();
3878 }
3879
Udam Saini0e94c362017-06-07 12:06:28 -07003880 @Override
3881 public boolean isTetheringSupported(String callerPkg) {
3882 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3883 return isTetheringSupported();
3884 }
3885
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003886 // if ro.tether.denied = true we default to no tethering
3887 // gservices could set the secure setting to 1 though to enable it on a build where it
3888 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003889 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003890 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3891 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3892 Settings.Global.TETHER_SUPPORTED, defaultVal));
3893 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003894 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003895
3896 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3897 boolean adminUser = false;
3898 final long token = Binder.clearCallingIdentity();
3899 try {
3900 adminUser = mUserManager.isAdminUser();
3901 } finally {
3902 Binder.restoreCallingIdentity(token);
3903 }
3904
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003905 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003906 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003907
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003908 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003909 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3910 String callerPkg) {
3911 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003912 if (!isTetheringSupported()) {
3913 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3914 return;
3915 }
3916 mTethering.startTethering(type, receiver, showProvisioningUi);
3917 }
3918
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003919 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003920 public void stopTethering(int type, String callerPkg) {
3921 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003922 mTethering.stopTethering(type);
3923 }
3924
markchienf2731272019-01-16 17:44:13 +08003925 /**
3926 * Get the latest value of the tethering entitlement check.
3927 *
3928 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3929 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3930 * if it's really needed.
3931 */
3932 @Override
markchien9554abf2019-03-06 16:25:00 +08003933 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003934 boolean showEntitlementUi, String callerPkg) {
3935 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003936 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003937 }
3938
markchien26299ed2019-02-27 14:56:11 +08003939 /** Register tethering event callback. */
3940 @Override
3941 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3942 String callerPkg) {
3943 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3944 mTethering.registerTetheringEventCallback(callback);
3945 }
3946
3947 /** Unregister tethering event callback. */
3948 @Override
3949 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3950 String callerPkg) {
3951 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3952 mTethering.unregisterTetheringEventCallback(callback);
3953 }
3954
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003955 // Called when we lose the default network and have no replacement yet.
3956 // This will automatically be cleared after X seconds or a new default network
3957 // becomes CONNECTED, whichever happens first. The timer is started by the
3958 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003959 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003960 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003961 if (mNetTransitionWakeLock.isHeld()) {
3962 return;
3963 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003964 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003965 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3966 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003967 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003968 mWakelockLogs.log("ACQUIRE for " + forWhom);
3969 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3970 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003971 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003972
Hugo Benichi4c31b342017-03-30 23:18:10 +09003973 // Called when we gain a new default network to release the network transition wakelock in a
3974 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3975 // message is cancelled.
3976 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003977 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003978 if (!mNetTransitionWakeLock.isHeld()) {
3979 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003980 }
3981 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003982 // Cancel self timeout on wakelock hold.
3983 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3984 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3985 mHandler.sendMessageDelayed(msg, 1000);
3986 }
3987
3988 // Called when either message of ensureNetworkTransitionWakelock or
3989 // scheduleReleaseNetworkTransitionWakelock is processed.
3990 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3991 String event = eventName(eventId);
3992 synchronized (this) {
3993 if (!mNetTransitionWakeLock.isHeld()) {
3994 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3995 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3996 return;
3997 }
3998 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003999 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4000 mTotalWakelockDurationMs += lockDuration;
4001 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4002 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004003 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004004 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004005 }
4006
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004007 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09004008 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004009 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004010 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004011 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004012 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004013 }
4014
Lorenzo Colitti18660282016-07-04 12:55:44 +09004015 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004016 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004017 enforceAccessPermission();
4018 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004019 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004020 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004021 mHandler.sendMessage(
4022 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4023 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004024
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004025 private void handleReportNetworkConnectivity(
4026 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004027 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004028 if (network == null) {
4029 nai = getDefaultNetwork();
4030 } else {
4031 nai = getNetworkAgentInfoForNetwork(network);
4032 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004033 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4034 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4035 return;
4036 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004037 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004038 if (hasConnectivity == nai.lastValidated) {
4039 return;
4040 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004041 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004042 int netid = nai.network.netId;
4043 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004044 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004045 // Validating a network that has not yet connected could result in a call to
4046 // rematchNetworkAndRequests() which is not meant to work on such networks.
4047 if (!nai.everConnected) {
4048 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004049 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004050 LinkProperties lp = getLinkProperties(nai);
4051 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4052 return;
4053 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004054 try {
4055 nai.networkMonitor().forceReevaluation(uid);
4056 } catch (RemoteException e) {
4057 e.rethrowFromSystemServer();
4058 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004059 }
4060
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004061 /**
4062 * Returns information about the proxy a certain network is using. If given a null network, it
4063 * it will return the proxy for the bound network for the caller app or the default proxy if
4064 * none.
4065 *
4066 * @param network the network we want to get the proxy information for.
4067 * @return Proxy information if a network has a proxy configured, or otherwise null.
4068 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004069 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004070 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004071 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004072 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004073 if (network == null) {
4074 // Get the network associated with the calling UID.
4075 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4076 true);
4077 if (activeNetwork == null) {
4078 return null;
4079 }
4080 return getLinkPropertiesProxyInfo(activeNetwork);
4081 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4082 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4083 // caller may not have.
4084 return getLinkPropertiesProxyInfo(network);
4085 }
4086 // No proxy info available if the calling UID does not have network access.
4087 return null;
4088 }
4089
4090 @VisibleForTesting
4091 protected boolean queryUserAccess(int uid, int netId) {
4092 return NetworkUtils.queryUserAccess(uid, netId);
4093 }
4094
4095 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004096 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4097 if (nai == null) return null;
4098 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004099 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4100 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004101 }
4102 }
4103
Chalard Jean3c443fc2018-06-07 18:37:59 +09004104 @Override
4105 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004106 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004107 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004108 }
4109
Chalard Jean5afbc832018-06-07 18:02:37 +09004110 @Override
4111 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004112 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004113 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004114 }
4115
Jason Monk207900c2014-04-25 15:00:09 -04004116 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004117 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004118 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004119 proxy = null;
4120 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004121 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004122 }
4123
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004124 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4125 // when any network changes proxy.
4126 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4127 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004128 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004129 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4130 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4131
Chalard Jean4949dd72018-06-07 17:41:29 +09004132 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004133 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004134 }
4135 }
4136
Robert Greenwalt434203a2010-10-11 16:00:27 -07004137 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004138 final private HashMap<Uri, Integer> mUriEventMap;
4139 final private Context mContext;
4140 final private Handler mHandler;
4141
4142 SettingsObserver(Context context, Handler handler) {
4143 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004144 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004145 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004146 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004147 }
4148
Erik Klineda4bfa82015-04-30 12:58:40 +09004149 void observe(Uri uri, int what) {
4150 mUriEventMap.put(uri, what);
4151 final ContentResolver resolver = mContext.getContentResolver();
4152 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004153 }
4154
4155 @Override
4156 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004157 Slog.wtf(TAG, "Should never be reached.");
4158 }
4159
4160 @Override
4161 public void onChange(boolean selfChange, Uri uri) {
4162 final Integer what = mUriEventMap.get(uri);
4163 if (what != null) {
4164 mHandler.obtainMessage(what.intValue()).sendToTarget();
4165 } else {
4166 loge("No matching event to send for URI=" + uri);
4167 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004168 }
4169 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004170
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004171 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004172 Slog.d(TAG, s);
4173 }
4174
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004175 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004176 Slog.e(TAG, s);
4177 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004178
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004179 private static void loge(String s, Throwable t) {
4180 Slog.e(TAG, s, t);
4181 }
4182
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004183 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004184 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004185 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4186 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4187 *
4188 * @param oldPackage Package name of the application which currently controls VPN, which will
4189 * be replaced. If there is no such application, this should should either be
4190 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4191 * @param newPackage Package name of the application which should gain control of VPN, or
4192 * {@code null} to disable.
4193 * @param userId User for whom to prepare the new VPN.
4194 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004195 * @hide
4196 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004197 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004198 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4199 int userId) {
4200 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004201
Hugo Benichi20035e02017-04-26 14:53:28 +09004202 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004203 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004204 Vpn vpn = mVpns.get(userId);
4205 if (vpn != null) {
4206 return vpn.prepare(oldPackage, newPackage);
4207 } else {
4208 return false;
4209 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004210 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004211 }
4212
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004213 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004214 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4215 * This method is used by system-privileged apps.
4216 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4217 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4218 *
4219 * @param packageName The package for which authorization state should change.
4220 * @param userId User for whom {@code packageName} is installed.
4221 * @param authorized {@code true} if this app should be able to start a VPN connection without
4222 * explicit user approval, {@code false} if not.
4223 *
Jeff Davidson05542602014-08-11 14:07:27 -07004224 * @hide
4225 */
4226 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004227 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4228 enforceCrossUserPermission(userId);
4229
Hugo Benichi20035e02017-04-26 14:53:28 +09004230 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004231 Vpn vpn = mVpns.get(userId);
4232 if (vpn != null) {
4233 vpn.setPackageAuthorization(packageName, authorized);
4234 }
Jeff Davidson05542602014-08-11 14:07:27 -07004235 }
4236 }
4237
4238 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004239 * Configure a TUN interface and return its file descriptor. Parameters
4240 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004241 * and not available in ConnectivityManager. Permissions are checked in
4242 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004243 * @hide
4244 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004245 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004246 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004247 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004248 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004249 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004250 return mVpns.get(user).establish(config);
4251 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004252 }
4253
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004254 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004255 * Start legacy VPN, controlling native daemons as needed. Creates a
4256 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004257 */
4258 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004259 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004260 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004261 final LinkProperties egress = getActiveLinkProperties();
4262 if (egress == null) {
4263 throw new IllegalStateException("Missing active network connection");
4264 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004265 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004266 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004267 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4268 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004269 }
4270
4271 /**
4272 * Return the information of the ongoing legacy VPN. This method is used
4273 * by VpnSettings and not available in ConnectivityManager. Permissions
4274 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004275 */
4276 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004277 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4278 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004279
Hugo Benichi20035e02017-04-26 14:53:28 +09004280 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004281 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004282 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004283 }
4284
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004285 /**
Varun Anandd33cbc62019-02-07 14:13:13 -08004286 * Return the information of all ongoing VPNs.
4287 *
4288 * <p>This method is used to update NetworkStatsService.
4289 *
4290 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004291 */
Varun Anandd33cbc62019-02-07 14:13:13 -08004292 private VpnInfo[] getAllVpnInfo() {
4293 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004294 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004295 if (mLockdownEnabled) {
4296 return new VpnInfo[0];
4297 }
4298
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004299 List<VpnInfo> infoList = new ArrayList<>();
4300 for (int i = 0; i < mVpns.size(); i++) {
4301 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4302 if (info != null) {
4303 infoList.add(info);
4304 }
4305 }
4306 return infoList.toArray(new VpnInfo[infoList.size()]);
4307 }
4308 }
4309
4310 /**
4311 * @return VPN information for accounting, or null if we can't retrieve all required
Varun Anand95aa6d42019-02-17 23:43:25 -08004312 * information, e.g underlying ifaces.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004313 */
4314 @Nullable
4315 private VpnInfo createVpnInfo(Vpn vpn) {
4316 VpnInfo info = vpn.getVpnInfo();
4317 if (info == null) {
4318 return null;
4319 }
4320 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4321 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4322 // the underlyingNetworks list.
4323 if (underlyingNetworks == null) {
Varun Anand95aa6d42019-02-17 23:43:25 -08004324 NetworkAgentInfo defaultNai = getDefaultNetwork();
4325 if (defaultNai != null && defaultNai.linkProperties != null) {
4326 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004327 }
4328 }
Varun Anand95aa6d42019-02-17 23:43:25 -08004329 if (underlyingNetworks != null && underlyingNetworks.length > 0) {
4330 List<String> interfaces = new ArrayList<>();
4331 for (Network network : underlyingNetworks) {
4332 LinkProperties lp = getLinkProperties(network);
4333 if (lp != null) {
4334 interfaces.add(lp.getInterfaceName());
4335 }
4336 }
4337 if (!interfaces.isEmpty()) {
4338 info.underlyingIfaces = interfaces.toArray(new String[interfaces.size()]);
4339 }
4340 }
4341 return info.underlyingIfaces == null ? null : info;
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004342 }
4343
4344 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004345 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4346 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004347 * Permissions are checked in Vpn class.
4348 * @hide
4349 */
4350 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004351 public VpnConfig getVpnConfig(int userId) {
4352 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004353 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004354 Vpn vpn = mVpns.get(userId);
4355 if (vpn != null) {
4356 return vpn.getVpnConfig();
4357 } else {
4358 return null;
4359 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004360 }
4361 }
4362
Chalard Jean6b65ec72018-05-18 22:02:56 +09004363 /**
4364 * Ask all VPN objects to recompute and update their capabilities.
4365 *
4366 * When underlying networks change, VPNs may have to update capabilities to reflect things
4367 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4368 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4369 * handler thread through their agent, this is asynchronous. When the capabilities objects
4370 * are computed they will be up-to-date as they are computed synchronously from here and
4371 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004372 */
4373 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004374 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004375 synchronized (mVpns) {
4376 for (int i = 0; i < mVpns.size(); i++) {
4377 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004378 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4379 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004380 }
4381 }
4382 }
4383
Varun Anand4fa80e82019-02-06 10:13:38 -08004384 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4385 ensureRunningOnConnectivityServiceThread();
4386 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4387 if (vpnNai == null || nc == null) {
4388 return;
4389 }
4390 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4391 }
4392
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004393 @Override
4394 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004395 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4396 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4397 return false;
4398 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004399
Hugo Benichi69744342017-11-27 10:57:16 +09004400 synchronized (mVpns) {
4401 // Tear down existing lockdown if profile was removed
4402 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4403 if (mLockdownEnabled) {
4404 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4405 if (profileTag == null) {
4406 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4407 return false;
4408 }
4409 String profileName = new String(profileTag);
4410 final VpnProfile profile = VpnProfile.decode(
4411 profileName, mKeyStore.get(Credentials.VPN + profileName));
4412 if (profile == null) {
4413 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4414 setLockdownTracker(null);
4415 return true;
4416 }
4417 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004418 Vpn vpn = mVpns.get(user);
4419 if (vpn == null) {
4420 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4421 return false;
4422 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004423 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004424 } else {
4425 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004426 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004427 }
4428
4429 return true;
4430 }
4431
4432 /**
4433 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4434 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4435 */
Hugo Benichi69744342017-11-27 10:57:16 +09004436 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004437 private void setLockdownTracker(LockdownVpnTracker tracker) {
4438 // Shutdown any existing tracker
4439 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004440 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4441 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004442 mLockdownTracker = null;
4443 if (existing != null) {
4444 existing.shutdown();
4445 }
4446
Robin Leec3736bc2017-03-10 16:19:54 +00004447 if (tracker != null) {
4448 mLockdownTracker = tracker;
4449 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004450 }
4451 }
4452
Hugo Benichi69744342017-11-27 10:57:16 +09004453 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004454 private void throwIfLockdownEnabled() {
4455 if (mLockdownEnabled) {
4456 throw new IllegalStateException("Unavailable in lockdown mode");
4457 }
4458 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004459
Robin Lee244ce8e2016-01-05 18:03:46 +00004460 /**
Robin Lee17e61832016-05-09 13:46:28 +01004461 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4462 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004463 *
Robin Lee17e61832016-05-09 13:46:28 +01004464 * @return {@code true} if the service was started, the service was already connected, or there
4465 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004466 */
Robin Lee17e61832016-05-09 13:46:28 +01004467 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004468 synchronized (mVpns) {
4469 Vpn vpn = mVpns.get(userId);
4470 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004471 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004472 // exists already.
4473 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4474 return false;
4475 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004476
Robin Lee812800c2016-05-13 15:38:08 +01004477 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004478 }
4479 }
4480
4481 @Override
Charles He36738632017-05-15 17:07:18 +01004482 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4483 enforceSettingsPermission();
4484 enforceCrossUserPermission(userId);
4485
4486 synchronized (mVpns) {
4487 Vpn vpn = mVpns.get(userId);
4488 if (vpn == null) {
4489 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4490 return false;
4491 }
4492 return vpn.isAlwaysOnPackageSupported(packageName);
4493 }
4494 }
4495
4496 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004497 public boolean setAlwaysOnVpnPackage(
4498 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4499 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004500 enforceCrossUserPermission(userId);
4501
Robin Lee244ce8e2016-01-05 18:03:46 +00004502 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004503 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4504 if (LockdownVpnTracker.isEnabled()) {
4505 return false;
4506 }
4507
Robin Lee244ce8e2016-01-05 18:03:46 +00004508 Vpn vpn = mVpns.get(userId);
4509 if (vpn == null) {
4510 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4511 return false;
4512 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004513 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004514 return false;
4515 }
Robin Lee17e61832016-05-09 13:46:28 +01004516 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004517 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004518 return false;
4519 }
4520 }
4521 return true;
4522 }
4523
4524 @Override
4525 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004526 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004527 enforceCrossUserPermission(userId);
4528
4529 synchronized (mVpns) {
4530 Vpn vpn = mVpns.get(userId);
4531 if (vpn == null) {
4532 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4533 return null;
4534 }
4535 return vpn.getAlwaysOnPackage();
4536 }
4537 }
4538
Wink Savilleab9321d2013-06-29 21:10:57 -07004539 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004540 public boolean isVpnLockdownEnabled(int userId) {
4541 enforceControlAlwaysOnVpnPermission();
4542 enforceCrossUserPermission(userId);
4543
4544 synchronized (mVpns) {
4545 Vpn vpn = mVpns.get(userId);
4546 if (vpn == null) {
4547 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4548 return false;
4549 }
4550 return vpn.getLockdown();
4551 }
4552 }
4553
4554 @Override
4555 public List<String> getVpnLockdownWhitelist(int userId) {
4556 enforceControlAlwaysOnVpnPermission();
4557 enforceCrossUserPermission(userId);
4558
4559 synchronized (mVpns) {
4560 Vpn vpn = mVpns.get(userId);
4561 if (vpn == null) {
4562 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4563 return null;
4564 }
4565 return vpn.getLockdownWhitelist();
4566 }
4567 }
4568
4569 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004570 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004571 // TODO: Remove? Any reason to trigger a provisioning check?
4572 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004573 }
4574
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004575 /** Location to an updatable file listing carrier provisioning urls.
4576 * An example:
4577 *
4578 * <?xml version="1.0" encoding="utf-8"?>
4579 * <provisioningUrls>
4580 * <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 -07004581 * </provisioningUrls>
4582 */
4583 private static final String PROVISIONING_URL_PATH =
4584 "/data/misc/radio/provisioning_urls.xml";
4585 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004586
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004587 /** XML tag for root element. */
4588 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4589 /** XML tag for individual url */
4590 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004591 /** XML attribute for mcc */
4592 private static final String ATTR_MCC = "mcc";
4593 /** XML attribute for mnc */
4594 private static final String ATTR_MNC = "mnc";
4595
Paul Jensen434dde82015-06-11 09:43:30 -04004596 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004597 FileReader fileReader = null;
4598 XmlPullParser parser = null;
4599 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004600
4601 try {
4602 fileReader = new FileReader(mProvisioningUrlFile);
4603 parser = Xml.newPullParser();
4604 parser.setInput(fileReader);
4605 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4606
4607 while (true) {
4608 XmlUtils.nextElement(parser);
4609
4610 String element = parser.getName();
4611 if (element == null) break;
4612
Paul Jensen434dde82015-06-11 09:43:30 -04004613 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004614 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4615 try {
4616 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4617 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4618 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4619 parser.next();
4620 if (parser.getEventType() == XmlPullParser.TEXT) {
4621 return parser.getText();
4622 }
4623 }
4624 }
4625 } catch (NumberFormatException e) {
4626 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4627 }
4628 }
4629 }
4630 return null;
4631 } catch (FileNotFoundException e) {
4632 loge("Carrier Provisioning Urls file not found");
4633 } catch (XmlPullParserException e) {
4634 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4635 } catch (IOException e) {
4636 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4637 } finally {
4638 if (fileReader != null) {
4639 try {
4640 fileReader.close();
4641 } catch (IOException e) {}
4642 }
4643 }
4644 return null;
4645 }
4646
Wink Saville42d4f082013-07-20 20:31:59 -07004647 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004648 public String getMobileProvisioningUrl() {
4649 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004650 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004651 if (TextUtils.isEmpty(url)) {
4652 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004653 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004654 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004655 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004656 }
Wink Saville8cf35602013-07-10 23:00:07 -07004657 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004658 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004659 String phoneNumber = mTelephonyManager.getLine1Number();
4660 if (TextUtils.isEmpty(phoneNumber)) {
4661 phoneNumber = "0000000000";
4662 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004663 url = String.format(url,
4664 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4665 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004666 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004667 }
4668
Wink Savilleab9321d2013-06-29 21:10:57 -07004669 return url;
4670 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004671
Wink Saville948282b2013-08-29 08:55:16 -07004672 @Override
4673 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004674 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004675 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004676 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4677 return;
4678 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004679 final long ident = Binder.clearCallingIdentity();
4680 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004681 // Concatenate the range of types onto the range of NetIDs.
4682 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4683 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004684 } finally {
4685 Binder.restoreCallingIdentity(ident);
4686 }
Wink Saville948282b2013-08-29 08:55:16 -07004687 }
Wink Saville7788c612013-08-29 14:57:08 -07004688
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004689 @Override
4690 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004691 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004692 final long ident = Binder.clearCallingIdentity();
4693 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004694 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004695 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004696 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4697 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004698 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004699 } finally {
4700 Binder.restoreCallingIdentity(ident);
4701 }
4702 }
4703
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004704 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004705 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004706 Vpn userVpn = mVpns.get(userId);
4707 if (userVpn != null) {
4708 loge("Starting user already has a VPN");
4709 return;
4710 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004711 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004712 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004713 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4714 updateLockdownVpn();
4715 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004716 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004717 }
4718
4719 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004720 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004721 Vpn userVpn = mVpns.get(userId);
4722 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004723 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004724 return;
4725 }
Robin Lee17e61832016-05-09 13:46:28 +01004726 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004727 mVpns.delete(userId);
4728 }
4729 }
4730
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004731 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004732 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004733 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004734 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004735 final int vpnsSize = mVpns.size();
4736 for (int i = 0; i < vpnsSize; i++) {
4737 Vpn vpn = mVpns.valueAt(i);
4738 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004739 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4740 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004741 }
4742 }
4743 }
4744
4745 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004746 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004747 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004748 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004749 final int vpnsSize = mVpns.size();
4750 for (int i = 0; i < vpnsSize; i++) {
4751 Vpn vpn = mVpns.valueAt(i);
4752 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004753 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4754 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004755 }
4756 }
4757 }
4758
junyulai2454b692018-11-01 17:16:31 +08004759 private void onPackageAdded(String packageName, int uid) {
4760 if (TextUtils.isEmpty(packageName) || uid < 0) {
4761 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4762 return;
4763 }
4764 mPermissionMonitor.onPackageAdded(packageName, uid);
4765 }
4766
junyulaiefb04d32018-11-12 22:39:30 +08004767 private void onPackageReplaced(String packageName, int uid) {
4768 if (TextUtils.isEmpty(packageName) || uid < 0) {
4769 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4770 return;
4771 }
4772 final int userId = UserHandle.getUserId(uid);
4773 synchronized (mVpns) {
4774 final Vpn vpn = mVpns.get(userId);
4775 if (vpn == null) {
4776 return;
4777 }
4778 // Legacy always-on VPN won't be affected since the package name is not set.
4779 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4780 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4781 + userId);
4782 vpn.startAlwaysOnVpn();
4783 }
4784 }
4785 }
4786
4787 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004788 if (TextUtils.isEmpty(packageName) || uid < 0) {
4789 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4790 return;
4791 }
4792 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004793
4794 final int userId = UserHandle.getUserId(uid);
4795 synchronized (mVpns) {
4796 final Vpn vpn = mVpns.get(userId);
4797 if (vpn == null) {
4798 return;
4799 }
4800 // Legacy always-on VPN won't be affected since the package name is not set.
4801 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4802 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4803 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004804 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004805 }
4806 }
junyulai2454b692018-11-01 17:16:31 +08004807 }
4808
Robin Lee89e7a692016-02-29 14:38:17 +00004809 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004810 synchronized (mVpns) {
4811 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4812 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4813 updateLockdownVpn();
4814 } else {
4815 startAlwaysOnVpn(userId);
4816 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004817 }
4818 }
4819
junyulai2454b692018-11-01 17:16:31 +08004820 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004821 @Override
4822 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004823 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004824 final String action = intent.getAction();
4825 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004826 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4827 final Uri packageData = intent.getData();
4828 final String packageName =
4829 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004830 if (userId == UserHandle.USER_NULL) return;
4831
Robin Lee323f29d2016-05-04 16:38:06 +01004832 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004833 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004834 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004835 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004836 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4837 onUserAdded(userId);
4838 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4839 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004840 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4841 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004842 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4843 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004844 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4845 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004846 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004847 final boolean isReplacing = intent.getBooleanExtra(
4848 Intent.EXTRA_REPLACING, false);
4849 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004850 }
4851 }
4852 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004853
Robin Lee95204e02017-01-27 11:59:22 +00004854 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4855 @Override
4856 public void onReceive(Context context, Intent intent) {
4857 // Try creating lockdown tracker, since user present usually means
4858 // unlocked keystore.
4859 updateLockdownVpn();
4860 mContext.unregisterReceiver(this);
4861 }
4862 };
4863
Chalard Jean4133a122018-06-04 13:33:12 +09004864 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4865 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004866
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004867 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4868 // Map from UID to number of NetworkRequests that UID has filed.
4869 @GuardedBy("mUidToNetworkRequestCount")
4870 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4871
Robert Greenwalta67be032014-05-16 15:49:14 -07004872 private static class NetworkFactoryInfo {
4873 public final String name;
4874 public final Messenger messenger;
4875 public final AsyncChannel asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004876 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004877
Chalard Jean05ab6812018-05-02 21:14:54 +09004878 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4879 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004880 this.name = name;
4881 this.messenger = messenger;
4882 this.asyncChannel = asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004883 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004884 }
4885 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004886
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004887 private void ensureNetworkRequestHasType(NetworkRequest request) {
4888 if (request.type == NetworkRequest.Type.NONE) {
4889 throw new IllegalArgumentException(
4890 "All NetworkRequests in ConnectivityService must have a type");
4891 }
4892 }
4893
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004894 /**
4895 * Tracks info about the requester.
4896 * Also used to notice when the calling process dies so we can self-expire
4897 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004898 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004899 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004900 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004901 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004902 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004903 final int mPid;
4904 final int mUid;
4905 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004906
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004907 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004908 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004909 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004910 mPendingIntent = pi;
4911 messenger = null;
4912 mBinder = null;
4913 mPid = getCallingPid();
4914 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004915 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004916 }
4917
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004918 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004919 super();
4920 messenger = m;
4921 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004922 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004923 mBinder = binder;
4924 mPid = getCallingPid();
4925 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004926 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004927 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004928
4929 try {
4930 mBinder.linkToDeath(this, 0);
4931 } catch (RemoteException e) {
4932 binderDied();
4933 }
4934 }
4935
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004936 private void enforceRequestCountLimit() {
4937 synchronized (mUidToNetworkRequestCount) {
4938 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4939 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004940 throw new ServiceSpecificException(
4941 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004942 }
4943 mUidToNetworkRequestCount.put(mUid, networkRequests);
4944 }
4945 }
4946
Robert Greenwalt9258c642014-03-26 16:47:06 -07004947 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004948 if (mBinder != null) {
4949 mBinder.unlinkToDeath(this, 0);
4950 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004951 }
4952
4953 public void binderDied() {
4954 log("ConnectivityService NetworkRequestInfo binderDied(" +
4955 request + ", " + mBinder + ")");
4956 releaseNetworkRequest(request);
4957 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004958
4959 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004960 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004961 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004962 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004963 }
4964
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004965 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4966 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4967 if (badCapability != null) {
4968 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004969 }
4970 }
4971
Chalard Jeanb03a6222018-04-11 21:09:10 +09004972 // This checks that the passed capabilities either do not request a specific SSID, or the
4973 // calling app has permission to do so.
4974 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4975 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004976 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004977 throw new SecurityException("Insufficient permissions to request a specific SSID");
4978 }
4979 }
4980
Erik Kline9d598e12015-07-13 16:37:51 +09004981 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004982 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004983 synchronized (nai) {
4984 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4985 if (nri.request.networkCapabilities.hasSignalStrength() &&
4986 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4987 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4988 }
4989 }
4990 }
Chalard Jean4133a122018-06-04 13:33:12 +09004991 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004992 }
4993
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004994 private void updateSignalStrengthThresholds(
4995 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4996 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004997 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004998 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4999
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005000 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005001 String detail;
5002 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5003 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5004 } else {
5005 detail = reason;
5006 }
5007 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5008 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
5009 }
5010
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005011 nai.asyncChannel.sendMessage(
5012 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09005013 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005014 }
5015
Etan Cohen859748f2017-04-03 17:42:34 -07005016 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5017 if (nc == null) {
5018 return;
5019 }
5020 NetworkSpecifier ns = nc.getNetworkSpecifier();
5021 if (ns == null) {
5022 return;
5023 }
5024 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5025 ns.assertValidFromUid(Binder.getCallingUid());
5026 }
5027
Robert Greenwalt9258c642014-03-26 16:47:06 -07005028 @Override
5029 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005030 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005031 final NetworkRequest.Type type = (networkCapabilities == null)
5032 ? NetworkRequest.Type.TRACK_DEFAULT
5033 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005034 // If the requested networkCapabilities is null, take them instead from
5035 // the default network request. This allows callers to keep track of
5036 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005037 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005038 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005039 enforceAccessPermission();
5040 } else {
5041 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5042 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005043 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5044 // of the app when the request is filed, but we never change the request if the app
5045 // changes network state. http://b/29964605
5046 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005047 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005048 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005049 ensureSufficientPermissionsForRequest(networkCapabilities,
5050 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005051 // Set the UID range for this request to the single UID of the requester, or to an empty
5052 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005053 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5054 // are no visible methods to set the UIDs, an app could use reflection to try and get
5055 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005056 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005057
Etan Cohenba07c8c2017-02-05 10:42:27 -08005058 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005059 throw new IllegalArgumentException("Bad timeout specified");
5060 }
Etan Cohen859748f2017-04-03 17:42:34 -07005061 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005062
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005063 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005064 nextNetworkRequestId(), type);
5065 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005066 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005067
5068 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005069 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005070 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005071 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005072 }
5073 return networkRequest;
5074 }
5075
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005076 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005077 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005078 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005079 } else {
5080 enforceChangePermission();
5081 }
5082 }
5083
fenglub15e72b2015-03-20 11:29:56 -07005084 @Override
fengludb571472015-04-21 17:12:05 -07005085 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005086 enforceAccessPermission();
5087 NetworkAgentInfo nai = null;
5088 if (network == null) {
5089 return false;
5090 }
5091 synchronized (mNetworkForNetId) {
5092 nai = mNetworkForNetId.get(network.netId);
5093 }
5094 if (nai != null) {
5095 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005096 synchronized (mBandwidthRequests) {
5097 final int uid = Binder.getCallingUid();
5098 Integer uidReqs = mBandwidthRequests.get(uid);
5099 if (uidReqs == null) {
5100 uidReqs = new Integer(0);
5101 }
5102 mBandwidthRequests.put(uid, ++uidReqs);
5103 }
fenglub15e72b2015-03-20 11:29:56 -07005104 return true;
5105 }
5106 return false;
5107 }
5108
Felipe Lemeee27cab2016-06-20 16:36:29 -07005109 private boolean isSystem(int uid) {
5110 return uid < Process.FIRST_APPLICATION_UID;
5111 }
fenglub15e72b2015-03-20 11:29:56 -07005112
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005113 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005114 final int uid = Binder.getCallingUid();
5115 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005116 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005117 return;
5118 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005119 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5120 // Policy already enforced.
5121 return;
5122 }
5123 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5124 // If UID is restricted, don't allow them to bring up metered APNs.
5125 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005126 }
5127 }
5128
Robert Greenwalt9258c642014-03-26 16:47:06 -07005129 @Override
5130 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5131 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005132 checkNotNull(operation, "PendingIntent cannot be null.");
5133 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5134 enforceNetworkRequestPermissions(networkCapabilities);
5135 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005136 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005137 ensureSufficientPermissionsForRequest(networkCapabilities,
5138 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005139 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005140 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005141
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005142 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005143 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5144 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005145 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005146 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5147 nri));
5148 return networkRequest;
5149 }
5150
Jeremy Joslin79294842014-12-03 17:15:28 -08005151 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5152 mHandler.sendMessageDelayed(
5153 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5154 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5155 }
5156
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005157 @Override
5158 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005159 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005160 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5161 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005162 }
5163
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005164 // In order to implement the compatibility measure for pre-M apps that call
5165 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5166 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5167 // This ensures it has permission to do so.
5168 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5169 if (nc == null) {
5170 return false;
5171 }
5172 int[] transportTypes = nc.getTransportTypes();
5173 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5174 return false;
5175 }
5176 try {
5177 mContext.enforceCallingOrSelfPermission(
5178 android.Manifest.permission.ACCESS_WIFI_STATE,
5179 "ConnectivityService");
5180 } catch (SecurityException e) {
5181 return false;
5182 }
5183 return true;
5184 }
5185
Robert Greenwalt9258c642014-03-26 16:47:06 -07005186 @Override
5187 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5188 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005189 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5190 enforceAccessPermission();
5191 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005192
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005193 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005194 ensureSufficientPermissionsForRequest(networkCapabilities,
5195 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005196 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005197 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5198 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5199 // onLost and onAvailable callbacks when networks move in and out of the background.
5200 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5201 // can't request networks.
5202 restrictBackgroundRequestForCaller(nc);
5203 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005204
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005205 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005206 NetworkRequest.Type.LISTEN);
5207 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005208 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005209
5210 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5211 return networkRequest;
5212 }
5213
5214 @Override
5215 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5216 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005217 checkNotNull(operation, "PendingIntent cannot be null.");
5218 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5219 enforceAccessPermission();
5220 }
Etan Cohen859748f2017-04-03 17:42:34 -07005221 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005222 ensureSufficientPermissionsForRequest(networkCapabilities,
5223 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005224
Chalard Jeandda156a2018-01-10 21:19:32 +09005225 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005226 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005227
5228 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005229 NetworkRequest.Type.LISTEN);
5230 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005231 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005232
5233 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005234 }
5235
Erik Klineacdd6392016-07-07 16:50:58 +09005236 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005237 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005238 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005239 mHandler.sendMessage(mHandler.obtainMessage(
5240 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005241 }
5242
5243 @Override
Chalard Jean05ab6812018-05-02 21:14:54 +09005244 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005245 enforceConnectivityInternalPermission();
Chalard Jean05ab6812018-05-02 21:14:54 +09005246 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5247 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005248 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean05ab6812018-05-02 21:14:54 +09005249 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005250 }
5251
Robert Greenwalta67be032014-05-16 15:49:14 -07005252 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005253 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005254 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5255 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5256 }
5257
5258 @Override
5259 public void unregisterNetworkFactory(Messenger messenger) {
5260 enforceConnectivityInternalPermission();
5261 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5262 }
5263
5264 private void handleUnregisterNetworkFactory(Messenger messenger) {
5265 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5266 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005267 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005268 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005269 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005270 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005271 }
5272
Robert Greenwalt7b816022014-04-18 15:25:25 -07005273 /**
5274 * NetworkAgentInfo supporting a request by requestId.
5275 * These have already been vetted (their Capabilities satisfy the request)
5276 * and the are the highest scored network available.
5277 * the are keyed off the Requests requestId.
5278 */
Hugo Benichicd952782017-09-20 11:20:14 +09005279 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5280 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005281 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005282
Paul Jensen31a94f42015-02-13 14:18:39 -05005283 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5284 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005285 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005286 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5287 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5288 // there may not be a strict 1:1 correlation between the two.
5289 @GuardedBy("mNetworkForNetId")
5290 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005291
Robert Greenwalt7b816022014-04-18 15:25:25 -07005292 // NetworkAgentInfo keyed off its connecting messenger
5293 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005294 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005295 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005296
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005297 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005298 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005299
Paul Jensen2c311d62014-11-17 12:34:51 -05005300 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005301 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005302
Erik Klineda4bfa82015-04-30 12:58:40 +09005303 // Request used to optionally keep mobile data active even when higher
5304 // priority networks like Wi-Fi are active.
5305 private final NetworkRequest mDefaultMobileDataRequest;
5306
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005307 // Request used to optionally keep wifi data active even when higher
5308 // priority networks like ethernet are active.
5309 private final NetworkRequest mDefaultWifiRequest;
5310
Hugo Benichicd952782017-09-20 11:20:14 +09005311 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5312 synchronized (mNetworkForRequestId) {
5313 return mNetworkForRequestId.get(requestId);
5314 }
5315 }
5316
5317 private void clearNetworkForRequest(int requestId) {
5318 synchronized (mNetworkForRequestId) {
5319 mNetworkForRequestId.remove(requestId);
5320 }
5321 }
5322
5323 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5324 synchronized (mNetworkForRequestId) {
5325 mNetworkForRequestId.put(requestId, nai);
5326 }
5327 }
5328
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005329 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005330 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005331 }
5332
Varun Anand4fa80e82019-02-06 10:13:38 -08005333 @Nullable
5334 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5335 return nai != null ? nai.network : null;
5336 }
5337
5338 private void ensureRunningOnConnectivityServiceThread() {
5339 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5340 throw new IllegalStateException(
5341 "Not running on ConnectivityService thread: "
5342 + Thread.currentThread().getName());
5343 }
5344 }
5345
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005346 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005347 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005348 }
5349
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005350 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5351 return nri.request.requestId == mDefaultRequest.requestId;
5352 }
5353
Chalard Jean05ab6812018-05-02 21:14:54 +09005354 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5355 // changes that would conflict throughout the automerger graph. Having this method temporarily
5356 // helps with the process of going through with all these dependent changes across the entire
5357 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005358 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005359 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005360 int currentScore, NetworkMisc networkMisc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005361 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5362 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5363 }
5364
5365 /**
5366 * Register a new agent with ConnectivityService to handle a network.
5367 *
5368 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5369 * @param networkInfo the initial info associated with this network. It can be updated later :
5370 * see {@link #updateNetworkInfo}.
5371 * @param linkProperties the initial link properties of this network. They can be updated
5372 * later : see {@link #updateLinkProperties}.
5373 * @param networkCapabilities the initial capabilites of this network. They can be updated
5374 * later : see {@link #updateNetworkCapabilities}.
5375 * @param currentScore the initial score of the network. See
5376 * {@link NetworkAgentInfo#getCurrentScore}.
5377 * @param networkMisc metadata about the network. This is never updated.
5378 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5379 */
5380 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5381 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5382 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005383 enforceConnectivityInternalPermission();
5384
Rubin Xu1bb5c082017-09-05 18:40:49 +01005385 LinkProperties lp = new LinkProperties(linkProperties);
5386 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005387 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5388 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005389 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005390 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005391 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Luke Huang65914772019-03-16 00:31:46 +08005392 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mDnsResolver,
5393 mNMS, factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005394 // Make sure the network capabilities reflect what the agent info says.
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005395 nai.setNetworkCapabilities(mixInCapabilities(nai, nc));
Chalard Jeand771aa02018-04-26 16:16:10 +09005396 final String extraInfo = networkInfo.getExtraInfo();
5397 final String name = TextUtils.isEmpty(extraInfo)
5398 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005399 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005400 final long token = Binder.clearCallingIdentity();
5401 try {
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005402 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005403 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005404 } finally {
5405 Binder.restoreCallingIdentity(token);
5406 }
5407 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5408 // If the network disconnects or sends any other event before that, messages are deferred by
5409 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5410 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005411 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005412 }
5413
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005414 @VisibleForTesting
5415 protected NetworkStackClient getNetworkStack() {
5416 return NetworkStackClient.getInstance();
5417 }
5418
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005419 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5420 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005421 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005422 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005423 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005424 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005425 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005426 synchronized (this) {
5427 if (mSystemReady) {
5428 try {
5429 networkMonitor.notifySystemReady();
5430 } catch (RemoteException e) {
5431 e.rethrowFromSystemServer();
5432 }
5433 }
5434 }
5435
5436 try {
5437 networkMonitor.start();
5438 } catch (RemoteException e) {
5439 e.rethrowFromSystemServer();
5440 }
Erik Klinee5dac902018-03-04 21:01:01 +09005441 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5442 NetworkInfo networkInfo = nai.networkInfo;
5443 nai.networkInfo = null;
5444 updateNetworkInfo(nai, networkInfo);
5445 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005446 }
5447
lucaslin25a4ec32018-11-28 12:51:55 +08005448 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5449 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005450 int netId = networkAgent.network.netId;
5451
Lorenzo Colittidf595632019-01-08 14:43:37 +09005452 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5453 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5454 // are accurate.
5455 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005456
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005457 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005458 updateMtu(newLp, oldLp);
5459 // TODO - figure out what to do for clat
5460// for (LinkProperties lp : newLp.getStackedLinks()) {
5461// updateMtu(lp, null);
5462// }
lucaslin041a1af2018-11-28 19:27:52 +08005463 if (isDefaultNetwork(networkAgent)) {
5464 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5465 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005466
Erik Kline94887872016-04-05 13:30:49 +09005467 updateRoutes(newLp, oldLp, netId);
5468 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005469 // Make sure LinkProperties represents the latest private DNS status.
5470 // This does not need to be done before updateDnses because the
5471 // LinkProperties are not the source of the private DNS configuration.
5472 // updateDnses will fetch the private DNS configuration from DnsManager.
5473 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005474
Paul Jensene0bef712014-12-10 15:12:18 -05005475 if (isDefaultNetwork(networkAgent)) {
5476 handleApplyDefaultProxy(newLp.getHttpProxy());
5477 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005478 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005479 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005480 // TODO - move this check to cover the whole function
5481 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005482 synchronized (networkAgent) {
5483 networkAgent.linkProperties = newLp;
5484 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005485 // Start or stop DNS64 detection and 464xlat according to network state.
5486 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005487 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005488 try {
5489 networkAgent.networkMonitor().notifyLinkPropertiesChanged(newLp);
5490 } catch (RemoteException e) {
5491 e.rethrowFromSystemServer();
5492 }
lucaslin25a4ec32018-11-28 12:51:55 +08005493 if (networkAgent.everConnected) {
5494 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5495 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005496 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005497
5498 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005499 }
5500
Joel Scherpelz668370b2017-06-08 15:35:21 +09005501 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005502 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005503 // marks on unsupported interfaces is harmless.
5504 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5505 return;
5506 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005507
Joel Scherpelz668370b2017-06-08 15:35:21 +09005508 int mark = mContext.getResources().getInteger(
5509 com.android.internal.R.integer.config_networkWakeupPacketMark);
5510 int mask = mContext.getResources().getInteger(
5511 com.android.internal.R.integer.config_networkWakeupPacketMask);
5512
5513 // Mask/mark of zero will not detect anything interesting.
5514 // Don't install rules unless both values are nonzero.
5515 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005516 return;
5517 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005518
5519 final String prefix = "iface:" + iface;
5520 try {
5521 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005522 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005523 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005524 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005525 }
5526 } catch (Exception e) {
5527 loge("Exception modifying wakeup packet monitoring: " + e);
5528 }
5529
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005530 }
5531
5532 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5533 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005534 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005535 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5536 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005537 for (String iface : interfaceDiff.added) {
5538 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005539 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005540 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005541 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005542 } catch (Exception e) {
5543 loge("Exception adding interface: " + e);
5544 }
5545 }
5546 for (String iface : interfaceDiff.removed) {
5547 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005548 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005549 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005550 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005551 } catch (Exception e) {
5552 loge("Exception removing interface: " + e);
5553 }
5554 }
5555 }
5556
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005557 /**
5558 * Have netd update routes from oldLp to newLp.
5559 * @return true if routes changed between oldLp and newLp
5560 */
5561 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005562 // Compare the route diff to determine which routes should be added and removed.
5563 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5564 oldLp != null ? oldLp.getAllRoutes() : null,
5565 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005566
5567 // add routes before removing old in case it helps with continuous connectivity
5568
Chalard Jean4d660112018-06-04 16:52:49 +09005569 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005570 for (RouteInfo route : routeDiff.added) {
5571 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005572 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005573 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005574 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005575 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005576 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5577 loge("Exception in addRoute for non-gateway: " + e);
5578 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005579 }
5580 }
5581 for (RouteInfo route : routeDiff.added) {
5582 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005583 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005584 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005585 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005586 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005587 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5588 loge("Exception in addRoute for gateway: " + e);
5589 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005590 }
5591 }
5592
5593 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005594 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005595 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005596 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005597 } catch (Exception e) {
5598 loge("Exception in removeRoute: " + e);
5599 }
5600 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005601 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005602 }
Erik Kline41368502015-06-17 13:19:54 +09005603
Erik Kline94887872016-04-05 13:30:49 +09005604 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5605 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5606 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005607 }
Erik Kline94887872016-04-05 13:30:49 +09005608
Erik Kline1742fe12017-12-13 19:40:49 +09005609 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5610 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5611
Erik Klinea24d4592018-01-11 21:07:29 +09005612 if (DBG) {
5613 final Collection<InetAddress> dnses = newLp.getDnsServers();
5614 log("Setting DNS servers for network " + netId + " to " + dnses);
5615 }
Erik Kline94887872016-04-05 13:30:49 +09005616 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005617 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005618 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005619 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005620 }
Erik Kline4edba012017-04-07 15:29:29 +09005621 }
5622
Luke Huang8a462ec2018-08-24 20:33:16 +08005623 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005624 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005625 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005626 }
5627 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005628 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005629 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005630 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005631 }
5632
Paul Jensen3d194ea2015-06-16 14:27:36 -04005633 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005634 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5635 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5636 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005637 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005638 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005639 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005640 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5641 // causing a connect/teardown loop.
5642 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5643 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005644 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005645 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005646 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5647 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005648 // does not cause any request (that is not a listen) currently matching that agent to
5649 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005650 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005651 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005652 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005653 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005654 }
5655
Paul Jensen3d194ea2015-06-16 14:27:36 -04005656 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005657 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005658 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005659 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005660 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005661 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005662 }
Paul Jensene0988542015-06-25 15:30:08 -04005663 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005664 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005665 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005666 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005667 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005668 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005669 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005670 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005671 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005672 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005673 if (nai.isSuspended()) {
5674 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5675 } else {
5676 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5677 }
lucasline252a742019-03-12 13:08:03 +08005678 if (nai.partialConnectivity) {
5679 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5680 } else {
5681 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5682 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005683
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005684 return newNc;
5685 }
5686
5687 /**
5688 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5689 *
5690 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5691 * capabilities we manage and store in {@code nai}, such as validated status and captive
5692 * portal status)
5693 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5694 * potentially triggers rematches.
5695 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5696 * change.)
5697 *
5698 * @param oldScore score of the network before any of the changes that prompted us
5699 * to call this function.
5700 * @param nai the network having its capabilities updated.
5701 * @param nc the new network capabilities.
5702 */
5703 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5704 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5705
5706 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005707
Luke Huang8a462ec2018-08-24 20:33:16 +08005708 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5709 final int newPermission = getNetworkPermission(newNc);
5710 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005711 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005712 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005713 } catch (RemoteException e) {
5714 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005715 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005716 }
5717
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005718 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005719 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005720 prevNc = nai.networkCapabilities;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005721 nai.setNetworkCapabilities(newNc);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005722 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005723
Chalard Jeanf213ca12018-01-16 18:43:05 +09005724 updateUids(nai, prevNc, newNc);
5725
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005726 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005727 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5728 // the change we're processing can't affect any requests, it can only affect the listens
5729 // on this network. We might have been called by rematchNetworkAndRequests when a
5730 // network changed foreground state.
5731 processListenRequests(nai, true);
5732 } else {
5733 // If the requestable capabilities have changed or the score changed, we can't have been
5734 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005735 rematchAllNetworksAndRequests(nai, oldScore);
5736 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005737 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005738
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005739 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005740 final boolean oldMetered = prevNc.isMetered();
5741 final boolean newMetered = newNc.isMetered();
5742 final boolean meteredChanged = oldMetered != newMetered;
5743
5744 if (meteredChanged) {
5745 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5746 mRestrictBackground);
5747 }
5748
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005749 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005750 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005751
5752 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005753 if (meteredChanged || roamingChanged) {
5754 notifyIfacesChangedForNetworkStats();
5755 }
5756 }
5757
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005758 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005759 // Tell VPNs about updated capabilities, since they may need to
5760 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005761 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005762 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005763 }
5764
Chalard Jeanf213ca12018-01-16 18:43:05 +09005765 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5766 NetworkCapabilities newNc) {
5767 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5768 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5769 if (null == prevRanges) prevRanges = new ArraySet<>();
5770 if (null == newRanges) newRanges = new ArraySet<>();
5771 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5772
5773 prevRanges.removeAll(newRanges);
5774 newRanges.removeAll(prevRangesCopy);
5775
5776 try {
5777 if (!newRanges.isEmpty()) {
5778 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5779 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005780 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005781 }
5782 if (!prevRanges.isEmpty()) {
5783 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5784 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005785 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005786 }
5787 } catch (Exception e) {
5788 // Never crash!
5789 loge("Exception in updateUids: " + e);
5790 }
5791 }
5792
Hugo Benichief502882017-09-01 01:23:32 +00005793 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005794 ensureRunningOnConnectivityServiceThread();
5795
Erik Kline736353a2018-03-21 07:18:33 -07005796 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005797 // Ignore updates for disconnected networks
5798 return;
5799 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005800 // newLp is already a defensive copy.
5801 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005802 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005803 log("Update of LinkProperties for " + nai.name() +
5804 "; created=" + nai.created +
5805 "; everConnected=" + nai.everConnected);
5806 }
lucaslin25a4ec32018-11-28 12:51:55 +08005807 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005808 }
5809
Paul Jensenc8b9a742014-09-30 15:37:41 -04005810 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005811 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5812 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005813 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005814 if (nr.isListen()) continue;
Chalard Jean05ab6812018-05-02 21:14:54 +09005815 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005816 }
5817 }
5818
Chalard Jean05ab6812018-05-02 21:14:54 +09005819 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5820 int score = 0;
5821 int serial = 0;
5822 if (nai != null) {
5823 score = nai.getCurrentScore();
5824 serial = nai.factorySerialNumber;
5825 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005826 if (VDBG || DDBG){
5827 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5828 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005829 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005830 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5831 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005832 }
5833 }
5834
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005835 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5836 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005837 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005838 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005839 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5840 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005841 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005842 sendIntent(nri.mPendingIntent, intent);
5843 }
5844 // else not handled
5845 }
5846
5847 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5848 mPendingIntentWakeLock.acquire();
5849 try {
5850 if (DBG) log("Sending " + pendingIntent);
5851 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5852 } catch (PendingIntent.CanceledException e) {
5853 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5854 mPendingIntentWakeLock.release();
5855 releasePendingNetworkRequest(pendingIntent);
5856 }
5857 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5858 }
5859
5860 @Override
5861 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5862 String resultData, Bundle resultExtras) {
5863 if (DBG) log("Finished sending " + pendingIntent);
5864 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005865 // Release with a delay so the receiving client has an opportunity to put in its
5866 // own request.
5867 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005868 }
5869
Chalard Jeanf19db372018-01-26 19:24:40 +09005870 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005871 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005872 if (nri.messenger == null) {
5873 return; // Default request has no msgr
5874 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005875 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005876 // TODO: check if defensive copies of data is needed.
5877 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005878 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005879 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5880 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005881 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005882 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005883 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005884 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5885 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005886 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005887 // For this notification, arg1 contains the blocked status.
5888 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005889 break;
5890 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005891 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005892 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005893 break;
5894 }
5895 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005896 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005897 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005898 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005899 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005900 break;
5901 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005902 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005903 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005904 break;
5905 }
junyulai05986c62018-08-07 19:50:45 +08005906 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005907 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005908 msg.arg1 = arg1;
5909 break;
5910 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005911 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005912 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005913 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005914 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005915 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005916 String notification = ConnectivityManager.getCallbackName(notificationType);
5917 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005918 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005919 nri.messenger.send(msg);
5920 } catch (RemoteException e) {
5921 // may occur naturally in the race of binder death.
5922 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5923 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005924 }
5925
Hugo Benichidba33db2017-03-23 22:40:44 +09005926 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5927 bundle.putParcelable(t.getClass().getSimpleName(), t);
5928 }
5929
Paul Jensenc8b9a742014-09-30 15:37:41 -04005930 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005931 if (nai.numRequestNetworkRequests() != 0) {
5932 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5933 NetworkRequest nr = nai.requestAt(i);
5934 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005935 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005936 loge("Dead network still had at least " + nr);
5937 break;
5938 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005939 }
5940 nai.asyncChannel.disconnect();
5941 }
5942
Robert Greenwalt7b816022014-04-18 15:25:25 -07005943 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5944 if (oldNetwork == null) {
5945 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5946 return;
5947 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005948 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005949
5950 // If we get here it means that the last linger timeout for this network expired. So there
5951 // must be no other active linger timers, and we must stop lingering.
5952 oldNetwork.clearLingerState();
5953
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005954 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005955 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005956 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005957 } else {
5958 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005959 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5960 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005961 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005962 }
5963
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005964 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005965 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005966
Paul Jensen27b02b72014-07-14 12:03:33 -04005967 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005968 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005969 } catch (Exception e) {
5970 loge("Exception setting default network :" + e);
5971 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005972
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005973 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005974 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005975 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005976 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005977 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005978 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5979 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005980 }
5981
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005982 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005983 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5984 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5985 NetworkRequest nr = nri.request;
5986 if (!nr.isListen()) continue;
5987 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5988 nai.removeRequest(nri.request.requestId);
5989 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5990 }
5991 }
5992
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005993 if (capabilitiesChanged) {
5994 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5995 }
5996
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005997 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5998 NetworkRequest nr = nri.request;
5999 if (!nr.isListen()) continue;
6000 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
6001 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006002 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006003 }
6004 }
6005 }
6006
Paul Jensen2161a8e2014-09-11 11:00:39 -04006007 // Handles a network appearing or improving its score.
6008 //
6009 // - Evaluates all current NetworkRequests that can be
6010 // satisfied by newNetwork, and reassigns to newNetwork
6011 // any such requests for which newNetwork is the best.
6012 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006013 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006014 // needed. A network is needed if it is the best network for
6015 // one or more NetworkRequests, or if it is a VPN.
6016 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006017 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006018 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006019 //
6020 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6021 // networks that have no chance (i.e. even if validated)
6022 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006023 //
6024 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6025 // it does not remove NetworkRequests that other Networks could better satisfy.
6026 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6027 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6028 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006029 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006030 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006031 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6032 // performed to tear down unvalidated networks that have no chance (i.e. even if
6033 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006034 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006035 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006036 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006037 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006038 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006039 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006040
6041 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6042 final int score = newNetwork.getCurrentScore();
6043
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006044 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006045
Paul Jensen2161a8e2014-09-11 11:00:39 -04006046 // Find and migrate to this Network any NetworkRequests for
6047 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006048 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6049 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006050 NetworkCapabilities nc = newNetwork.networkCapabilities;
6051 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006052 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006053 // Process requests in the first pass and listens in the second pass. This allows us to
6054 // change a network's capabilities depending on which requests it has. This is only
6055 // correct if the change in capabilities doesn't affect whether the network satisfies
6056 // requests or not, and doesn't affect the network's score.
6057 if (nri.request.isListen()) continue;
6058
Hugo Benichicd952782017-09-20 11:20:14 +09006059 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006060 final boolean satisfies = newNetwork.satisfies(nri.request);
6061 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006062 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006063 log("Network " + newNetwork.name() + " was already satisfying" +
6064 " request " + nri.request.requestId + ". No change.");
6065 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006066 keep = true;
6067 continue;
6068 }
6069
6070 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006071 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006072 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006073 // next check if it's better than any current network we're using for
6074 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006075 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006076 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006077 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006078 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006079 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006080 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006081 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006082 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006083 if (VDBG || DDBG){
6084 log(" accepting network in place of " + currentNetwork.name());
6085 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006086 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006087 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006088 affectedNetworks.add(currentNetwork);
6089 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006090 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006091 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006092 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006093 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006094 if (!newNetwork.addRequest(nri.request)) {
6095 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6096 }
6097 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006098 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006099 // Tell NetworkFactories about the new score, so they can stop
6100 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006101 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006102 // network. Think about if there is a way to reduce this. Push
6103 // netid->request mapping to each factory?
Chalard Jean05ab6812018-05-02 21:14:54 +09006104 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006105 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006106 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006107 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006108 if (currentNetwork != null) {
6109 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6110 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006111 }
6112 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006113 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006114 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6115 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006116 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006117 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6118 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6119 // This means this code doesn't have to handle the case where "currentNetwork" no
6120 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6121 if (DBG) {
6122 log("Network " + newNetwork.name() + " stopped satisfying" +
6123 " request " + nri.request.requestId);
6124 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006125 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006126 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006127 clearNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09006128 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006129 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006130 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6131 newNetwork.name() +
6132 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006133 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006134 // TODO: Technically, sending CALLBACK_LOST here is
6135 // incorrect if there is a replacement network currently
6136 // connected that can satisfy nri, which is a request
6137 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006138 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6139 // so this code is only incorrect for a network that loses
6140 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006141 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006142 }
6143 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006144 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006145 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006146 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006147 makeDefault(newNetwork);
6148 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006149 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006150 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006151 // Have a new default network, release the transition wakelock in
6152 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006153 }
6154
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006155 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6156 Slog.wtf(TAG, String.format(
6157 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006158 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006159 }
6160 if (newNetwork.getCurrentScore() != score) {
6161 Slog.wtf(TAG, String.format(
6162 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006163 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006164 }
6165
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006166 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006167 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6168 // If the network went from background to foreground or vice versa, we need to update
6169 // its foreground state. It is safe to do this after rematching the requests because
6170 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6171 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006172 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006173 } else {
6174 processListenRequests(newNetwork, false);
6175 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006176
Paul Jensencf4c2c62015-07-01 14:16:32 -04006177 // do this after the default net is switched, but
6178 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006179 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006180
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006181 // Linger any networks that are no longer needed. This should be done after sending the
6182 // available callback for newNetwork.
6183 for (NetworkAgentInfo nai : affectedNetworks) {
6184 updateLingerState(nai, now);
6185 }
6186 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6187 // does not need to be done in any particular order.
6188 updateLingerState(newNetwork, now);
6189
Paul Jensencf4c2c62015-07-01 14:16:32 -04006190 if (isNewDefault) {
6191 // Maintain the illusion: since the legacy API only
6192 // understands one network at a time, we must pretend
6193 // that the current default network disconnected before
6194 // the new one connected.
6195 if (oldDefaultNetwork != null) {
6196 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6197 oldDefaultNetwork, true);
6198 }
6199 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6200 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6201 notifyLockdownVpn(newNetwork);
6202 }
6203
Robert Greenwalt7b816022014-04-18 15:25:25 -07006204 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006205 // Notify battery stats service about this network, both the normal
6206 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006207 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006208 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006209 final IBatteryStats bs = BatteryStatsService.getService();
6210 final int type = newNetwork.networkInfo.getType();
6211
6212 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6213 bs.noteNetworkInterfaceType(baseIface, type);
6214 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6215 final String stackedIface = stacked.getInterfaceName();
6216 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006217 }
6218 } catch (RemoteException ignored) {
6219 }
6220
Robert Greenwalt152ed372014-12-17 17:19:53 -08006221 // This has to happen after the notifyNetworkCallbacks as that tickles each
6222 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006223 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006224 // and will generally do a dns request so they can ensureRouteToHost and if
6225 // they do that before the callbacks happen they'll use the default network.
6226 //
6227 // TODO: Is there still a race here? We send the broadcast
6228 // after sending the callback, but if the app can receive the
6229 // broadcast before the callback, it might still break.
6230 //
6231 // This *does* introduce a race where if the user uses the new api
6232 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6233 // they may get old info. Reverse this after the old startUsing api is removed.
6234 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006235 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6236 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006237 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006238 // legacy type tracker filters out repeat adds
6239 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6240 }
6241 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006242
6243 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6244 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6245 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6246 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6247 if (newNetwork.isVPN()) {
6248 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6249 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006250 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006251 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6252 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006253 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006254 if (nai.getLingerExpiry() > 0) {
6255 // This network has active linger timers and no requests, but is not
6256 // lingering. Linger it.
6257 //
6258 // One way (the only way?) this can happen if this network is unvalidated
6259 // and became unneeded due to another network improving its score to the
6260 // point where this network will no longer be able to satisfy any requests
6261 // even if it validates.
6262 updateLingerState(nai, now);
6263 } else {
6264 if (DBG) log("Reaping " + nai.name());
6265 teardownUnneededNetwork(nai);
6266 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006267 }
6268 }
6269 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006270 }
6271
Paul Jensen1c7ba022015-06-16 14:27:36 -04006272 /**
6273 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6274 * being disconnected.
6275 * @param changed If only one Network's score or capabilities have been modified since the last
6276 * time this function was called, pass this Network in this argument, otherwise pass
6277 * null.
6278 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6279 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6280 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6281 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6282 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006283 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006284 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006285 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6286 // to avoid the slowness. It is not simply enough to process just "changed", for
6287 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006288 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006289
6290 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6291 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6292 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006293 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006294 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006295 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006296 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006297 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6298 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6299 // Rematch higher scoring networks first to prevent requests first matching a lower
6300 // scoring network and then a higher scoring network, which could produce multiple
6301 // callbacks and inadvertently unlinger networks.
6302 Arrays.sort(nais);
6303 for (NetworkAgentInfo nai : nais) {
6304 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006305 // Only reap the last time through the loop. Reaping before all rematching
6306 // is complete could incorrectly teardown a network that hasn't yet been
6307 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006308 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006309 : ReapUnvalidatedNetworks.REAP,
6310 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006311 }
6312 }
6313 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006314
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006315 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006316 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006317 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006318 // For now only update icons for default connection.
6319 // TODO: Update WiFi and cellular icons separately. b/17237507
6320 if (!isDefaultNetwork(nai)) return;
6321
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006322 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006323 // Don't repeat publish.
6324 if (newInetCondition == mDefaultInetConditionPublished) return;
6325
6326 mDefaultInetConditionPublished = newInetCondition;
6327 sendInetConditionBroadcast(nai.networkInfo);
6328 }
6329
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006330 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006331 synchronized (mVpns) {
6332 if (mLockdownTracker != null) {
6333 if (nai != null && nai.isVPN()) {
6334 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6335 } else {
6336 mLockdownTracker.onNetworkInfoChanged();
6337 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006338 }
6339 }
6340 }
6341
Robert Greenwalt7b816022014-04-18 15:25:25 -07006342 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006343 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006344 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006345 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006346 synchronized (networkAgent) {
6347 oldInfo = networkAgent.networkInfo;
6348 networkAgent.networkInfo = newInfo;
6349 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006350 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006351
Robert Greenwalt7b816022014-04-18 15:25:25 -07006352 if (DBG) {
6353 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6354 (oldInfo == null ? "null" : oldInfo.getState()) +
6355 " to " + state);
6356 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006357
Robin Lee585e2482016-05-01 23:00:00 +01006358 if (!networkAgent.created
6359 && (state == NetworkInfo.State.CONNECTED
6360 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006361
6362 // A network that has just connected has zero requests and is thus a foreground network.
6363 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6364
Robert Greenwalt7b816022014-04-18 15:25:25 -07006365 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006366 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006367 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006368 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006369 (networkAgent.networkMisc == null ||
6370 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006371 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006372 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006373 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006374 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006375 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006376 loge("Error creating network " + networkAgent.network.netId + ": "
6377 + e.getMessage());
6378 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006379 }
Paul Jenseneec75412014-08-04 12:21:19 -04006380 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006381 }
6382
6383 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6384 networkAgent.everConnected = true;
6385
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006386 if (networkAgent.linkProperties == null) {
6387 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6388 }
6389
lucaslin8175ac992019-04-03 17:09:28 +08006390 // NetworkCapabilities need to be set before sending the private DNS config to
6391 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
6392 synchronized (networkAgent) {
6393 networkAgent.setNetworkCapabilities(networkAgent.networkCapabilities);
6394 }
Erik Kline736353a2018-03-21 07:18:33 -07006395 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006396 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6397 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006398
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006399 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6400 // command must be sent after updating LinkProperties to maximize chances of
6401 // NetworkMonitor seeing the correct LinkProperties when starting.
6402 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6403 try {
lucaslin43338992019-03-20 18:21:59 +08006404 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6405 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6406 }
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09006407 networkAgent.networkMonitor().notifyNetworkConnected(
6408 networkAgent.linkProperties, networkAgent.networkCapabilities);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006409 } catch (RemoteException e) {
6410 e.rethrowFromSystemServer();
6411 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006412 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006413
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006414 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6415 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6416 // capabilities, so it only needs to be done once on initial connect, not every time the
6417 // network's capabilities change. Note that we do this before rematching the network,
6418 // so we could decide to tear it down immediately afterwards. That's fine though - on
6419 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6420 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006421 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006422
Varun Anand4fa80e82019-02-06 10:13:38 -08006423 if (networkAgent.isVPN()) {
6424 updateAllVpnsCapabilities();
6425 }
6426
Paul Jensen2161a8e2014-09-11 11:00:39 -04006427 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006428 final long now = SystemClock.elapsedRealtime();
6429 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006430
6431 // This has to happen after matching the requests, because callbacks are just requests.
6432 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006433 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006434 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006435 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006436 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006437 }
Chalard Jean392971c2018-05-11 20:19:20 +09006438 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006439 if (networkAgent.isVPN()) {
6440 // As the active or bound network changes for apps, broadcast the default proxy, as
6441 // apps may need to update their proxy data. This is called after disconnecting from
6442 // VPN to make sure we do not broadcast the old proxy data.
6443 // TODO(b/122649188): send the broadcast only to VPN users.
6444 mProxyTracker.sendProxyBroadcast();
6445 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006446 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6447 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006448 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006449 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006450 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006451 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006452 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6453 networkAgent.networkCapabilities);
6454 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6455 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006456 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6457 ConnectivityManager.CALLBACK_SUSPENDED :
6458 ConnectivityManager.CALLBACK_RESUMED));
6459 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006460 }
6461 }
6462
Robert Greenwaltac96c522014-06-03 16:43:57 -07006463 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006464 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006465 if (score < 0) {
6466 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6467 "). Bumping score to min of 0");
6468 score = 0;
6469 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006470
Paul Jensen2161a8e2014-09-11 11:00:39 -04006471 final int oldScore = nai.getCurrentScore();
6472 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006473
Paul Jensen85cf78e2015-06-25 13:25:07 -04006474 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006475
Paul Jensenc8b9a742014-09-30 15:37:41 -04006476 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006477 }
6478
Erik Klinec75d4fa2017-02-15 19:59:17 +09006479 // Notify only this one new request of the current state. Transfer all the
6480 // current state by calling NetworkCapabilities and LinkProperties callbacks
6481 // so that callers can be guaranteed to have as close to atomicity in state
6482 // transfer as can be supported by this current API.
6483 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006484 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006485 if (nri.mPendingIntent != null) {
6486 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6487 // Attempt no subsequent state pushes where intents are involved.
6488 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006489 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006490
junyulai05986c62018-08-07 19:50:45 +08006491 final boolean metered = nai.networkCapabilities.isMetered();
6492 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6493 metered, mRestrictBackground);
6494 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6495 }
6496
6497 /**
6498 * Notify of the blocked state apps with a registered callback matching a given NAI.
6499 *
6500 * Unlike other callbacks, blocked status is different between each individual uid. So for
6501 * any given nai, all requests need to be considered according to the uid who filed it.
6502 *
6503 * @param nai The target NetworkAgentInfo.
6504 * @param oldMetered True if the previous network capabilities is metered.
6505 * @param newRestrictBackground True if data saver is enabled.
6506 */
6507 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6508 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6509
6510 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6511 NetworkRequest nr = nai.requestAt(i);
6512 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6513 final int uidRules = mUidRules.get(nri.mUid);
6514 final boolean oldBlocked, newBlocked;
6515 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6516 // between these two calls.
6517 synchronized (mVpns) {
6518 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6519 oldRestrictBackground);
6520 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6521 newRestrictBackground);
6522 }
6523 if (oldBlocked != newBlocked) {
6524 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6525 encodeBool(newBlocked));
6526 }
6527 }
6528 }
6529
6530 /**
6531 * Notify apps with a given UID of the new blocked state according to new uid rules.
6532 * @param uid The uid for which the rules changed.
6533 * @param newRules The new rules to apply.
6534 */
6535 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6536 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6537 final boolean metered = nai.networkCapabilities.isMetered();
6538 final boolean oldBlocked, newBlocked;
6539 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6540 // rules changed event. And this function actually loop through all connected nai and
6541 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6542 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6543 synchronized (mVpns) {
6544 oldBlocked = isUidNetworkingWithVpnBlocked(
6545 uid, mUidRules.get(uid), metered, mRestrictBackground);
6546 newBlocked = isUidNetworkingWithVpnBlocked(
6547 uid, newRules, metered, mRestrictBackground);
6548 }
6549 if (oldBlocked == newBlocked) {
6550 return;
6551 }
6552 final int arg = encodeBool(newBlocked);
6553 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6554 NetworkRequest nr = nai.requestAt(i);
6555 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6556 if (nri != null && nri.mUid == uid) {
6557 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6558 }
6559 }
6560 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006561 }
6562
Robert Greenwalt8d482522015-06-24 13:23:42 -07006563 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006564 // The NetworkInfo we actually send out has no bearing on the real
6565 // state of affairs. For example, if the default connection is mobile,
6566 // and a request for HIPRI has just gone away, we need to pretend that
6567 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6568 // the state to DISCONNECTED, even though the network is of type MOBILE
6569 // and is still connected.
6570 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6571 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006572 if (state != DetailedState.DISCONNECTED) {
6573 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006574 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006575 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006576 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006577 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6578 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6579 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6580 if (info.isFailover()) {
6581 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6582 nai.networkInfo.setFailover(false);
6583 }
6584 if (info.getReason() != null) {
6585 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6586 }
6587 if (info.getExtraInfo() != null) {
6588 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6589 }
6590 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006591 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006592 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006593 if (newDefaultAgent != null) {
6594 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6595 newDefaultAgent.networkInfo);
6596 } else {
6597 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6598 }
6599 }
6600 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6601 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006602 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006603 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006604 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006605 }
6606 }
6607 }
6608
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006609 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006610 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006611 String notification = ConnectivityManager.getCallbackName(notifyType);
6612 log("notifyType " + notification + " for " + networkAgent.name());
6613 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006614 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6615 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006616 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6617 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006618 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6619 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006620 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006621 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006622 } else {
6623 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6624 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006625 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006626 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006627
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006628 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6629 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6630 }
6631
Jeff Sharkey69736342014-12-08 14:50:12 -08006632 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006633 * Returns the list of all interfaces that could be used by network traffic that does not
6634 * explicitly specify a network. This includes the default network, but also all VPNs that are
6635 * currently connected.
6636 *
6637 * Must be called on the handler thread.
6638 */
6639 private Network[] getDefaultNetworks() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006640 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006641 ArrayList<Network> defaultNetworks = new ArrayList<>();
6642 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6643 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6644 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6645 defaultNetworks.add(nai.network);
6646 }
6647 }
6648 return defaultNetworks.toArray(new Network[0]);
6649 }
6650
6651 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006652 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6653 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006654 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006655 private void notifyIfacesChangedForNetworkStats() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006656 ensureRunningOnConnectivityServiceThread();
6657 String activeIface = null;
6658 LinkProperties activeLinkProperties = getActiveLinkProperties();
6659 if (activeLinkProperties != null) {
6660 activeIface = activeLinkProperties.getInterfaceName();
6661 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006662 try {
Varun Anandd33cbc62019-02-07 14:13:13 -08006663 mStatsService.forceUpdateIfaces(
6664 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006665 } catch (Exception ignored) {
6666 }
6667 }
6668
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006669 @Override
6670 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006671 int user = UserHandle.getUserId(Binder.getCallingUid());
6672 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006673 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006674 return mVpns.get(user).addAddress(address, prefixLength);
6675 }
6676 }
6677
6678 @Override
6679 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006680 int user = UserHandle.getUserId(Binder.getCallingUid());
6681 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006682 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006683 return mVpns.get(user).removeAddress(address, prefixLength);
6684 }
6685 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006686
6687 @Override
6688 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006689 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006690 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006691 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006692 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006693 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006694 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006695 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006696 mHandler.post(() -> {
6697 // Update VPN's capabilities based on updated underlying network set.
6698 updateAllVpnsCapabilities();
6699 notifyIfacesChangedForNetworkStats();
6700 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006701 }
6702 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006703 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006704
6705 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006706 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006707 enforceConnectivityInternalPermission();
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09006708 final String defaultUrl = mContext.getResources().getString(
6709 R.string.config_networkDefaultCaptivePortalServerUrl);
6710 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext, defaultUrl);
Udam Sainib7c24872016-01-04 12:16:14 -08006711 }
6712
6713 @Override
junyulai7c469172019-01-16 20:23:34 +08006714 public void startNattKeepalive(Network network, int intervalSeconds,
6715 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006716 enforceKeepalivePermission();
6717 mKeepaliveTracker.startNattKeepalive(
junyulai0c666972019-03-04 22:45:36 +08006718 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai7c469172019-01-16 20:23:34 +08006719 intervalSeconds, cb,
junyulai06835112019-01-03 18:50:15 +08006720 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006721 }
6722
6723 @Override
junyulai215b8772019-01-15 11:32:44 +08006724 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006725 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006726 String dstAddr) {
junyulai215b8772019-01-15 11:32:44 +08006727 mKeepaliveTracker.startNattKeepalive(
6728 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006729 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006730 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6731 }
6732
6733 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006734 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006735 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006736 enforceKeepalivePermission();
6737 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006738 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006739 }
6740
6741 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006742 public void stopKeepalive(Network network, int slot) {
6743 mHandler.sendMessage(mHandler.obtainMessage(
junyulai06835112019-01-03 18:50:15 +08006744 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006745 }
6746
6747 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006748 public void factoryReset() {
6749 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006750
6751 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6752 return;
6753 }
6754
Robin Lee3b3dd942015-05-12 18:14:58 +01006755 final int userId = UserHandle.getCallingUserId();
6756
Stuart Scottf1fb3972015-04-02 18:00:02 -07006757 // Turn airplane mode off
6758 setAirplaneMode(false);
6759
Stuart Scotte3e314d2015-04-20 14:07:45 -07006760 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6761 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006762 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006763 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006764 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006765 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006766 }
6767
Stuart Scotte3e314d2015-04-20 14:07:45 -07006768 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006769 // Remove always-on package
6770 synchronized (mVpns) {
6771 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6772 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006773 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006774 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6775 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006776
Hugo Benichi69744342017-11-27 10:57:16 +09006777 // Turn Always-on VPN off
6778 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6779 final long ident = Binder.clearCallingIdentity();
6780 try {
6781 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6782 mLockdownEnabled = false;
6783 setLockdownTracker(null);
6784 } finally {
6785 Binder.restoreCallingIdentity(ident);
6786 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006787 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006788
Hugo Benichi69744342017-11-27 10:57:16 +09006789 // Turn VPN off
6790 VpnConfig vpnConfig = getVpnConfig(userId);
6791 if (vpnConfig != null) {
6792 if (vpnConfig.legacy) {
6793 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6794 } else {
6795 // Prevent this app (packagename = vpnConfig.user) from initiating
6796 // VPN connections in the future without user intervention.
6797 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006798
Hugo Benichi69744342017-11-27 10:57:16 +09006799 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6800 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006801 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006802 }
6803 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006804
6805 Settings.Global.putString(mContext.getContentResolver(),
6806 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006807 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006808
Ricky Wai44dcbde2018-01-23 04:09:45 +00006809 @Override
6810 public byte[] getNetworkWatchlistConfigHash() {
6811 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6812 if (nwm == null) {
6813 loge("Unable to get NetworkWatchlistManager");
6814 return null;
6815 }
6816 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6817 return nwm.getWatchlistConfigHash();
6818 }
6819
Paul Jensencf4c2c62015-07-01 14:16:32 -04006820 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006821 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6822 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006823 }
6824
6825 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006826 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6827 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6828 }
6829
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006830 @VisibleForTesting
6831 public boolean hasService(String name) {
6832 return ServiceManager.checkService(name) != null;
6833 }
6834
Hugo Benichi64901e52017-10-19 14:42:40 +09006835 @VisibleForTesting
6836 protected IpConnectivityMetrics.Logger metricsLogger() {
6837 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6838 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006839 }
6840
6841 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006842 int[] transports = nai.networkCapabilities.getTransportTypes();
6843 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006844 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006845
6846 private static boolean toBool(int encodedBoolean) {
6847 return encodedBoolean != 0; // Only 0 means false.
6848 }
6849
6850 private static int encodeBool(boolean b) {
6851 return b ? 1 : 0;
6852 }
mswest46386886f2018-03-12 10:34:34 -07006853
6854 @Override
6855 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6856 FileDescriptor err, String[] args, ShellCallback callback,
6857 ResultReceiver resultReceiver) {
6858 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6859 }
6860
6861 private class ShellCmd extends ShellCommand {
6862
6863 @Override
6864 public int onCommand(String cmd) {
6865 if (cmd == null) {
6866 return handleDefaultCommands(cmd);
6867 }
6868 final PrintWriter pw = getOutPrintWriter();
6869 try {
6870 switch (cmd) {
6871 case "airplane-mode":
6872 final String action = getNextArg();
6873 if ("enable".equals(action)) {
6874 setAirplaneMode(true);
6875 return 0;
6876 } else if ("disable".equals(action)) {
6877 setAirplaneMode(false);
6878 return 0;
6879 } else if (action == null) {
6880 final ContentResolver cr = mContext.getContentResolver();
6881 final int enabled = Settings.Global.getInt(cr,
6882 Settings.Global.AIRPLANE_MODE_ON);
6883 pw.println(enabled == 0 ? "disabled" : "enabled");
6884 return 0;
6885 } else {
6886 onHelp();
6887 return -1;
6888 }
6889 default:
6890 return handleDefaultCommands(cmd);
6891 }
6892 } catch (Exception e) {
6893 pw.println(e);
6894 }
6895 return -1;
6896 }
6897
6898 @Override
6899 public void onHelp() {
6900 PrintWriter pw = getOutPrintWriter();
6901 pw.println("Connectivity service commands:");
6902 pw.println(" help");
6903 pw.println(" Print this help text.");
6904 pw.println(" airplane-mode [enable|disable]");
6905 pw.println(" Turn airplane mode on or off.");
6906 pw.println(" airplane-mode");
6907 pw.println(" Get airplane mode.");
6908 }
6909 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006910
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006911 @GuardedBy("mVpns")
6912 private Vpn getVpnIfOwner() {
6913 final int uid = Binder.getCallingUid();
6914 final int user = UserHandle.getUserId(uid);
6915
6916 final Vpn vpn = mVpns.get(user);
6917 if (vpn == null) {
6918 return null;
6919 } else {
6920 final VpnInfo info = vpn.getVpnInfo();
6921 return (info == null || info.ownerUid != uid) ? null : vpn;
6922 }
6923 }
6924
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006925 /**
6926 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6927 * for testing.
6928 */
6929 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6930 if (checkNetworkStackPermission()) {
6931 return null;
6932 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006933 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006934 Vpn vpn = getVpnIfOwner();
6935 if (vpn != null) {
6936 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006937 }
6938 }
6939 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6940 + "permission");
6941 }
6942
6943 /**
6944 * @param connectionInfo the connection to resolve.
6945 * @return {@code uid} if the connection is found and the app has permission to observe it
6946 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6947 * connection is not found.
6948 */
6949 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6950 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6951 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6952 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6953 }
6954
6955 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6956 connectionInfo.local, connectionInfo.remote);
6957
6958 /* Filter out Uids not associated with the VPN. */
6959 if (vpn != null && !vpn.appliesToUid(uid)) {
6960 return INVALID_UID;
6961 }
6962
6963 return uid;
6964 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006965
6966 @Override
6967 public boolean isCallerCurrentAlwaysOnVpnApp() {
6968 synchronized (mVpns) {
6969 Vpn vpn = getVpnIfOwner();
6970 return vpn != null && vpn.getAlwaysOn();
6971 }
6972 }
6973
6974 @Override
6975 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6976 synchronized (mVpns) {
6977 Vpn vpn = getVpnIfOwner();
6978 return vpn != null && vpn.getLockdown();
6979 }
6980 }
Benedict Wonga341fbc2018-11-09 14:45:34 -08006981
6982 /**
6983 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
6984 *
6985 * <p>The TestNetworkService must be run in the system server due to TUN creation.
6986 */
6987 @Override
6988 public IBinder startOrGetTestNetworkService() {
6989 synchronized (mTNSLock) {
6990 TestNetworkService.enforceTestNetworkPermissions(mContext);
6991
6992 if (mTNS == null) {
6993 mTNS = new TestNetworkService(mContext, mNMS);
6994 }
6995
6996 return mTNS;
6997 }
6998 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006999}