blob: ed704b8bbd81fe2d486bfa705d2d21f546cb4d26 [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;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090044import static android.net.shared.NetworkParcelableUtil.toStableParcelable;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070045import static android.os.Process.INVALID_UID;
46import static android.system.OsConstants.IPPROTO_TCP;
47import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060048
Hugo Benichia0385682017-03-22 17:07:57 +090049import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060050
Wenchao Tongf5ea3402015-03-04 13:26:38 -080051import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080052import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090053import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070054import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070055import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ContentResolver;
57import android.content.Context;
58import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070059import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070060import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070061import android.database.ContentObserver;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090062import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070063import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.ConnectivityManager;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090065import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.IConnectivityManager;
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
298 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800299 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700300 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900301 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700302
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700303 private String mCurrentTcpBufferSizes;
304
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900305 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900306 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
307 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900308
Paul Jensenb10e37f2014-11-25 12:33:08 -0500309 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400310 // Tear down networks that have no chance (e.g. even if validated) of becoming
311 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500312 // all networks have been rematched against all NetworkRequests.
313 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400314 // Don't reap networks. This should be passed when some networks have not yet been
315 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500316 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900317 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500318
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900319 private enum UnneededFor {
320 LINGER, // Determine whether this network is unneeded and should be lingered.
321 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
322 }
323
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700324 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700325 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700326 * from one net to another. Clear happens when we get a new
327 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
328 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700329 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700330 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700331
Robert Greenwalt434203a2010-10-11 16:00:27 -0700332 /**
333 * used internally to reload global proxy settings
334 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700335 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700336
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700337 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400338 * PAC manager has received new port.
339 */
340 private static final int EVENT_PROXY_HAS_CHANGED = 16;
341
Robert Greenwalte049c232014-04-11 15:53:27 -0700342 /**
343 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700344 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700345 */
346 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
347
Robert Greenwalt7b816022014-04-18 15:25:25 -0700348 /**
349 * used internally when registering NetworkAgents
350 * obj = Messenger
351 */
352 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
353
Robert Greenwalt9258c642014-03-26 16:47:06 -0700354 /**
355 * used to add a network request
356 * includes a NetworkRequestInfo
357 */
358 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
359
360 /**
361 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900362 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700363 * cancel it.
364 * includes a NetworkRequestInfo
365 */
366 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
367
368 /**
369 * used to add a network listener - no request
370 * includes a NetworkRequestInfo
371 */
372 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
373
374 /**
375 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400376 * arg1 = UID of caller
377 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700378 */
379 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
380
Robert Greenwalta67be032014-05-16 15:49:14 -0700381 /**
382 * used internally when registering NetworkFactories
383 * obj = Messenger
384 */
385 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
386
Robert Greenwalt27711812014-06-25 16:45:57 -0700387 /**
388 * used internally to expire a wakelock when transitioning
389 * from one net to another. Expire happens when we fail to find
390 * a new network (typically after 1 minute) -
391 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
392 * a replacement network.
393 */
394 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
395
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700396 /**
397 * Used internally to indicate the system is ready.
398 */
399 private static final int EVENT_SYSTEM_READY = 25;
400
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800401 /**
402 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400403 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800404 */
405 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
406
407 /**
408 * used to remove a pending intent and its associated network request.
409 * arg1 = UID of caller
410 * obj = PendingIntent
411 */
412 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
413
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900414 /**
415 * used to specify whether a network should be used even if unvalidated.
416 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
417 * arg2 = whether to remember this choice in the future (1 or 0)
418 * obj = network
419 */
420 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
421
422 /**
423 * used to ask the user to confirm a connection to an unvalidated network.
424 * obj = network
425 */
426 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700427
Erik Klineda4bfa82015-04-30 12:58:40 +0900428 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700429 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900430 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700431 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900432
Paul Jensen694f2b82015-06-17 14:15:39 -0400433 /**
434 * used to add a network listener with a pending intent
435 * obj = NetworkRequestInfo
436 */
437 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
438
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900439 /**
440 * used to specify whether a network should not be penalized when it becomes unvalidated.
441 */
442 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
443
444 /**
445 * used to trigger revalidation of a network.
446 */
447 private static final int EVENT_REVALIDATE_NETWORK = 36;
448
Erik Klinea24d4592018-01-11 21:07:29 +0900449 // Handle changes in Private DNS settings.
450 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
451
dalyk7301aa42018-03-05 12:42:22 -0500452 // Handle private DNS validation status updates.
453 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
454
junyulai05986c62018-08-07 19:50:45 +0800455 /**
456 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
457 */
458 private static final int EVENT_UID_RULES_CHANGED = 39;
459
460 /**
461 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
462 */
463 private static final int EVENT_DATA_SAVER_CHANGED = 40;
464
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900465 /**
466 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
467 * been tested.
468 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
469 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
470 * arg2 = NetID.
471 */
472 public static final int EVENT_NETWORK_TESTED = 41;
473
474 /**
475 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
476 * config was resolved.
477 * obj = PrivateDnsConfig
478 * arg2 = netid
479 */
480 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
481
482 /**
483 * Request ConnectivityService display provisioning notification.
484 * arg1 = Whether to make the notification visible.
485 * arg2 = NetID.
486 * obj = Intent to be launched when notification selected by user, null if !arg1.
487 */
488 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
489
490 /**
lucaslind2e045e02019-01-24 15:55:30 +0800491 * This event can handle dismissing notification by given network id.
492 */
493 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
494
495 /**
lucasline252a742019-03-12 13:08:03 +0800496 * Used to specify whether a network should be used even if connectivity is partial.
497 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
498 * false)
499 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
500 * obj = network
501 */
502 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
503
504 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900505 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
506 * should be shown.
507 */
508 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
509
510 /**
511 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
512 * should be hidden.
513 */
514 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
515
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900516 private static String eventName(int what) {
517 return sMagicDecoderRing.get(what, Integer.toString(what));
518 }
519
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900520 /** Handler thread used for both of the handlers below. */
521 @VisibleForTesting
522 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700523 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700524 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700525 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700526 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900527 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700528
Mike Lockwood0f79b542009-08-14 14:18:49 -0400529 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800530 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400531
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700532 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700533 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800534 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700535
Chalard Jean52c2aa72018-06-07 16:44:04 +0900536 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
537 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000538 @VisibleForTesting
539 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400540
Erik Klineda4bfa82015-04-30 12:58:40 +0900541 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700542
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400543 private UserManager mUserManager;
544
Chalard Jean4133a122018-06-04 13:33:12 +0900545 private NetworkConfig[] mNetConfigs;
546 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700547
Robert Greenwalt50393202011-06-21 17:26:14 -0700548 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900549 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700550
Chalard Jean4133a122018-06-04 13:33:12 +0900551 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400552
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900553 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900554 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900555 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900556
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700557 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800558 private static final int MIN_NET_ID = 100; // some reserved marks
559 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700560 private int mNextNetId = MIN_NET_ID;
561
Robert Greenwalt34524f02014-05-18 16:22:10 -0700562 // sequence number of NetworkRequests
563 private int mNextNetworkRequestId = 1;
564
Erik Kline7523eb32015-07-09 18:24:03 +0900565 // NetworkRequest activity String log entries.
566 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
567 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
568
Hugo Benichic2ae2872016-07-11 11:05:12 +0900569 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900570 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900571 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
572
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900573 private static final int MAX_WAKELOCK_LOGS = 20;
574 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900575 private int mTotalWakelockAcquisitions = 0;
576 private int mTotalWakelockReleases = 0;
577 private long mTotalWakelockDurationMs = 0;
578 private long mMaxWakelockDurationMs = 0;
579 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900580
Hugo Benichif9fdf872016-07-28 17:53:06 +0900581 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900582
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700583 @GuardedBy("mBandwidthRequests")
584 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
585
Erik Kline065ab6e2016-10-02 18:02:14 +0900586 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900587 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900588
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900589 @VisibleForTesting
590 final MultipathPolicyTracker mMultipathPolicyTracker;
591
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 /**
593 * Implements support for the legacy "one network per network type" model.
594 *
595 * We used to have a static array of NetworkStateTrackers, one for each
596 * network type, but that doesn't work any more now that we can have,
597 * for example, more that one wifi network. This class stores all the
598 * NetworkAgentInfo objects that support a given type, but the legacy
599 * API will only see the first one.
600 *
601 * It serves two main purposes:
602 *
603 * 1. Provide information about "the network for a given type" (since this
604 * API only supports one).
605 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
606 * the first network for a given type changes, or if the default network
607 * changes.
608 */
609 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900610
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900611 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 /**
615 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
616 * Each list holds references to all NetworkAgentInfos that are used to
617 * satisfy requests for that network type.
618 *
619 * This array is built out at startup such that an unsupported network
620 * doesn't get an ArrayList instance, making this a tristate:
621 * unsupported, supported but not active and active.
622 *
623 * The actual lists are populated when we scan the network types that
624 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900625 *
626 * Threading model:
627 * - addSupportedType() is only called in the constructor
628 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
629 * They are therefore not thread-safe with respect to each other.
630 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
631 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
632 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700633 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900634 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700635
636 public LegacyTypeTracker() {
637 mTypeLists = (ArrayList<NetworkAgentInfo>[])
638 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
639 }
640
641 public void addSupportedType(int type) {
642 if (mTypeLists[type] != null) {
643 throw new IllegalStateException(
644 "legacy list for type " + type + "already initialized");
645 }
Chalard Jean4133a122018-06-04 13:33:12 +0900646 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700647 }
648
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700649 public boolean isTypeSupported(int type) {
650 return isNetworkTypeValid(type) && mTypeLists[type] != null;
651 }
652
653 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900654 synchronized (mTypeLists) {
655 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
656 return mTypeLists[type].get(0);
657 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700658 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900659 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700660 }
661
Robert Greenwalt8d482522015-06-24 13:23:42 -0700662 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900663 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900664 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700665 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900666 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900667 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900668 }
669 }
670
671 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700672 public void add(int type, NetworkAgentInfo nai) {
673 if (!isTypeSupported(type)) {
674 return; // Invalid network type.
675 }
676 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
677
678 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
679 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700680 return;
681 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900682 synchronized (mTypeLists) {
683 list.add(nai);
684 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900685
686 // 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 +0900687 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900688 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700689 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
690 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700691 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700692 }
693
Lorenzo Colittia793a672014-07-31 23:20:17 +0900694 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900695 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900696 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
697 if (list == null || list.isEmpty()) {
698 return;
699 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900700 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900701
Hugo Benichi78caa2582016-06-21 09:48:07 +0900702 synchronized (mTypeLists) {
703 if (!list.remove(nai)) {
704 return;
705 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900706 }
707
Robert Greenwalt8d482522015-06-24 13:23:42 -0700708 final DetailedState state = DetailedState.DISCONNECTED;
709
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900710 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700711 maybeLogBroadcast(nai, state, type, wasDefault);
712 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900713 }
714
715 if (!list.isEmpty() && wasFirstNetwork) {
716 if (DBG) log("Other network available for type " + type +
717 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900718 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700719 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
720 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900721 }
722 }
723
724 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900725 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
726 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700727 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900728 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700729 }
730 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700731
Robert Greenwalt8d482522015-06-24 13:23:42 -0700732 // send out another legacy broadcast - currently only used for suspend/unsuspend
733 // toggle
734 public void update(NetworkAgentInfo nai) {
735 final boolean isDefault = isDefaultNetwork(nai);
736 final DetailedState state = nai.networkInfo.getDetailedState();
737 for (int type = 0; type < mTypeLists.length; type++) {
738 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700739 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900740 final boolean isFirst = contains && (nai == list.get(0));
741 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700742 maybeLogBroadcast(nai, state, type, isDefault);
743 sendLegacyNetworkBroadcast(nai, state, type);
744 }
745 }
746 }
747
Lorenzo Colittia793a672014-07-31 23:20:17 +0900748 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900749 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900750 String state = (nai.networkInfo != null) ?
751 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
752 "???/???";
753 return name + " " + state;
754 }
755
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700756 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900757 pw.println("mLegacyTypeTracker:");
758 pw.increaseIndent();
759 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700760 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900761 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700762 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900763 pw.println();
764 pw.println("Current state:");
765 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900766 synchronized (mTypeLists) {
767 for (int type = 0; type < mTypeLists.length; type++) {
768 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
769 for (NetworkAgentInfo nai : mTypeLists[type]) {
770 pw.println(type + " " + naiToString(nai));
771 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900772 }
773 }
774 pw.decreaseIndent();
775 pw.decreaseIndent();
776 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700777 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700778 }
779 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
780
Vishnu Nair5c010902017-10-26 10:08:50 -0700781 /**
782 * Helper class which parses out priority arguments and dumps sections according to their
783 * priority. If priority arguments are omitted, function calls the legacy dump command.
784 */
785 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
786 @Override
787 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
788 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
789 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
790 }
791
792 @Override
793 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
794 doDump(fd, pw, args, asProto);
795 }
796
797 @Override
798 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
799 doDump(fd, pw, args, asProto);
800 }
801 };
802
Jeff Sharkey899223b2012-08-04 15:24:58 -0700803 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700804 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900805 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
806 }
807
808 @VisibleForTesting
809 protected ConnectivityService(Context context, INetworkManagementService netManager,
810 INetworkStatsService statsService, INetworkPolicyManager policyManager,
811 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800812 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800813
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900814 mSystemProperties = getSystemProperties();
815
Hugo Benichif9fdf872016-07-28 17:53:06 +0900816 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900817 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900818 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900819 mNetworkRequests.put(mDefaultRequest, defaultNRI);
820 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900821
Chalard Jeandda156a2018-01-10 21:19:32 +0900822 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900823 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700824
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700825 // The default WiFi request is a background request so that apps using WiFi are
826 // migrated to a better network (typically ethernet) when one comes up, instead
827 // of staying on WiFi forever.
828 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
829 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
830
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900831 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900832 mHandlerThread.start();
833 mHandler = new InternalHandler(mHandlerThread.getLooper());
834 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700835
Jeremy Joslin79294842014-12-03 17:15:28 -0800836 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
837 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
838
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900839 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900840
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700841 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800842 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800843 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700844 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900845 mPolicyManagerInternal = checkNotNull(
846 LocalServices.getService(NetworkPolicyManagerInternal.class),
847 "missing NetworkPolicyManagerInternal");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000848 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900849
Luke Huang674660f2018-09-27 19:33:11 +0800850 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700851 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700852 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700853
junyulai05986c62018-08-07 19:50:45 +0800854 // To ensure uid rules are synchronized with Network Policy, register for
855 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
856 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700857 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900858 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700859 } catch (RemoteException e) {
860 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700861 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700862 }
863
864 final PowerManager powerManager = (PowerManager) context.getSystemService(
865 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700866 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
867 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
868 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800869 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700870
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700871 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700872
Wink Saville51f456f2013-04-23 14:26:51 -0700873 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900874 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700875 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700876 String[] naStrings = context.getResources().getStringArray(
877 com.android.internal.R.array.networkAttributes);
878 for (String naString : naStrings) {
879 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700880 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700881 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700882 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800883 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700884 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700885 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700886 }
Wink Saville51f456f2013-04-23 14:26:51 -0700887 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
888 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
889 n.type);
890 continue;
891 }
Wink Saville975c8482011-04-07 14:23:45 -0700892 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800893 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700894 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700895 continue;
896 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700897 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700898
Wink Saville975c8482011-04-07 14:23:45 -0700899 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700900 mNetworksDefined++;
901 } catch(Exception e) {
902 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700903 }
904 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700905
906 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
907 if (mNetConfigs[TYPE_VPN] == null) {
908 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
909 // don't need to add TYPE_VPN to mNetConfigs.
910 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
911 mNetworksDefined++; // used only in the log() statement below.
912 }
913
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900914 // Do the same for Ethernet, since it's often not specified in the configs, although many
915 // devices can use it via USB host adapters.
916 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
917 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
918 mNetworksDefined++;
919 }
920
Wink Saville5e56bc52013-07-29 15:00:57 -0700921 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700922
Robert Greenwalt50393202011-06-21 17:26:14 -0700923 mProtectedNetworks = new ArrayList<Integer>();
924 int[] protectedNetworks = context.getResources().getIntArray(
925 com.android.internal.R.array.config_protectedNetworks);
926 for (int p : protectedNetworks) {
927 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
928 mProtectedNetworks.add(p);
929 } else {
930 if (DBG) loge("Ignoring protectedNetwork " + p);
931 }
932 }
933
Erik Kline47222fc2017-04-30 19:36:15 +0900934 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800935
Luke Huang4e25ec62018-09-27 16:58:23 +0800936 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700937
Varun Anand4fa80e82019-02-06 10:13:38 -0800938 // Set up the listener for user state for creating user VPNs.
939 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700940 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100941 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700942 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700943 intentFilter.addAction(Intent.ACTION_USER_ADDED);
944 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000945 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700946 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800947 mIntentReceiver,
948 UserHandle.ALL,
949 intentFilter,
950 null /* broadcastPermission */,
951 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000952 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
953 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900954
junyulai2454b692018-11-01 17:16:31 +0800955 // Listen to package add and removal events for all users.
956 intentFilter = new IntentFilter();
957 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800958 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800959 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
960 intentFilter.addDataScheme("package");
961 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800962 mIntentReceiver,
963 UserHandle.ALL,
964 intentFilter,
965 null /* broadcastPermission */,
966 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800967
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700968 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800969 mNMS.registerObserver(mTethering);
970 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700971 } catch (RemoteException e) {
972 loge("Error registering observer :" + e);
973 }
974
Erik Klineda4bfa82015-04-30 12:58:40 +0900975 mSettingsObserver = new SettingsObserver(mContext, mHandler);
976 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800977
Chalard Jean4133a122018-06-04 13:33:12 +0900978 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
979 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400980
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400981 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900982
983 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900984 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
985 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900986
987 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
988 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
989 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
990 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
991 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
992 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
993 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900994
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900995 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900996 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900997 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900998
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900999 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1000
Luke Huang4e25ec62018-09-27 16:58:23 +08001001 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001002 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001004
Mike Yuf9729752018-08-17 15:22:05 +08001005 @VisibleForTesting
1006 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001007 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001008 final TetheringDependencies deps = new TetheringDependencies() {
1009 @Override
1010 public boolean isTetheringSupported() {
1011 return ConnectivityService.this.isTetheringSupported();
1012 }
Erik Kline72302902018-06-14 17:36:40 +09001013 @Override
1014 public NetworkRequest getDefaultNetworkRequest() {
1015 return mDefaultRequest;
1016 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001017 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001018 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001019 IoThread.get().getLooper(), new MockableSystemProperties(),
1020 deps);
1021 }
1022
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001023 @VisibleForTesting
1024 protected ProxyTracker makeProxyTracker() {
1025 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1026 }
1027
Chalard Jean26400492018-04-18 20:18:38 +09001028 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1029 final NetworkCapabilities netCap = new NetworkCapabilities();
1030 netCap.addCapability(NET_CAPABILITY_INTERNET);
1031 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1032 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1033 netCap.setSingleUid(uid);
1034 return netCap;
1035 }
1036
Chalard Jeandda156a2018-01-10 21:19:32 +09001037 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001038 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001039 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001040 netCap.addCapability(NET_CAPABILITY_INTERNET);
1041 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001042 if (transportType > -1) {
1043 netCap.addTransportType(transportType);
1044 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001045 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001046 }
1047
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001048 // Used only for testing.
1049 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001050 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001051 // changing ContentResolver to make registerContentObserver non-final).
1052 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1053 // by subclassing SettingsObserver.
1054 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001055 void updateAlwaysOnNetworks() {
1056 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001057 }
1058
Erik Kline736353a2018-03-21 07:18:33 -07001059 // See FakeSettingsProvider comment above.
1060 @VisibleForTesting
1061 void updatePrivateDnsSettings() {
1062 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1063 }
1064
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001065 private void handleAlwaysOnNetworkRequest(
1066 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001067 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001068 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1069 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001070 if (enable == isEnabled) {
1071 return; // Nothing to do.
1072 }
1073
1074 if (enable) {
1075 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001076 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001077 } else {
Etan Cohenddb720a2019-01-08 12:09:18 -08001078 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1079 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001080 }
1081 }
1082
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001083 private void handleConfigureAlwaysOnNetworks() {
1084 handleAlwaysOnNetworkRequest(
1085 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1086 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1087 false);
1088 }
1089
Erik Klineda4bfa82015-04-30 12:58:40 +09001090 private void registerSettingsCallbacks() {
1091 // Watch for global HTTP proxy changes.
1092 mSettingsObserver.observe(
1093 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1094 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1095
1096 // Watch for whether or not to keep mobile data always on.
1097 mSettingsObserver.observe(
1098 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001099 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1100
1101 // Watch for whether or not to keep wifi always on.
1102 mSettingsObserver.observe(
1103 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1104 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001105 }
1106
Erik Klinea24d4592018-01-11 21:07:29 +09001107 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001108 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1109 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001110 }
1111 }
1112
Robert Greenwalt34524f02014-05-18 16:22:10 -07001113 private synchronized int nextNetworkRequestId() {
1114 return mNextNetworkRequestId++;
1115 }
1116
Paul Jensen67b0b072015-06-10 11:22:17 -04001117 @VisibleForTesting
1118 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001119 synchronized (mNetworkForNetId) {
1120 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1121 int netId = mNextNetId;
1122 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1123 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001124 if (!mNetIdInUse.get(netId)) {
1125 mNetIdInUse.put(netId, true);
1126 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001127 }
1128 }
1129 }
1130 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001131 }
1132
Chalard Jeanc0982912018-06-07 16:11:34 +09001133 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001134 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001135 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1136 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 state = nai.getNetworkState();
1139 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001141 final NetworkInfo info = new NetworkInfo(networkType, 0,
1142 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001143 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1144 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001145 final NetworkCapabilities capabilities = new NetworkCapabilities();
1146 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1147 !info.isRoaming());
1148 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001149 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001150 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001151 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001152 return state;
1153 } else {
1154 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001156 }
1157
junyulai4a192e22018-06-13 15:00:37 +08001158 @VisibleForTesting
1159 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001160 if (network == null) {
1161 return null;
1162 }
Erik Kline736353a2018-03-21 07:18:33 -07001163 return getNetworkAgentInfoForNetId(network.netId);
1164 }
1165
1166 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001168 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001172 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001173 synchronized (mVpns) {
1174 if (!mLockdownEnabled) {
1175 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001176 Vpn vpn = mVpns.get(user);
1177 if (vpn != null && vpn.appliesToUid(uid)) {
1178 return vpn.getUnderlyingNetworks();
1179 }
1180 }
1181 }
1182 return null;
1183 }
1184
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001186 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001187
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001188 final Network[] networks = getVpnUnderlyingNetworks(uid);
1189 if (networks != null) {
1190 // getUnderlyingNetworks() returns:
1191 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1192 // empty array => the VPN explicitly said "no default network".
1193 // non-empty array => the VPN specified one or more default networks; we use the
1194 // first one.
1195 if (networks.length > 0) {
1196 nai = getNetworkAgentInfoForNetwork(networks[0]);
1197 } else {
1198 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001199 }
1200 }
1201
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001203 return nai.getNetworkState();
1204 } else {
1205 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001206 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001207 }
1208
1209 /**
1210 * Check if UID should be blocked from using the network with the given LinkProperties.
1211 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001212 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1213 boolean ignoreBlocked) {
1214 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001215 if (ignoreBlocked) {
1216 return false;
1217 }
Robin Lee17e61832016-05-09 13:46:28 +01001218 synchronized (mVpns) {
1219 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001220 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001221 return true;
1222 }
1223 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001224 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001225 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001226 }
1227
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001228 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001229 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1230 return;
1231 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001232 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001233 synchronized (mBlockedAppUids) {
1234 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001235 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001236 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001237 blocked = false;
1238 } else {
1239 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001240 }
1241 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001242 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1243 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1244 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001245 }
1246
junyulai05986c62018-08-07 19:50:45 +08001247 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1248 boolean blocked) {
1249 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1250 return;
1251 }
1252 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1253 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1254 nri.mUid, nri.request.requestId, net.netId));
1255 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1256 }
1257
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001258 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001259 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1260 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001261 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001262 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001263 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001264 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1265
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001266 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001267 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001268 }
Hugo Benichi69744342017-11-27 10:57:16 +09001269 synchronized (mVpns) {
1270 if (mLockdownTracker != null) {
1271 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1272 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001273 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001274 }
1275
1276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 * Return NetworkInfo for the active (i.e., connected) network interface.
1278 * It is assumed that at most one network is active at a time. If more
1279 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001280 * @return the info for the active network, or {@code null} if none is
1281 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001283 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001285 enforceAccessPermission();
1286 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001287 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001288 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001289 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1290 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
1292
Paul Jensen31a94f42015-02-13 14:18:39 -05001293 @Override
1294 public Network getActiveNetwork() {
1295 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001296 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001297 }
1298
1299 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001300 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001301 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001302 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001303 }
1304
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001305 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001306 final int user = UserHandle.getUserId(uid);
1307 int vpnNetId = NETID_UNSET;
1308 synchronized (mVpns) {
1309 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001310 // TODO : now that capabilities contain the UID, the appliesToUid test should
1311 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001312 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1313 }
1314 NetworkAgentInfo nai;
1315 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001316 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001317 if (nai != null) {
1318 final NetworkCapabilities requiredCaps =
1319 createDefaultNetworkCapabilitiesForUid(uid);
1320 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1321 return nai.network;
1322 }
1323 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001324 }
1325 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001326 if (nai != null
1327 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1328 nai = null;
1329 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001330 return nai != null ? nai.network : null;
1331 }
1332
Lorenzo Colitti18660282016-07-04 12:55:44 +09001333 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001334 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1335 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001336 final int uid = Binder.getCallingUid();
1337 NetworkState state = getUnfilteredActiveNetworkState(uid);
1338 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001339 }
1340
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001341 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001342 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001343 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001344 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001345 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001346 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001347 }
1348
1349 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 public NetworkInfo getNetworkInfo(int networkType) {
1351 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001352 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001353 if (getVpnUnderlyingNetworks(uid) != null) {
1354 // A VPN is active, so we may need to return one of its underlying networks. This
1355 // information is not available in LegacyTypeTracker, so we have to get it from
1356 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001357 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001358 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001359 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001360 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001361 }
1362 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001363 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001364 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001367 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001368 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001369 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001370 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001371 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001372 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001373 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001374 return state.networkInfo;
1375 } else {
1376 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001377 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 }
1379
1380 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 public NetworkInfo[] getAllNetworkInfo() {
1382 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001383 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001384 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1385 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001386 NetworkInfo info = getNetworkInfo(networkType);
1387 if (info != null) {
1388 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001391 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001394 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001395 public Network getNetworkForType(int networkType) {
1396 enforceAccessPermission();
1397 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001398 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001399 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001400 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001401 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001402 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001403 }
1404
1405 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001406 public Network[] getAllNetworks() {
1407 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001408 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001409 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001410 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001411 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001412 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001413 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001414 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001415 }
1416
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001417 @Override
1418 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1419 // The basic principle is: if an app's traffic could possibly go over a
1420 // network, without the app doing anything multinetwork-specific,
1421 // (hence, by "default"), then include that network's capabilities in
1422 // the array.
1423 //
1424 // In the normal case, app traffic only goes over the system's default
1425 // network connection, so that's the only network returned.
1426 //
1427 // With a VPN in force, some app traffic may go into the VPN, and thus
1428 // over whatever underlying networks the VPN specifies, while other app
1429 // traffic may go over the system default network (e.g.: a split-tunnel
1430 // VPN, or an app disallowed by the VPN), so the set of networks
1431 // returned includes the VPN's underlying networks and the system
1432 // default.
1433 enforceAccessPermission();
1434
Chalard Jean4133a122018-06-04 13:33:12 +09001435 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001436
1437 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001438 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001439 if (nc != null) {
1440 result.put(nai.network, nc);
1441 }
1442
Hugo Benichi69744342017-11-27 10:57:16 +09001443 synchronized (mVpns) {
1444 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001445 Vpn vpn = mVpns.get(userId);
1446 if (vpn != null) {
1447 Network[] networks = vpn.getUnderlyingNetworks();
1448 if (networks != null) {
1449 for (Network network : networks) {
1450 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001451 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001452 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001453 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001454 }
1455 }
1456 }
1457 }
1458 }
1459 }
1460
1461 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1462 out = result.values().toArray(out);
1463 return out;
1464 }
1465
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001466 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001467 public boolean isNetworkSupported(int networkType) {
1468 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001469 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001470 }
1471
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001472 /**
1473 * Return LinkProperties for the active (i.e., connected) default
1474 * network interface. It is assumed that at most one default network
1475 * is active at a time. If more than one is active, it is indeterminate
1476 * which will be returned.
1477 * @return the ip properties for the active network, or {@code null} if
1478 * none is active
1479 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001480 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001481 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001482 enforceAccessPermission();
1483 final int uid = Binder.getCallingUid();
1484 NetworkState state = getUnfilteredActiveNetworkState(uid);
1485 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001486 }
1487
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001488 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001489 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001490 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001491 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1492 if (nai != null) {
1493 synchronized (nai) {
1494 return new LinkProperties(nai.linkProperties);
1495 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001496 }
1497 return null;
1498 }
1499
Robert Greenwalt12e67352014-05-13 21:41:06 -07001500 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001501 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001502 public LinkProperties getLinkProperties(Network network) {
1503 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001504 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1505 }
1506
1507 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1508 if (nai == null) {
1509 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001510 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001511 synchronized (nai) {
1512 return new LinkProperties(nai.linkProperties);
1513 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001514 }
1515
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001516 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001517 if (nai != null) {
1518 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001519 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001520 return networkCapabilitiesRestrictedForCallerPermissions(
1521 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001522 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001523 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001524 }
1525 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001526 return null;
1527 }
1528
1529 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001530 public NetworkCapabilities getNetworkCapabilities(Network network) {
1531 enforceAccessPermission();
1532 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1533 }
1534
Chalard Jeanb03a6222018-04-11 21:09:10 +09001535 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001536 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001537 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001538 if (!checkSettingsPermission(callerPid, callerUid)) {
1539 newNc.setUids(null);
1540 newNc.setSSID(null);
1541 }
Etan Cohen836ad572018-12-30 17:59:59 -08001542 if (newNc.getNetworkSpecifier() != null) {
1543 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1544 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001545 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001546 }
1547
Chalard Jeanb552c462018-02-21 18:43:54 +09001548 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1549 if (!checkSettingsPermission()) {
1550 nc.setSingleUid(Binder.getCallingUid());
1551 }
1552 }
1553
Chalard Jean26aa91a2018-03-20 19:13:57 +09001554 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1555 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1556 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1557 }
1558 }
1559
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001560 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001561 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001562 // Require internal since we're handing out IMSI details
1563 enforceConnectivityInternalPermission();
1564
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001565 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001566 for (Network network : getAllNetworks()) {
1567 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1568 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001569 // TODO (b/73321673) : NetworkState contains a copy of the
1570 // NetworkCapabilities, which may contain UIDs of apps to which the
1571 // network applies. Should the UIDs be cleared so as not to leak or
1572 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001573 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001574 }
1575 }
1576 return result.toArray(new NetworkState[result.size()]);
1577 }
1578
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001579 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001580 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001581 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001582 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1583 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1584 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001585 }
1586
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001587 @Override
1588 public boolean isActiveNetworkMetered() {
1589 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001590
Varun Anandc51b06d2019-02-25 17:22:02 -08001591 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001592 if (caps != null) {
1593 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1594 } else {
1595 // Always return the most conservative value
1596 return true;
1597 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001598 }
1599
Jeff Sharkey216c1812012-08-05 14:29:23 -07001600 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1601 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001602 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001603 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001604 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001605 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001606 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001607
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001608 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001609 * Ensures that the system cannot call a particular method.
1610 */
1611 private boolean disallowedBecauseSystemCaller() {
1612 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1613 // requestRouteToHost.
1614 if (isSystem(Binder.getCallingUid())) {
1615 log("This method exists only for app backwards compatibility"
1616 + " and must not be called by system services.");
1617 return true;
1618 }
1619 return false;
1620 }
1621
1622 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 * Ensure that a network route exists to deliver traffic to the specified
1624 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001625 * @param networkType the type of the network over which traffic to the
1626 * specified host is to be routed
1627 * @param hostAddress the IP address of the host to which the route is
1628 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 * @return {@code true} on success, {@code false} on failure
1630 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001631 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001632 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001633 if (disallowedBecauseSystemCaller()) {
1634 return false;
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001637 if (mProtectedNetworks.contains(networkType)) {
1638 enforceConnectivityInternalPermission();
1639 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001640
Chad Brubakerc0234532014-02-14 13:24:29 -08001641 InetAddress addr;
1642 try {
1643 addr = InetAddress.getByAddress(hostAddress);
1644 } catch (UnknownHostException e) {
1645 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1646 return false;
1647 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001650 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 return false;
1652 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001653
1654 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1655 if (nai == null) {
1656 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1657 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1658 } else {
1659 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1660 }
1661 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001662 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001663
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001664 DetailedState netState;
1665 synchronized (nai) {
1666 netState = nai.networkInfo.getDetailedState();
1667 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001668
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001669 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001670 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001671 log("requestRouteToHostAddress on down network "
1672 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001673 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001674 }
1675 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001677
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001678 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001679 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001680 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001681 LinkProperties lp;
1682 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001683 synchronized (nai) {
1684 lp = nai.linkProperties;
1685 netId = nai.network.netId;
1686 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001687 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001688 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1689 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001690 } finally {
1691 Binder.restoreCallingIdentity(token);
1692 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001693 }
1694
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001695 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001696 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001697 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001698 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001699 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001700 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001701 if (bestRoute.getGateway().equals(addr)) {
1702 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001703 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001704 } else {
1705 // if we will connect to this through another route, add a direct route
1706 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001707 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001708 }
1709 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001710 if (DBG) log("Adding legacy route " + bestRoute +
1711 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001712 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001713 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001714 } catch (Exception e) {
1715 // never crash - catch them all
1716 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001717 return false;
1718 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001719 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 }
1721
dalyk7301aa42018-03-05 12:42:22 -05001722 @VisibleForTesting
1723 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1724 @Override
1725 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1726 String hostname, boolean validated) {
1727 try {
1728 mHandler.sendMessage(mHandler.obtainMessage(
1729 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1730 new PrivateDnsValidationUpdate(netId,
1731 InetAddress.parseNumericAddress(ipAddress),
1732 hostname, validated)));
1733 } catch (IllegalArgumentException e) {
1734 loge("Error parsing ip address in validation event");
1735 }
1736 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001737
1738 @Override
1739 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1740 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1741 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1742 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1743 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1744 // event callback for certain nai. e.g. cellular. Register here to pass to
1745 // NetworkMonitor instead.
1746 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1747 // registerNetworkAgent to have NetworkMonitor created with system process as design
1748 // expectation. Also, NetdEventListenerService only allow one callback from each
1749 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1750 // NetworkMonitor registrants.
1751 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001752 try {
1753 nai.networkMonitor().notifyDnsResponse(returnCode);
1754 } catch (RemoteException e) {
1755 e.rethrowFromSystemServer();
1756 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001757 }
1758 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001759
1760 @Override
1761 public void onNat64PrefixEvent(int netId, boolean added,
1762 String prefixString, int prefixLength) {
1763 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1764 }
dalyk7301aa42018-03-05 12:42:22 -05001765 };
1766
1767 @VisibleForTesting
1768 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001769 final IIpConnectivityMetrics ipConnectivityMetrics =
1770 IIpConnectivityMetrics.Stub.asInterface(
1771 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1772 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001773 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001774 return;
dalyk7301aa42018-03-05 12:42:22 -05001775 }
1776
1777 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001778 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001779 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1780 mNetdEventCallback);
1781 } catch (Exception e) {
1782 loge("Error registering netd callback: " + e);
1783 }
1784 }
1785
Jeff Sharkey75d31892018-01-18 22:01:59 +09001786 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001787 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001788 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001789 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001790 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001791 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001792 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001793 // caller is NPMS, since we only register with them
1794 if (LOGD_BLOCKED_NETWORKINFO) {
1795 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1796 }
1797 mHandler.sendMessage(mHandler.obtainMessage(
1798 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1799
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001800 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001801 if (restrictBackground) {
1802 log("onRestrictBackgroundChanged(true): disabling tethering");
1803 mTethering.untetherAll();
1804 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001805 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001806 };
1807
junyulai05986c62018-08-07 19:50:45 +08001808 void handleUidRulesChanged(int uid, int newRules) {
1809 // skip update when we've already applied rules
1810 final int oldRules = mUidRules.get(uid, RULE_NONE);
1811 if (oldRules == newRules) return;
1812
1813 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1814
1815 if (newRules == RULE_NONE) {
1816 mUidRules.delete(uid);
1817 } else {
1818 mUidRules.put(uid, newRules);
1819 }
1820 }
1821
1822 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1823 if (mRestrictBackground == restrictBackground) return;
1824
1825 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1826 final boolean curMetered = nai.networkCapabilities.isMetered();
1827 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1828 restrictBackground);
1829 }
1830
1831 mRestrictBackground = restrictBackground;
1832 }
1833
1834 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1835 boolean isBackgroundRestricted) {
1836 synchronized (mVpns) {
1837 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1838 // Because the return value of this function depends on the list of UIDs the
1839 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1840 // list all state depending on the return value of this function has to be recomputed.
1841 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1842 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001843 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001844 return true;
1845 }
1846 }
1847
1848 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1849 isNetworkMetered, isBackgroundRestricted);
1850 }
1851
Robin Lee3b3dd942015-05-12 18:14:58 +01001852 /**
1853 * Require that the caller is either in the same user or has appropriate permission to interact
1854 * across users.
1855 *
1856 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1857 */
1858 private void enforceCrossUserPermission(int userId) {
1859 if (userId == UserHandle.getCallingUserId()) {
1860 // Not a cross-user call.
1861 return;
1862 }
1863 mContext.enforceCallingOrSelfPermission(
1864 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1865 "ConnectivityService");
1866 }
1867
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001868 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001869 for (String permission : permissions) {
1870 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001871 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001872 }
1873 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001874 return false;
1875 }
1876
1877 private void enforceAnyPermissionOf(String... permissions) {
1878 if (!checkAnyPermissionOf(permissions)) {
1879 throw new SecurityException("Requires one of the following permissions: "
1880 + String.join(", ", permissions) + ".");
1881 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001882 }
1883
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001884 private void enforceInternetPermission() {
1885 mContext.enforceCallingOrSelfPermission(
1886 android.Manifest.permission.INTERNET,
1887 "ConnectivityService");
1888 }
1889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001891 mContext.enforceCallingOrSelfPermission(
1892 android.Manifest.permission.ACCESS_NETWORK_STATE,
1893 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
1896 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001897 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 }
1899
Charles He36738632017-05-15 17:07:18 +01001900 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001901 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001902 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001903 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001904 }
1905
Chalard Jeanb552c462018-02-21 18:43:54 +09001906 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001907 return checkAnyPermissionOf(
1908 android.Manifest.permission.NETWORK_SETTINGS,
1909 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001910 }
1911
1912 private boolean checkSettingsPermission(int pid, int uid) {
1913 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001914 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1915 || PERMISSION_GRANTED == mContext.checkPermission(
1916 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001917 }
1918
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001919 private void enforceTetherAccessPermission() {
1920 mContext.enforceCallingOrSelfPermission(
1921 android.Manifest.permission.ACCESS_NETWORK_STATE,
1922 "ConnectivityService");
1923 }
1924
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001925 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001926 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001927 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001928 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001929 }
1930
Pavel Grafova462bcb2019-01-25 08:50:06 +00001931 private void enforceControlAlwaysOnVpnPermission() {
1932 mContext.enforceCallingOrSelfPermission(
1933 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1934 "ConnectivityService");
1935 }
1936
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001937 private void enforceNetworkStackSettingsOrSetup() {
1938 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001939 android.Manifest.permission.NETWORK_SETTINGS,
1940 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001941 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001942 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001943 }
1944
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001945 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001946 return checkAnyPermissionOf(
1947 android.Manifest.permission.NETWORK_STACK,
1948 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001949 }
1950
Hugo Benichi514da602016-07-19 15:59:27 +09001951 private void enforceConnectivityRestrictedNetworksPermission() {
1952 try {
1953 mContext.enforceCallingOrSelfPermission(
1954 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1955 "ConnectivityService");
1956 return;
1957 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1958 enforceConnectivityInternalPermission();
1959 }
1960
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001961 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001962 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001963 }
1964
Lorenzo Colitti18660282016-07-04 12:55:44 +09001965 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001966 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001967 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001968 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001969 }
1970
1971 private void sendInetConditionBroadcast(NetworkInfo info) {
1972 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1973 }
1974
Wink Saville628b0852011-08-04 15:01:58 -07001975 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001976 synchronized (mVpns) {
1977 if (mLockdownTracker != null) {
1978 info = new NetworkInfo(info);
1979 mLockdownTracker.augmentNetworkInfo(info);
1980 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001981 }
1982
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001983 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001984 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001985 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 if (info.isFailover()) {
1987 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1988 info.setFailover(false);
1989 }
1990 if (info.getReason() != null) {
1991 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1992 }
1993 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001994 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1995 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001997 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001998 return intent;
1999 }
2000
2001 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2002 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2003 }
2004
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002005 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002006 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2007 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2008 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002009 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002010 final long ident = Binder.clearCallingIdentity();
2011 try {
2012 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2013 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002017 }
2018
Mike Lockwood0f79b542009-08-14 14:18:49 -04002019 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002020 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002021 if (!mSystemReady
2022 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002023 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002024 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002025 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002026 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002027 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002028 }
2029
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002030 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002031 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002032 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002033 final NetworkInfo ni = intent.getParcelableExtra(
2034 ConnectivityManager.EXTRA_NETWORK_INFO);
2035 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2036 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2037 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002038 } else {
2039 BroadcastOptions opts = BroadcastOptions.makeBasic();
2040 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2041 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002042 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002043 final IBatteryStats bs = BatteryStatsService.getService();
2044 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002045 bs.noteConnectivityChanged(intent.getIntExtra(
2046 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002047 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002048 } catch (RemoteException e) {
2049 }
Chad Brubakerac925012018-03-08 10:37:09 -08002050 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002051 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002052 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002053 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002054 } finally {
2055 Binder.restoreCallingIdentity(ident);
2056 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002057 }
2058 }
2059
2060 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002061 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002062 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002063 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002064
Hugo Benichi20035e02017-04-26 14:53:28 +09002065 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002066 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002067 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002068 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002069 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002070 }
2071 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002072
Robin Lee244ce8e2016-01-05 18:03:46 +00002073 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2074 // for user to unlock device too.
2075 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002076
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002077 // Create network requests for always-on networks.
2078 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002079
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002080 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002081
2082 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002086 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002087 *
2088 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002089 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002090 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002091 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2092 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002093
2094 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002095 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002096
Robert Greenwalt7b816022014-04-18 15:25:25 -07002097 if (networkAgent.networkCapabilities.hasTransport(
2098 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002099 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2100 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002101 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002102 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 } else if (networkAgent.networkCapabilities.hasTransport(
2104 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002105 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2106 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002107 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002108 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002109 } else {
2110 // do not track any other networks
2111 timeout = 0;
2112 }
2113
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002115 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002116 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002117 } catch (Exception e) {
2118 // You shall not crash!
2119 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002120 }
2121 }
2122 }
2123
2124 /**
2125 * Remove data activity tracking when network disconnects.
2126 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2128 final String iface = networkAgent.linkProperties.getInterfaceName();
2129 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002130
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2132 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002133 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002134 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002135 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002136 } catch (Exception e) {
2137 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002138 }
2139 }
2140 }
2141
2142 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002143 * Update data activity tracking when network state is updated.
2144 */
2145 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2146 NetworkAgentInfo oldNetwork) {
2147 if (newNetwork != null) {
2148 setupDataActivityTracking(newNetwork);
2149 }
2150 if (oldNetwork != null) {
2151 removeDataActivityTracking(oldNetwork);
2152 }
2153 }
2154 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002155 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002156 * and set it on it's iface.
2157 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002158 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2159 final String iface = newLp.getInterfaceName();
2160 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002161 if (oldLp == null && mtu == 0) {
2162 // Silently ignore unset MTU value.
2163 return;
2164 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002165 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2166 if (VDBG) log("identical MTU - not setting");
2167 return;
2168 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002169 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002170 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002171 return;
2172 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002173
w1997615afd812014-08-05 15:18:11 -07002174 // Cannot set MTU without interface name
2175 if (TextUtils.isEmpty(iface)) {
2176 loge("Setting MTU size with null iface.");
2177 return;
2178 }
2179
Robert Greenwalt7b816022014-04-18 15:25:25 -07002180 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002181 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002182 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002183 } catch (Exception e) {
2184 Slog.e(TAG, "exception in setMtu()" + e);
2185 }
2186 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002187
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002188 @VisibleForTesting
2189 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002190 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2191
2192 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002193 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002194 protected MockableSystemProperties getSystemProperties() {
2195 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002196 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002197
lucaslin041a1af2018-11-28 19:27:52 +08002198 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002199 String[] values = null;
2200 if (tcpBufferSizes != null) {
2201 values = tcpBufferSizes.split(",");
2202 }
2203
2204 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002205 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002206 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2207 values = tcpBufferSizes.split(",");
2208 }
2209
2210 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2211
2212 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002213 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002214
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002215 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2216 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2217 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002218 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002219 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002220 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002221 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002222
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002223 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002224 Settings.Global.TCP_DEFAULT_INIT_RWND,
2225 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002226 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2227 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002228 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002229 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002230 }
2231
Robert Greenwalt562cc542014-05-15 18:07:26 -07002232 @Override
2233 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002234 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002235 NETWORK_RESTORE_DELAY_PROP_NAME);
2236 if(restoreDefaultNetworkDelayStr != null &&
2237 restoreDefaultNetworkDelayStr.length() != 0) {
2238 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002239 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002240 } catch (NumberFormatException e) {
2241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002243 // if the system property isn't set, use the value for the apn type
2244 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2245
2246 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2247 (mNetConfigs[networkType] != null)) {
2248 ret = mNetConfigs[networkType].restoreTime;
2249 }
2250 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 }
2252
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002253 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2254 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2255 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002256 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002257 // Start gathering diagnostic information.
2258 netDiags.add(new NetworkDiagnostics(
2259 nai.network,
2260 new LinkProperties(nai.linkProperties), // Must be a copy.
2261 DIAG_TIME_MS));
2262 }
2263
2264 for (NetworkDiagnostics netDiag : netDiags) {
2265 pw.println();
2266 netDiag.waitForMeasurements();
2267 netDiag.dump(pw);
2268 }
2269 }
2270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002272 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002273 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2274 }
2275
2276 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002277 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002278 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002279 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002280
Erik Kline3f8306b2018-05-01 16:51:44 +09002281 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002282 dumpNetworkDiagnostics(pw);
2283 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002284 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002285 mTethering.dump(fd, pw, args);
2286 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002287 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2288 dumpNetworks(pw);
2289 return;
2290 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2291 dumpNetworkRequests(pw);
2292 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002293 }
Erik Kline379747a2015-06-05 17:47:34 +09002294
Lorenzo Colittie3805462015-06-03 11:18:24 +09002295 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002296 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002297 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002298 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002299 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002300 pw.println();
2301
Paul Jensen85cf78e2015-06-25 13:25:07 -04002302 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002303 pw.print("Active default network: ");
2304 if (defaultNai == null) {
2305 pw.println("none");
2306 } else {
2307 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002309 pw.println();
2310
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002311 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002312 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002313 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002314 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002315 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002316
junyulai05986c62018-08-07 19:50:45 +08002317 pw.print("Restrict background: ");
2318 pw.println(mRestrictBackground);
2319 pw.println();
2320
2321 pw.println("Status for known UIDs:");
2322 pw.increaseIndent();
2323 final int size = mUidRules.size();
2324 for (int i = 0; i < size; i++) {
2325 // Don't crash if the array is modified while dumping in bugreports.
2326 try {
2327 final int uid = mUidRules.keyAt(i);
2328 final int uidRules = mUidRules.get(uid, RULE_NONE);
2329 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2330 } catch (ArrayIndexOutOfBoundsException e) {
2331 pw.println(" ArrayIndexOutOfBoundsException");
2332 } catch (ConcurrentModificationException e) {
2333 pw.println(" ConcurrentModificationException");
2334 }
2335 }
2336 pw.println();
2337 pw.decreaseIndent();
2338
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002339 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002340 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002341 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002342 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002343 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002344
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002345 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002346
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002347 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002348 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002349
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002350 pw.println();
2351 mKeepaliveTracker.dump(pw);
2352
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002353 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002354 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002355
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002356 pw.println();
2357 mMultipathPolicyTracker.dump(pw);
2358
Erik Kline3f8306b2018-05-01 16:51:44 +09002359 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002360 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002361 pw.println("mNetworkRequestInfoLogs (most recent first):");
2362 pw.increaseIndent();
2363 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2364 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002365
2366 pw.println();
2367 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2368 pw.increaseIndent();
2369 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2370 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002371
2372 pw.println();
2373 pw.println("NetTransition WakeLock activity (most recent first):");
2374 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002375 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2376 pw.println("total releases: " + mTotalWakelockReleases);
2377 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2378 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2379 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2380 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2381 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2382 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002383 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002384
2385 pw.println();
2386 pw.println("bandwidth update requests (by uid):");
2387 pw.increaseIndent();
2388 synchronized (mBandwidthRequests) {
2389 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2390 pw.println("[" + mBandwidthRequests.keyAt(i)
2391 + "]: " + mBandwidthRequests.valueAt(i));
2392 }
2393 }
2394 pw.decreaseIndent();
2395
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002396 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002397 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002398
2399 pw.println();
2400 pw.println("NetworkStackClient logs:");
2401 pw.increaseIndent();
2402 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404
Hugo Benichi14683812018-09-03 08:32:56 +09002405 private void dumpNetworks(IndentingPrintWriter pw) {
2406 for (NetworkAgentInfo nai : networksSortedById()) {
2407 pw.println(nai.toString());
2408 pw.increaseIndent();
2409 pw.println(String.format(
2410 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2411 nai.numForegroundNetworkRequests(),
2412 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2413 nai.numBackgroundNetworkRequests(),
2414 nai.numNetworkRequests()));
2415 pw.increaseIndent();
2416 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2417 pw.println(nai.requestAt(i).toString());
2418 }
2419 pw.decreaseIndent();
2420 pw.println("Lingered:");
2421 pw.increaseIndent();
2422 nai.dumpLingerTimers(pw);
2423 pw.decreaseIndent();
2424 pw.decreaseIndent();
2425 }
2426 }
2427
2428 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2429 for (NetworkRequestInfo nri : requestsSortedById()) {
2430 pw.println(nri.toString());
2431 }
2432 }
2433
Hugo Benichia2a917c2018-09-03 08:19:02 +09002434 /**
2435 * Return an array of all current NetworkAgentInfos sorted by network id.
2436 */
2437 private NetworkAgentInfo[] networksSortedById() {
2438 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2439 networks = mNetworkAgentInfos.values().toArray(networks);
2440 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2441 return networks;
2442 }
2443
2444 /**
2445 * Return an array of all current NetworkRequest sorted by request id.
2446 */
2447 private NetworkRequestInfo[] requestsSortedById() {
2448 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2449 requests = mNetworkRequests.values().toArray(requests);
2450 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2451 return requests;
2452 }
2453
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002454 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002455 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002456 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002457 if (officialNai != null && officialNai.equals(nai)) return true;
2458 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002459 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002460 " - " + nai);
2461 }
2462 return false;
2463 }
2464
Robert Greenwalt42acef32009-08-12 16:08:25 -07002465 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002466 private class NetworkStateTrackerHandler extends Handler {
2467 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002468 super(looper);
2469 }
2470
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002471 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002473 default:
2474 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002475 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002476 handleAsyncChannelHalfConnect(msg);
2477 break;
2478 }
2479 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2480 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2481 if (nai != null) nai.asyncChannel.disconnect();
2482 break;
2483 }
2484 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2485 handleAsyncChannelDisconnected(msg);
2486 break;
2487 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002488 }
2489 return true;
2490 }
2491
2492 private void maybeHandleNetworkAgentMessage(Message msg) {
2493 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2494 if (nai == null) {
2495 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002496 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002497 }
2498 return;
2499 }
2500
2501 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002502 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002503 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002504 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002505 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002506 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002507 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002508 break;
2509 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002510 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002511 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002512 break;
2513 }
2514 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002515 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002516 updateNetworkInfo(nai, info);
2517 break;
2518 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002519 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002520 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002521 break;
2522 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002523 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002524 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2525 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002526 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002527 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002528 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002529 // Mark the network as temporarily accepting partial connectivity so that it
2530 // will be validated (and possibly become default) even if it only provides
2531 // partial internet access. Note that if user connects to partial connectivity
2532 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2533 // out of wifi coverage) and if the same wifi is available again, the device
2534 // will auto connect to this wifi even though the wifi has "no internet".
2535 // TODO: Evaluate using a separate setting in IpMemoryStore.
2536 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002537 break;
2538 }
junyulai06835112019-01-03 18:50:15 +08002539 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2540 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002541 break;
2542 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002543 }
2544 }
2545
2546 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2547 switch (msg.what) {
2548 default:
2549 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002550 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002551 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002552 if (nai == null) break;
2553
lucasline252a742019-03-12 13:08:03 +08002554 final boolean partialConnectivity =
2555 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
2556 // If user accepts partial connectivity network, NetworkMonitor
2557 // will skip https probing. It will make partial connectivity
2558 // network becomes valid. But user still need to know this
2559 // network is limited. So, it's needed to refer to
2560 // acceptPartialConnectivity to add
2561 // NET_CAPABILITY_PARTIAL_CONNECTIVITY into NetworkCapabilities
2562 // of this network. So that user can see "Limited connection"
2563 // in the settings.
2564 || (nai.networkMisc.acceptPartialConnectivity
2565 && nai.partialConnectivity);
2566 // Once a network is determined to have partial connectivity, it cannot
2567 // go back to full connectivity without a disconnect.
2568 final boolean partialConnectivityChange =
2569 (partialConnectivity && !nai.partialConnectivity);
2570
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002571 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002572 final boolean wasValidated = nai.lastValidated;
2573 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002574 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2575 && valid) {
2576 nai.captivePortalLoginNotified = true;
2577 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2578 }
lucasline252a742019-03-12 13:08:03 +08002579 // If this network has just connected and partial connectivity has just been
2580 // detected, tell NetworkMonitor if the user accepted partial connectivity on a
2581 // previous connect.
2582 if ((msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
2583 && nai.networkMisc.acceptPartialConnectivity) {
2584 try {
2585 nai.networkMonitor().notifyAcceptPartialConnectivity();
2586 } catch (RemoteException e) {
2587 e.rethrowFromSystemServer();
2588 }
2589 }
Erik Klinea24d4592018-01-11 21:07:29 +09002590
Erik Klinea24d4592018-01-11 21:07:29 +09002591 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2592
Erik Klinea24d4592018-01-11 21:07:29 +09002593 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002594 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2595 ? " with redirect to " + redirectUrl
2596 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002597 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2598 }
Erik Klinea24d4592018-01-11 21:07:29 +09002599 if (valid != nai.lastValidated) {
2600 if (wasDefault) {
2601 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2602 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002603 }
Erik Klinea24d4592018-01-11 21:07:29 +09002604 final int oldScore = nai.getCurrentScore();
2605 nai.lastValidated = valid;
2606 nai.everValidated |= valid;
2607 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2608 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2609 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002610 if (valid) {
2611 handleFreshlyValidatedNetwork(nai);
2612 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2613 // valid.
2614 mNotifier.clearNotification(nai.network.netId,
2615 NotificationType.NO_INTERNET);
2616 mNotifier.clearNotification(nai.network.netId,
2617 NotificationType.LOST_INTERNET);
2618 }
lucasline252a742019-03-12 13:08:03 +08002619 } else if (partialConnectivityChange) {
2620 nai.partialConnectivity = partialConnectivity;
2621 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002622 }
2623 updateInetCondition(nai);
2624 // Let the NetworkAgent know the state of its network
2625 Bundle redirectUrlBundle = new Bundle();
2626 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2627 nai.asyncChannel.sendMessage(
2628 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2629 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2630 0, redirectUrlBundle);
2631 if (wasValidated && !nai.lastValidated) {
2632 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002633 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002634 break;
2635 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002636 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002637 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002638 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002639 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002640 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002641 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002642 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002643 nai.lastCaptivePortalDetected = visible;
2644 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002645 if (visible) {
2646 nai.captivePortalLoginNotified = false;
2647 }
Calvin Onbe96da12016-10-11 15:10:46 -07002648 if (nai.lastCaptivePortalDetected &&
2649 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2650 if (DBG) log("Avoiding captive portal network: " + nai.name());
2651 nai.asyncChannel.sendMessage(
2652 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2653 teardownUnneededNetwork(nai);
2654 break;
2655 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002656 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002657 }
2658 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002659 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002660 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002661 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2662 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002663 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002664 if (nai == null) {
2665 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2666 break;
2667 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002668 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002669 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002670 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002671 }
Paul Jensen869868be2014-05-15 10:33:05 -04002672 }
Paul Jensen869868be2014-05-15 10:33:05 -04002673 break;
2674 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002675 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002676 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002677 if (nai == null) break;
2678
Erik Kline736353a2018-03-21 07:18:33 -07002679 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002680 break;
2681 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002682 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002683 return true;
2684 }
2685
Calvin Onbe96da12016-10-11 15:10:46 -07002686 private int getCaptivePortalMode() {
2687 return Settings.Global.getInt(mContext.getContentResolver(),
2688 Settings.Global.CAPTIVE_PORTAL_MODE,
2689 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2690 }
2691
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002692 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2693 switch (msg.what) {
2694 default:
2695 return false;
2696 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2697 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2698 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2699 handleLingerComplete(nai);
2700 }
2701 break;
2702 }
2703 }
2704 return true;
2705 }
2706
Etan Cohenddb720a2019-01-08 12:09:18 -08002707 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2708 switch (msg.what) {
2709 default:
2710 return false;
2711 case android.net.NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2712 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2713 /* callOnUnavailable */ true);
2714 break;
2715 }
2716 }
2717 return true;
2718 }
2719
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002720 @Override
2721 public void handleMessage(Message msg) {
Etan Cohenddb720a2019-01-08 12:09:18 -08002722 if (!maybeHandleAsyncChannelMessage(msg)
2723 && !maybeHandleNetworkMonitorMessage(msg)
2724 && !maybeHandleNetworkAgentInfoMessage(msg)
2725 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002726 maybeHandleNetworkAgentMessage(msg);
2727 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002728 }
2729 }
2730
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002731 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2732 private final NetworkAgentInfo mNai;
2733
2734 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2735 mNai = nai;
2736 }
2737
2738 @Override
2739 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2741 new Pair<>(mNai, networkMonitor)));
2742 }
2743
2744 @Override
2745 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2746 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2747 testResult, mNai.network.netId, redirectUrl));
2748 }
2749
2750 @Override
2751 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2752 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2753 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2754 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2755 }
2756
2757 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002758 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002759 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002760 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002761
2762 final PendingIntent pendingIntent;
2763 // Only the system server can register notifications with package "android"
2764 final long token = Binder.clearCallingIdentity();
2765 try {
2766 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2767 } finally {
2768 Binder.restoreCallingIdentity(token);
2769 }
2770 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2771 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2772 mNai.network.netId,
2773 pendingIntent));
2774 }
2775
2776 @Override
2777 public void hideProvisioningNotification() {
2778 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2779 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2780 mNai.network.netId));
2781 }
2782 }
2783
Erik Kline736353a2018-03-21 07:18:33 -07002784 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002785 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002786 }
2787
Erik Klinec6d00222018-06-26 18:53:43 +09002788 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2789 if (nai == null) return;
2790 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2791 // in order to restart a validation pass from within netd.
2792 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2793 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2794 updateDnses(nai.linkProperties, null, nai.network.netId);
2795 }
2796 }
2797
Erik Klinea24d4592018-01-11 21:07:29 +09002798 private void handlePrivateDnsSettingsChanged() {
2799 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2800
2801 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002802 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002803 if (networkRequiresValidation(nai)) {
2804 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2805 }
Erik Klinea24d4592018-01-11 21:07:29 +09002806 }
2807 }
2808
Erik Kline736353a2018-03-21 07:18:33 -07002809 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2810 // Private DNS only ever applies to networks that might provide
2811 // Internet access and therefore also require validation.
2812 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002813
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002814 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002815 // schedule DNS resolutions. If a DNS resolution is required the
2816 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002817 try {
2818 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2819 } catch (RemoteException e) {
2820 e.rethrowFromSystemServer();
2821 }
Erik Kline736353a2018-03-21 07:18:33 -07002822
2823 // With Private DNS bypass support, we can proceed to update the
2824 // Private DNS config immediately, even if we're in strict mode
2825 // and have not yet resolved the provider name into a set of IPs.
2826 updatePrivateDns(nai, cfg);
2827 }
2828
2829 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2830 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002831 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002832 }
2833
dalyk7301aa42018-03-05 12:42:22 -05002834 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2835 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2836 if (nai == null) {
2837 return;
2838 }
2839 mDnsManager.updatePrivateDnsValidation(update);
2840 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2841 }
2842
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002843 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2844 int prefixLength) {
2845 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2846 if (nai == null) return;
2847
2848 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2849 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2850
2851 IpPrefix prefix = null;
2852 if (added) {
2853 try {
2854 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2855 prefixLength);
2856 } catch (IllegalArgumentException e) {
2857 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2858 return;
2859 }
2860 }
2861
2862 nai.clatd.setNat64Prefix(prefix);
2863 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2864 }
2865
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002866 private void updateLingerState(NetworkAgentInfo nai, long now) {
2867 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2868 // 2. If the network was lingering and there are now requests, unlinger it.
2869 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2870 // one lingered request, start lingering.
2871 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002872 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002873 if (DBG) log("Unlingering " + nai.name());
2874 nai.unlinger();
2875 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002876 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002877 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002878 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002879 nai.linger();
2880 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2881 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2882 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002883 }
2884
Robert Greenwalt7b816022014-04-18 15:25:25 -07002885 private void handleAsyncChannelHalfConnect(Message msg) {
2886 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002887 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002888 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2889 if (VDBG) log("NetworkFactory connected");
Etan Cohenddb720a2019-01-08 12:09:18 -08002890 // Finish setting up the full connection
2891 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2892 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002893 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002894 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002895 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002896 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09002897 final int score;
2898 final int serial;
2899 if (nai != null) {
2900 score = nai.getCurrentScore();
2901 serial = nai.factorySerialNumber;
2902 } else {
2903 score = 0;
2904 serial = NetworkFactory.SerialNumber.NONE;
2905 }
2906 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2907 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002908 }
2909 } else {
2910 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002911 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002912 }
2913 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2914 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2915 if (VDBG) log("NetworkAgent connected");
2916 // A network agent has requested a connection. Establish the connection.
2917 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2918 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2919 } else {
2920 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002921 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002922 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002923 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002924 synchronized (mNetworkForNetId) {
2925 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002926 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002927 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002928 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002929 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002930 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002931 }
2932 }
2933 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002934
Chalard Jean392971c2018-05-11 20:19:20 +09002935 // This is a no-op if it's called with a message designating a network that has
2936 // already been destroyed, because its reference will not be found in the relevant
2937 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002938 private void handleAsyncChannelDisconnected(Message msg) {
2939 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2940 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002941 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002942 } else {
2943 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2944 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002945 }
2946 }
2947
Chalard Jean392971c2018-05-11 20:19:20 +09002948 // Destroys a network, remove references to it from the internal state managed by
2949 // ConnectivityService, free its interfaces and clean up.
2950 // Must be called on the Handler thread.
2951 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2952 if (DBG) {
2953 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2954 }
lucaslinf80b83b2019-02-12 15:30:13 +08002955 // Clear all notifications of this network.
2956 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002957 // A network agent has disconnected.
2958 // TODO - if we move the logic to the network agent (have them disconnect
2959 // because they lost all their requests or because their score isn't good)
2960 // then they would disconnect organically, report their new state and then
2961 // disconnect the channel.
2962 if (nai.networkInfo.isConnected()) {
2963 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2964 null, null);
2965 }
2966 final boolean wasDefault = isDefaultNetwork(nai);
2967 if (wasDefault) {
2968 mDefaultInetConditionPublished = 0;
2969 // Log default network disconnection before required book-keeping.
2970 // Let rematchAllNetworksAndRequests() below record a new default network event
2971 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2972 // whose timestamps tell how long it takes to recover a default network.
2973 long now = SystemClock.elapsedRealtime();
2974 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2975 }
2976 notifyIfacesChangedForNetworkStats();
2977 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2978 // by other networks that are already connected. Perhaps that can be done by
2979 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2980 // of rematchAllNetworksAndRequests
2981 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai06835112019-01-03 18:50:15 +08002982 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002983 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2984 // Disable wakeup packet monitoring for each interface.
2985 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2986 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002987 try {
2988 nai.networkMonitor().notifyNetworkDisconnected();
2989 } catch (RemoteException e) {
2990 e.rethrowFromSystemServer();
2991 }
Chalard Jean392971c2018-05-11 20:19:20 +09002992 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09002993 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09002994 synchronized (mNetworkForNetId) {
2995 // Remove the NetworkAgent, but don't mark the netId as
2996 // available until we've told netd to delete it below.
2997 mNetworkForNetId.remove(nai.network.netId);
2998 }
2999 // Remove all previously satisfied requests.
3000 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3001 NetworkRequest request = nai.requestAt(i);
3002 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
3003 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3004 clearNetworkForRequest(request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09003005 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003006 }
3007 }
3008 nai.clearLingerState();
3009 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003010 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003011 notifyLockdownVpn(nai);
3012 ensureNetworkTransitionWakelock(nai.name());
3013 }
3014 mLegacyTypeTracker.remove(nai, wasDefault);
3015 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3016 updateAllVpnsCapabilities();
3017 }
3018 rematchAllNetworksAndRequests(null, 0);
3019 mLingerMonitor.noteDisconnect(nai);
3020 if (nai.created) {
3021 // Tell netd to clean up the configuration for this network
3022 // (routing rules, DNS, etc).
3023 // This may be slow as it requires a lot of netd shelling out to ip and
3024 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3025 // after we've rematched networks with requests which should make a potential
3026 // fallback network the default or requested a new network from the
3027 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3028 // long time.
3029 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08003030 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003031 } catch (Exception e) {
3032 loge("Exception removing network: " + e);
3033 }
3034 mDnsManager.removeNetwork(nai.network);
3035 }
3036 synchronized (mNetworkForNetId) {
3037 mNetIdInUse.delete(nai.network.netId);
3038 }
3039 }
3040
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003041 // If this method proves to be too slow then we can maintain a separate
3042 // pendingIntent => NetworkRequestInfo map.
3043 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3044 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3045 Intent intent = pendingIntent.getIntent();
3046 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3047 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3048 if (existingPendingIntent != null &&
3049 existingPendingIntent.getIntent().filterEquals(intent)) {
3050 return entry.getValue();
3051 }
3052 }
3053 return null;
3054 }
3055
3056 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3057 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3058
3059 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3060 if (existingRequest != null) { // remove the existing request.
3061 if (DBG) log("Replacing " + existingRequest.request + " with "
3062 + nri.request + " because their intents matched.");
Etan Cohenddb720a2019-01-08 12:09:18 -08003063 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3064 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003065 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003066 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003067 }
3068
Erik Klineda4bfa82015-04-30 12:58:40 +09003069 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003070 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003071 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003072 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003073 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003074 if (nri.request.networkCapabilities.hasSignalStrength() &&
3075 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3076 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003077 }
3078 }
3079 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003080 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003081 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003082 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003083 }
3084 }
3085
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003086 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3087 int callingUid) {
3088 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3089 if (nri != null) {
Etan Cohenddb720a2019-01-08 12:09:18 -08003090 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003091 }
3092 }
3093
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003094 // Determines whether the network is the best (or could become the best, if it validated), for
3095 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3096 // on the value of reason:
3097 //
3098 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3099 // then it should be torn down.
3100 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3101 // then it should be lingered.
3102 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3103 final int numRequests;
3104 switch (reason) {
3105 case TEARDOWN:
3106 numRequests = nai.numRequestNetworkRequests();
3107 break;
3108 case LINGER:
3109 numRequests = nai.numForegroundNetworkRequests();
3110 break;
3111 default:
3112 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3113 return true;
3114 }
3115
3116 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003117 return false;
3118 }
Paul Jensene0988542015-06-25 15:30:08 -04003119 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003120 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3121 // Background requests don't affect lingering.
3122 continue;
3123 }
3124
Paul Jensene0988542015-06-25 15:30:08 -04003125 // If this Network is already the highest scoring Network for a request, or if
3126 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003127 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003128 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003129 // Note that this catches two important cases:
3130 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3131 // is currently satisfying the request. This is desirable when
3132 // cellular ends up validating but WiFi does not.
3133 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003134 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003135 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003136 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003137 nai.getCurrentScoreAsValidated())) {
3138 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003139 }
3140 }
Paul Jensene0988542015-06-25 15:30:08 -04003141 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003142 }
3143
Erik Klineacdd6392016-07-07 16:50:58 +09003144 private NetworkRequestInfo getNriForAppRequest(
3145 NetworkRequest request, int callingUid, String requestedOperation) {
3146 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3147
Robert Greenwalt9258c642014-03-26 16:47:06 -07003148 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003149 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003150 log(String.format("UID %d attempted to %s for unowned request %s",
3151 callingUid, requestedOperation, nri));
3152 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003153 }
Erik Klineacdd6392016-07-07 16:50:58 +09003154 }
3155
3156 return nri;
3157 }
3158
Erik Kline57faba92015-11-25 12:49:38 +09003159 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003160 if (mNetworkRequests.get(nri.request) == null) {
3161 return;
Erik Kline57faba92015-11-25 12:49:38 +09003162 }
Hugo Benichicd952782017-09-20 11:20:14 +09003163 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003164 return;
3165 }
3166 if (VDBG || (DBG && nri.request.isRequest())) {
3167 log("releasing " + nri.request + " (timeout)");
3168 }
3169 handleRemoveNetworkRequest(nri);
3170 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003171 }
3172
Etan Cohenddb720a2019-01-08 12:09:18 -08003173 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3174 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003175 final NetworkRequestInfo nri =
3176 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3177 if (nri == null) {
3178 return;
Erik Kline57faba92015-11-25 12:49:38 +09003179 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003180 if (VDBG || (DBG && nri.request.isRequest())) {
3181 log("releasing " + nri.request + " (release request)");
3182 }
3183 handleRemoveNetworkRequest(nri);
Etan Cohenddb720a2019-01-08 12:09:18 -08003184 if (callOnUnavailable) {
3185 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3186 }
Erik Kline57faba92015-11-25 12:49:38 +09003187 }
Erik Klineacdd6392016-07-07 16:50:58 +09003188
Hugo Benichidba33db2017-03-23 22:40:44 +09003189 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003190 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003191 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003192
Erik Klineacdd6392016-07-07 16:50:58 +09003193 synchronized (mUidToNetworkRequestCount) {
3194 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3195 if (requests < 1) {
3196 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3197 nri.mUid);
3198 } else if (requests == 1) {
3199 mUidToNetworkRequestCount.removeAt(
3200 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3201 } else {
3202 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3203 }
3204 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003205
Erik Klineacdd6392016-07-07 16:50:58 +09003206 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3207 if (nri.request.isRequest()) {
3208 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003209 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003210 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003211 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003212 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003213 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003214 log(" Removing from current network " + nai.name() +
3215 ", leaving " + nai.numNetworkRequests() + " requests.");
3216 }
3217 // If there are still lingered requests on this network, don't tear it down,
3218 // but resume lingering instead.
3219 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003220 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003221 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3222 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003223 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003224 wasKept = true;
3225 }
Hugo Benichicd952782017-09-20 11:20:14 +09003226 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003227 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3228 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003229 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003230 }
Erik Klineacdd6392016-07-07 16:50:58 +09003231 }
3232
Erik Klineacdd6392016-07-07 16:50:58 +09003233 // Maintain the illusion. When this request arrived, we might have pretended
3234 // that a network connected to serve it, even though the network was already
3235 // connected. Now that this request has gone away, we might have to pretend
3236 // that the network disconnected. LegacyTypeTracker will generate that
3237 // phantom disconnect for this type.
3238 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3239 boolean doRemove = true;
3240 if (wasKept) {
3241 // check if any of the remaining requests for this network are for the
3242 // same legacy type - if so, don't remove the nai
3243 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3244 NetworkRequest otherRequest = nai.requestAt(i);
3245 if (otherRequest.legacyType == nri.request.legacyType &&
3246 otherRequest.isRequest()) {
3247 if (DBG) log(" still have other legacy request - leaving");
3248 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003249 }
3250 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003251 }
3252
Erik Klineacdd6392016-07-07 16:50:58 +09003253 if (doRemove) {
3254 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003255 }
3256 }
Erik Klineacdd6392016-07-07 16:50:58 +09003257
3258 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3259 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3260 nri.request);
3261 }
3262 } else {
3263 // listens don't have a singular affectedNetwork. Check all networks to see
3264 // if this listen request applies and remove it.
3265 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3266 nai.removeRequest(nri.request.requestId);
3267 if (nri.request.networkCapabilities.hasSignalStrength() &&
3268 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3269 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3270 }
3271 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003272 }
3273 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003274
Lorenzo Colitti18660282016-07-04 12:55:44 +09003275 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003276 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003277 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003278 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003279 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003280 }
3281
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003282 @Override
lucasline252a742019-03-12 13:08:03 +08003283 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3284 enforceNetworkStackSettingsOrSetup();
3285 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3286 encodeBool(accept), encodeBool(always), network));
3287 }
3288
3289 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003290 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003291 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003292 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3293 }
3294
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003295 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3296 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3297 " accept=" + accept + " always=" + always);
3298
3299 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3300 if (nai == null) {
3301 // Nothing to do.
3302 return;
3303 }
3304
3305 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003306 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003307 return;
3308 }
3309
3310 if (!nai.networkMisc.explicitlySelected) {
3311 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3312 }
3313
3314 if (accept != nai.networkMisc.acceptUnvalidated) {
3315 int oldScore = nai.getCurrentScore();
3316 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003317 // If network becomes partial connectivity and user already accepted to use this
3318 // network, we should respect the user's option and don't need to popup the
3319 // PARTIAL_CONNECTIVITY notification to user again.
3320 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003321 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003322 sendUpdatedScoreToFactories(nai);
3323 }
3324
3325 if (always) {
3326 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003327 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003328 }
3329
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003330 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003331 // Tell the NetworkAgent to not automatically reconnect to the network.
3332 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003333 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003334 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003335 }
3336
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003337 }
3338
lucasline252a742019-03-12 13:08:03 +08003339 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3340 boolean always) {
3341 if (DBG) {
3342 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3343 + " always=" + always);
3344 }
3345
3346 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3347 if (nai == null) {
3348 // Nothing to do.
3349 return;
3350 }
3351
3352 if (nai.lastValidated) {
3353 // The network validated while the dialog box was up. Take no action.
3354 return;
3355 }
3356
3357 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3358 nai.networkMisc.acceptPartialConnectivity = accept;
3359 }
3360
3361 // TODO: Use the current design or save the user choice into IpMemoryStore.
3362 if (always) {
3363 nai.asyncChannel.sendMessage(
3364 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3365 }
3366
3367 if (!accept) {
3368 // Tell the NetworkAgent to not automatically reconnect to the network.
3369 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3370 // Tear down the network.
3371 teardownUnneededNetwork(nai);
3372 } else {
3373 try {
3374 nai.networkMonitor().notifyAcceptPartialConnectivity();
3375 } catch (RemoteException e) {
3376 e.rethrowFromSystemServer();
3377 }
3378 }
3379 }
3380
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003381 private void handleSetAvoidUnvalidated(Network network) {
3382 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3383 if (nai == null || nai.lastValidated) {
3384 // Nothing to do. The network either disconnected or revalidated.
3385 return;
3386 }
3387 if (!nai.avoidUnvalidated) {
3388 int oldScore = nai.getCurrentScore();
3389 nai.avoidUnvalidated = true;
3390 rematchAllNetworksAndRequests(nai, oldScore);
3391 sendUpdatedScoreToFactories(nai);
3392 }
3393 }
3394
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003395 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003396 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003397 mHandler.sendMessageDelayed(
3398 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3399 PROMPT_UNVALIDATED_DELAY_MS);
3400 }
3401
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003402 @Override
3403 public void startCaptivePortalApp(Network network) {
3404 enforceConnectivityInternalPermission();
3405 mHandler.post(() -> {
3406 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3407 if (nai == null) return;
3408 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003409 try {
3410 nai.networkMonitor().launchCaptivePortalApp();
3411 } catch (RemoteException e) {
3412 e.rethrowFromSystemServer();
3413 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003414 });
3415 }
3416
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003417 /**
3418 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3419 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003420 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003421 * @param appExtras Bundle to use as intent extras for the captive portal application.
3422 * Must be treated as opaque to avoid preventing the captive portal app to
3423 * update its arguments.
3424 */
3425 @Override
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003426 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003427 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3428
3429 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3430 appIntent.putExtras(appExtras);
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003431 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3432 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003433 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3434
3435 Binder.withCleanCallingIdentity(() ->
3436 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3437 }
3438
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003439 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3440 private final Network mNetwork;
3441
3442 private CaptivePortalImpl(Network network) {
3443 mNetwork = network;
3444 }
3445
3446 @Override
3447 public void appResponse(final int response) throws RemoteException {
3448 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3449 enforceSettingsPermission();
3450 }
3451
3452 // getNetworkAgentInfoForNetwork is thread-safe
3453 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3454 if (nai == null) return;
3455
3456 // nai.networkMonitor() is thread-safe
3457 final INetworkMonitor nm = nai.networkMonitor();
3458 if (nm == null) return;
3459
3460 final long token = Binder.clearCallingIdentity();
3461 try {
3462 nm.notifyCaptivePortalAppFinished(response);
3463 } finally {
3464 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3465 Binder.restoreCallingIdentity(token);
3466 }
3467 }
3468
3469 @Override
3470 public void logEvent(int eventId, String packageName) {
3471 enforceSettingsPermission();
3472
3473 new MetricsLogger().action(eventId, packageName);
3474 }
3475 }
3476
Hugo Benichic8e9e122016-09-14 23:23:08 +00003477 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003478 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003479 }
3480
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003481 @Override
3482 public boolean getAvoidBadWifi() {
3483 if (!checkNetworkStackPermission()) {
3484 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3485 }
3486 return avoidBadWifi();
3487 }
3488
3489
Erik Kline065ab6e2016-10-02 18:02:14 +09003490 private void rematchForAvoidBadWifiUpdate() {
3491 rematchAllNetworksAndRequests(null, 0);
3492 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3493 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3494 sendUpdatedScoreToFactories(nai);
3495 }
3496 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003497 }
3498
Erik Kline065ab6e2016-10-02 18:02:14 +09003499 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003500 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003501 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003502 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003503 if (!configRestrict) {
3504 pw.println("Bad Wi-Fi avoidance: unrestricted");
3505 return;
3506 }
3507
3508 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3509 pw.increaseIndent();
3510 pw.println("Config restrict: " + configRestrict);
3511
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003512 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003513 String description;
3514 // Can't use a switch statement because strings are legal case labels, but null is not.
3515 if ("0".equals(value)) {
3516 description = "get stuck";
3517 } else if (value == null) {
3518 description = "prompt";
3519 } else if ("1".equals(value)) {
3520 description = "avoid";
3521 } else {
3522 description = value + " (?)";
3523 }
3524 pw.println("User setting: " + description);
3525 pw.println("Network overrides:");
3526 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003527 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003528 if (nai.avoidUnvalidated) {
3529 pw.println(nai.name());
3530 }
3531 }
3532 pw.decreaseIndent();
3533 pw.decreaseIndent();
3534 }
3535
lucaslind2e045e02019-01-24 15:55:30 +08003536 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003537 final String action;
3538 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003539 case LOGGED_IN:
3540 action = Settings.ACTION_WIFI_SETTINGS;
3541 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3542 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3543 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3544 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003545 case NO_INTERNET:
3546 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3547 break;
3548 case LOST_INTERNET:
3549 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3550 break;
lucasline252a742019-03-12 13:08:03 +08003551 case PARTIAL_CONNECTIVITY:
3552 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3553 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003554 default:
3555 Slog.wtf(TAG, "Unknown notification type " + type);
3556 return;
3557 }
3558
3559 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003560 if (type != NotificationType.LOGGED_IN) {
3561 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3562 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3563 intent.setClassName("com.android.settings",
3564 "com.android.settings.wifi.WifiNoInternetDialog");
3565 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003566
3567 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3568 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3569 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3570 }
3571
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003572 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003573 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003574 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3575
lucasline252a742019-03-12 13:08:03 +08003576 // Only prompt if the network is unvalidated or network has partial internet connectivity
3577 // and was explicitly selected by the user, and if we haven't already been told to switch
3578 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3579 // because we're already prompting the user to sign in.
3580 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3581 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
3582 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003583 return;
3584 }
lucasline252a742019-03-12 13:08:03 +08003585 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3586 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3587 // popup the notification immediately when the network is partial connectivity.
3588 if (nai.partialConnectivity) {
3589 // Treat PARTIAL_CONNECTIVITY as NO_INTERNET temporary until Settings has been updated.
3590 // TODO: Need to change back to PARTIAL_CONNECTIVITY when Settings part is merged.
3591 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3592 } else {
3593 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3594 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003595 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003596
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003597 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3598 NetworkCapabilities nc = nai.networkCapabilities;
3599 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003600
lucasline252a742019-03-12 13:08:03 +08003601 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3602 return;
3603 }
3604
3605 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003606 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003607 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003608 }
3609
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003610 @Override
3611 public int getMultipathPreference(Network network) {
3612 enforceAccessPermission();
3613
3614 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003615 if (nai != null && nai.networkCapabilities
3616 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003617 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3618 }
3619
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003620 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3621 if (networkPreference != null) {
3622 return networkPreference;
3623 }
3624
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003625 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3626 }
3627
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003628 @Override
3629 public NetworkRequest getDefaultRequest() {
3630 return mDefaultRequest;
3631 }
3632
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003633 private class InternalHandler extends Handler {
3634 public InternalHandler(Looper looper) {
3635 super(looper);
3636 }
3637
3638 @Override
3639 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003640 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003641 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003642 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003643 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003644 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003645 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003646 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003647 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003648 break;
3649 }
Jason Monkdecd2952013-10-10 14:02:51 -04003650 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003651 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003652 break;
3653 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003654 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003655 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3656 break;
3657 }
3658 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3659 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003660 break;
3661 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003662 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003663 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3664 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3665 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003666 break;
3667 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003668 case EVENT_REGISTER_NETWORK_REQUEST:
3669 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003670 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003671 break;
3672 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003673 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3674 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003675 handleRegisterNetworkRequestWithIntent(msg);
3676 break;
3677 }
Erik Kline57faba92015-11-25 12:49:38 +09003678 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3679 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3680 handleTimedOutNetworkRequest(nri);
3681 break;
3682 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003683 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3684 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3685 break;
3686 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003687 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenddb720a2019-01-08 12:09:18 -08003688 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3689 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003690 break;
3691 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003692 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003693 Network network = (Network) msg.obj;
3694 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003695 break;
3696 }
lucasline252a742019-03-12 13:08:03 +08003697 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3698 Network network = (Network) msg.obj;
3699 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3700 toBool(msg.arg2));
3701 break;
3702 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003703 case EVENT_SET_AVOID_UNVALIDATED: {
3704 handleSetAvoidUnvalidated((Network) msg.obj);
3705 break;
3706 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003707 case EVENT_PROMPT_UNVALIDATED: {
3708 handlePromptUnvalidated((Network) msg.obj);
3709 break;
3710 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003711 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3712 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003713 break;
3714 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003715 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003716 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003717 mKeepaliveTracker.handleStartKeepalive(msg);
3718 break;
3719 }
3720 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003721 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003722 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3723 int slot = msg.arg1;
3724 int reason = msg.arg2;
3725 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3726 break;
3727 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003728 case EVENT_SYSTEM_READY: {
3729 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003730 // Might have been called already in handleRegisterNetworkAgent since
3731 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3732 // this several times is fine.
3733 try {
3734 nai.networkMonitor().notifySystemReady();
3735 } catch (RemoteException e) {
3736 e.rethrowFromSystemServer();
3737 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003738 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003739 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003740 break;
3741 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003742 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003743 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003744 break;
3745 }
Erik Klinea24d4592018-01-11 21:07:29 +09003746 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3747 handlePrivateDnsSettingsChanged();
3748 break;
dalyk7301aa42018-03-05 12:42:22 -05003749 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3750 handlePrivateDnsValidationUpdate(
3751 (PrivateDnsValidationUpdate) msg.obj);
3752 break;
junyulai05986c62018-08-07 19:50:45 +08003753 case EVENT_UID_RULES_CHANGED:
3754 handleUidRulesChanged(msg.arg1, msg.arg2);
3755 break;
3756 case EVENT_DATA_SAVER_CHANGED:
3757 handleRestrictBackgroundChanged(toBool(msg.arg1));
3758 break;
lucaslind2e045e02019-01-24 15:55:30 +08003759 case EVENT_TIMEOUT_NOTIFICATION:
3760 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3761 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 }
3763 }
3764 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003765
3766 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003767 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003768 public int tether(String iface, String callerPkg) {
3769 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003770 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003771 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003772 } else {
3773 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3774 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003775 }
3776
3777 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003778 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003779 public int untether(String iface, String callerPkg) {
3780 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003781
3782 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003783 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003784 } else {
3785 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3786 }
3787 }
3788
3789 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003790 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003791 public int getLastTetherError(String iface) {
3792 enforceTetherAccessPermission();
3793
3794 if (isTetheringSupported()) {
3795 return mTethering.getLastTetherError(iface);
3796 } else {
3797 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3798 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003799 }
3800
3801 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003802 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003803 public String[] getTetherableUsbRegexs() {
3804 enforceTetherAccessPermission();
3805 if (isTetheringSupported()) {
3806 return mTethering.getTetherableUsbRegexs();
3807 } else {
3808 return new String[0];
3809 }
3810 }
3811
Lorenzo Colitti18660282016-07-04 12:55:44 +09003812 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003813 public String[] getTetherableWifiRegexs() {
3814 enforceTetherAccessPermission();
3815 if (isTetheringSupported()) {
3816 return mTethering.getTetherableWifiRegexs();
3817 } else {
3818 return new String[0];
3819 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003820 }
3821
Lorenzo Colitti18660282016-07-04 12:55:44 +09003822 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003823 public String[] getTetherableBluetoothRegexs() {
3824 enforceTetherAccessPermission();
3825 if (isTetheringSupported()) {
3826 return mTethering.getTetherableBluetoothRegexs();
3827 } else {
3828 return new String[0];
3829 }
3830 }
3831
Lorenzo Colitti18660282016-07-04 12:55:44 +09003832 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003833 public int setUsbTethering(boolean enable, String callerPkg) {
3834 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003835 if (isTetheringSupported()) {
3836 return mTethering.setUsbTethering(enable);
3837 } else {
3838 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3839 }
3840 }
3841
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003842 // TODO - move iface listing, queries, etc to new module
3843 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003844 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003845 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003846 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003847 return mTethering.getTetherableIfaces();
3848 }
3849
Lorenzo Colitti18660282016-07-04 12:55:44 +09003850 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003851 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003852 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003853 return mTethering.getTetheredIfaces();
3854 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003855
Lorenzo Colitti18660282016-07-04 12:55:44 +09003856 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003857 public String[] getTetheringErroredIfaces() {
3858 enforceTetherAccessPermission();
3859 return mTethering.getErroredIfaces();
3860 }
3861
Lorenzo Colitti18660282016-07-04 12:55:44 +09003862 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003863 public String[] getTetheredDhcpRanges() {
3864 enforceConnectivityInternalPermission();
3865 return mTethering.getTetheredDhcpRanges();
3866 }
3867
Udam Saini0e94c362017-06-07 12:06:28 -07003868 @Override
3869 public boolean isTetheringSupported(String callerPkg) {
3870 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3871 return isTetheringSupported();
3872 }
3873
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003874 // if ro.tether.denied = true we default to no tethering
3875 // gservices could set the secure setting to 1 though to enable it on a build where it
3876 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003877 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003878 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3879 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3880 Settings.Global.TETHER_SUPPORTED, defaultVal));
3881 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003882 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003883
3884 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3885 boolean adminUser = false;
3886 final long token = Binder.clearCallingIdentity();
3887 try {
3888 adminUser = mUserManager.isAdminUser();
3889 } finally {
3890 Binder.restoreCallingIdentity(token);
3891 }
3892
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003893 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003894 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003895
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003896 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003897 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3898 String callerPkg) {
3899 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003900 if (!isTetheringSupported()) {
3901 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3902 return;
3903 }
3904 mTethering.startTethering(type, receiver, showProvisioningUi);
3905 }
3906
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003907 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003908 public void stopTethering(int type, String callerPkg) {
3909 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003910 mTethering.stopTethering(type);
3911 }
3912
markchienf2731272019-01-16 17:44:13 +08003913 /**
3914 * Get the latest value of the tethering entitlement check.
3915 *
3916 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3917 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3918 * if it's really needed.
3919 */
3920 @Override
markchien9554abf2019-03-06 16:25:00 +08003921 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003922 boolean showEntitlementUi, String callerPkg) {
3923 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003924 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003925 }
3926
markchien26299ed2019-02-27 14:56:11 +08003927 /** Register tethering event callback. */
3928 @Override
3929 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3930 String callerPkg) {
3931 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3932 mTethering.registerTetheringEventCallback(callback);
3933 }
3934
3935 /** Unregister tethering event callback. */
3936 @Override
3937 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3938 String callerPkg) {
3939 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3940 mTethering.unregisterTetheringEventCallback(callback);
3941 }
3942
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003943 // Called when we lose the default network and have no replacement yet.
3944 // This will automatically be cleared after X seconds or a new default network
3945 // becomes CONNECTED, whichever happens first. The timer is started by the
3946 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003947 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003948 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003949 if (mNetTransitionWakeLock.isHeld()) {
3950 return;
3951 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003952 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003953 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3954 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003955 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003956 mWakelockLogs.log("ACQUIRE for " + forWhom);
3957 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3958 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003959 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003960
Hugo Benichi4c31b342017-03-30 23:18:10 +09003961 // Called when we gain a new default network to release the network transition wakelock in a
3962 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3963 // message is cancelled.
3964 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003965 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003966 if (!mNetTransitionWakeLock.isHeld()) {
3967 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003968 }
3969 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003970 // Cancel self timeout on wakelock hold.
3971 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3972 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3973 mHandler.sendMessageDelayed(msg, 1000);
3974 }
3975
3976 // Called when either message of ensureNetworkTransitionWakelock or
3977 // scheduleReleaseNetworkTransitionWakelock is processed.
3978 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3979 String event = eventName(eventId);
3980 synchronized (this) {
3981 if (!mNetTransitionWakeLock.isHeld()) {
3982 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3983 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3984 return;
3985 }
3986 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003987 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3988 mTotalWakelockDurationMs += lockDuration;
3989 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3990 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003991 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003992 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003993 }
3994
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003995 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003996 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003997 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003998 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003999 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004000 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004001 }
4002
Lorenzo Colitti18660282016-07-04 12:55:44 +09004003 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004004 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004005 enforceAccessPermission();
4006 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004007 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004008 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004009 mHandler.sendMessage(
4010 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4011 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004012
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004013 private void handleReportNetworkConnectivity(
4014 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004015 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004016 if (network == null) {
4017 nai = getDefaultNetwork();
4018 } else {
4019 nai = getNetworkAgentInfoForNetwork(network);
4020 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004021 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4022 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4023 return;
4024 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004025 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004026 if (hasConnectivity == nai.lastValidated) {
4027 return;
4028 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004029 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004030 int netid = nai.network.netId;
4031 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004032 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004033 // Validating a network that has not yet connected could result in a call to
4034 // rematchNetworkAndRequests() which is not meant to work on such networks.
4035 if (!nai.everConnected) {
4036 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004037 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004038 LinkProperties lp = getLinkProperties(nai);
4039 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4040 return;
4041 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004042 try {
4043 nai.networkMonitor().forceReevaluation(uid);
4044 } catch (RemoteException e) {
4045 e.rethrowFromSystemServer();
4046 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047 }
4048
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004049 /**
4050 * Returns information about the proxy a certain network is using. If given a null network, it
4051 * it will return the proxy for the bound network for the caller app or the default proxy if
4052 * none.
4053 *
4054 * @param network the network we want to get the proxy information for.
4055 * @return Proxy information if a network has a proxy configured, or otherwise null.
4056 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004057 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004058 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004059 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004060 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004061 if (network == null) {
4062 // Get the network associated with the calling UID.
4063 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4064 true);
4065 if (activeNetwork == null) {
4066 return null;
4067 }
4068 return getLinkPropertiesProxyInfo(activeNetwork);
4069 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4070 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4071 // caller may not have.
4072 return getLinkPropertiesProxyInfo(network);
4073 }
4074 // No proxy info available if the calling UID does not have network access.
4075 return null;
4076 }
4077
4078 @VisibleForTesting
4079 protected boolean queryUserAccess(int uid, int netId) {
4080 return NetworkUtils.queryUserAccess(uid, netId);
4081 }
4082
4083 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004084 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4085 if (nai == null) return null;
4086 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004087 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4088 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004089 }
4090 }
4091
Chalard Jean3c443fc2018-06-07 18:37:59 +09004092 @Override
4093 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004094 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004095 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004096 }
4097
Chalard Jean5afbc832018-06-07 18:02:37 +09004098 @Override
4099 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004100 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004101 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004102 }
4103
Jason Monk207900c2014-04-25 15:00:09 -04004104 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004105 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004106 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004107 proxy = null;
4108 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004109 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004110 }
4111
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004112 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4113 // when any network changes proxy.
4114 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4115 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004116 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004117 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4118 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4119
Chalard Jean4949dd72018-06-07 17:41:29 +09004120 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004121 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004122 }
4123 }
4124
Robert Greenwalt434203a2010-10-11 16:00:27 -07004125 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004126 final private HashMap<Uri, Integer> mUriEventMap;
4127 final private Context mContext;
4128 final private Handler mHandler;
4129
4130 SettingsObserver(Context context, Handler handler) {
4131 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004132 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004133 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004134 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004135 }
4136
Erik Klineda4bfa82015-04-30 12:58:40 +09004137 void observe(Uri uri, int what) {
4138 mUriEventMap.put(uri, what);
4139 final ContentResolver resolver = mContext.getContentResolver();
4140 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004141 }
4142
4143 @Override
4144 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004145 Slog.wtf(TAG, "Should never be reached.");
4146 }
4147
4148 @Override
4149 public void onChange(boolean selfChange, Uri uri) {
4150 final Integer what = mUriEventMap.get(uri);
4151 if (what != null) {
4152 mHandler.obtainMessage(what.intValue()).sendToTarget();
4153 } else {
4154 loge("No matching event to send for URI=" + uri);
4155 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004156 }
4157 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004158
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004159 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004160 Slog.d(TAG, s);
4161 }
4162
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004163 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004164 Slog.e(TAG, s);
4165 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004166
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004167 private static void loge(String s, Throwable t) {
4168 Slog.e(TAG, s, t);
4169 }
4170
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004171 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004172 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004173 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4174 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4175 *
4176 * @param oldPackage Package name of the application which currently controls VPN, which will
4177 * be replaced. If there is no such application, this should should either be
4178 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4179 * @param newPackage Package name of the application which should gain control of VPN, or
4180 * {@code null} to disable.
4181 * @param userId User for whom to prepare the new VPN.
4182 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004183 * @hide
4184 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004185 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004186 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4187 int userId) {
4188 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004189
Hugo Benichi20035e02017-04-26 14:53:28 +09004190 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004191 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004192 Vpn vpn = mVpns.get(userId);
4193 if (vpn != null) {
4194 return vpn.prepare(oldPackage, newPackage);
4195 } else {
4196 return false;
4197 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004198 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004199 }
4200
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004201 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004202 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4203 * This method is used by system-privileged apps.
4204 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4205 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4206 *
4207 * @param packageName The package for which authorization state should change.
4208 * @param userId User for whom {@code packageName} is installed.
4209 * @param authorized {@code true} if this app should be able to start a VPN connection without
4210 * explicit user approval, {@code false} if not.
4211 *
Jeff Davidson05542602014-08-11 14:07:27 -07004212 * @hide
4213 */
4214 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004215 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4216 enforceCrossUserPermission(userId);
4217
Hugo Benichi20035e02017-04-26 14:53:28 +09004218 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004219 Vpn vpn = mVpns.get(userId);
4220 if (vpn != null) {
4221 vpn.setPackageAuthorization(packageName, authorized);
4222 }
Jeff Davidson05542602014-08-11 14:07:27 -07004223 }
4224 }
4225
4226 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004227 * Configure a TUN interface and return its file descriptor. Parameters
4228 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004229 * and not available in ConnectivityManager. Permissions are checked in
4230 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004231 * @hide
4232 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004233 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004234 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004235 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004236 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004237 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004238 return mVpns.get(user).establish(config);
4239 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004240 }
4241
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004242 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004243 * Start legacy VPN, controlling native daemons as needed. Creates a
4244 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004245 */
4246 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004247 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004248 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004249 final LinkProperties egress = getActiveLinkProperties();
4250 if (egress == null) {
4251 throw new IllegalStateException("Missing active network connection");
4252 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004253 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004254 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004255 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4256 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004257 }
4258
4259 /**
4260 * Return the information of the ongoing legacy VPN. This method is used
4261 * by VpnSettings and not available in ConnectivityManager. Permissions
4262 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004263 */
4264 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004265 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4266 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004267
Hugo Benichi20035e02017-04-26 14:53:28 +09004268 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004269 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004270 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004271 }
4272
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004273 /**
Varun Anandd33cbc62019-02-07 14:13:13 -08004274 * Return the information of all ongoing VPNs.
4275 *
4276 * <p>This method is used to update NetworkStatsService.
4277 *
4278 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004279 */
Varun Anandd33cbc62019-02-07 14:13:13 -08004280 private VpnInfo[] getAllVpnInfo() {
4281 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004282 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004283 if (mLockdownEnabled) {
4284 return new VpnInfo[0];
4285 }
4286
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004287 List<VpnInfo> infoList = new ArrayList<>();
4288 for (int i = 0; i < mVpns.size(); i++) {
4289 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4290 if (info != null) {
4291 infoList.add(info);
4292 }
4293 }
4294 return infoList.toArray(new VpnInfo[infoList.size()]);
4295 }
4296 }
4297
4298 /**
4299 * @return VPN information for accounting, or null if we can't retrieve all required
4300 * information, e.g primary underlying iface.
4301 */
4302 @Nullable
4303 private VpnInfo createVpnInfo(Vpn vpn) {
4304 VpnInfo info = vpn.getVpnInfo();
4305 if (info == null) {
4306 return null;
4307 }
4308 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4309 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4310 // the underlyingNetworks list.
4311 if (underlyingNetworks == null) {
4312 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4313 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4314 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4315 }
4316 } else if (underlyingNetworks.length > 0) {
4317 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4318 if (linkProperties != null) {
4319 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4320 }
4321 }
4322 return info.primaryUnderlyingIface == null ? null : info;
4323 }
4324
4325 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004326 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4327 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004328 * Permissions are checked in Vpn class.
4329 * @hide
4330 */
4331 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004332 public VpnConfig getVpnConfig(int userId) {
4333 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004334 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004335 Vpn vpn = mVpns.get(userId);
4336 if (vpn != null) {
4337 return vpn.getVpnConfig();
4338 } else {
4339 return null;
4340 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004341 }
4342 }
4343
Chalard Jean6b65ec72018-05-18 22:02:56 +09004344 /**
4345 * Ask all VPN objects to recompute and update their capabilities.
4346 *
4347 * When underlying networks change, VPNs may have to update capabilities to reflect things
4348 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4349 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4350 * handler thread through their agent, this is asynchronous. When the capabilities objects
4351 * are computed they will be up-to-date as they are computed synchronously from here and
4352 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004353 */
4354 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004355 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004356 synchronized (mVpns) {
4357 for (int i = 0; i < mVpns.size(); i++) {
4358 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004359 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4360 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004361 }
4362 }
4363 }
4364
Varun Anand4fa80e82019-02-06 10:13:38 -08004365 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4366 ensureRunningOnConnectivityServiceThread();
4367 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4368 if (vpnNai == null || nc == null) {
4369 return;
4370 }
4371 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4372 }
4373
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004374 @Override
4375 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004376 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4377 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4378 return false;
4379 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004380
Hugo Benichi69744342017-11-27 10:57:16 +09004381 synchronized (mVpns) {
4382 // Tear down existing lockdown if profile was removed
4383 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4384 if (mLockdownEnabled) {
4385 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4386 if (profileTag == null) {
4387 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4388 return false;
4389 }
4390 String profileName = new String(profileTag);
4391 final VpnProfile profile = VpnProfile.decode(
4392 profileName, mKeyStore.get(Credentials.VPN + profileName));
4393 if (profile == null) {
4394 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4395 setLockdownTracker(null);
4396 return true;
4397 }
4398 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004399 Vpn vpn = mVpns.get(user);
4400 if (vpn == null) {
4401 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4402 return false;
4403 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004404 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004405 } else {
4406 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004407 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004408 }
4409
4410 return true;
4411 }
4412
4413 /**
4414 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4415 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4416 */
Hugo Benichi69744342017-11-27 10:57:16 +09004417 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004418 private void setLockdownTracker(LockdownVpnTracker tracker) {
4419 // Shutdown any existing tracker
4420 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004421 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4422 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004423 mLockdownTracker = null;
4424 if (existing != null) {
4425 existing.shutdown();
4426 }
4427
Robin Leec3736bc2017-03-10 16:19:54 +00004428 if (tracker != null) {
4429 mLockdownTracker = tracker;
4430 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004431 }
4432 }
4433
Hugo Benichi69744342017-11-27 10:57:16 +09004434 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004435 private void throwIfLockdownEnabled() {
4436 if (mLockdownEnabled) {
4437 throw new IllegalStateException("Unavailable in lockdown mode");
4438 }
4439 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004440
Robin Lee244ce8e2016-01-05 18:03:46 +00004441 /**
Robin Lee17e61832016-05-09 13:46:28 +01004442 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4443 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004444 *
Robin Lee17e61832016-05-09 13:46:28 +01004445 * @return {@code true} if the service was started, the service was already connected, or there
4446 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004447 */
Robin Lee17e61832016-05-09 13:46:28 +01004448 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004449 synchronized (mVpns) {
4450 Vpn vpn = mVpns.get(userId);
4451 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004452 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004453 // exists already.
4454 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4455 return false;
4456 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004457
Robin Lee812800c2016-05-13 15:38:08 +01004458 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004459 }
4460 }
4461
4462 @Override
Charles He36738632017-05-15 17:07:18 +01004463 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4464 enforceSettingsPermission();
4465 enforceCrossUserPermission(userId);
4466
4467 synchronized (mVpns) {
4468 Vpn vpn = mVpns.get(userId);
4469 if (vpn == null) {
4470 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4471 return false;
4472 }
4473 return vpn.isAlwaysOnPackageSupported(packageName);
4474 }
4475 }
4476
4477 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004478 public boolean setAlwaysOnVpnPackage(
4479 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4480 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004481 enforceCrossUserPermission(userId);
4482
Robin Lee244ce8e2016-01-05 18:03:46 +00004483 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004484 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4485 if (LockdownVpnTracker.isEnabled()) {
4486 return false;
4487 }
4488
Robin Lee244ce8e2016-01-05 18:03:46 +00004489 Vpn vpn = mVpns.get(userId);
4490 if (vpn == null) {
4491 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4492 return false;
4493 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004494 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004495 return false;
4496 }
Robin Lee17e61832016-05-09 13:46:28 +01004497 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004498 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004499 return false;
4500 }
4501 }
4502 return true;
4503 }
4504
4505 @Override
4506 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004507 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004508 enforceCrossUserPermission(userId);
4509
4510 synchronized (mVpns) {
4511 Vpn vpn = mVpns.get(userId);
4512 if (vpn == null) {
4513 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4514 return null;
4515 }
4516 return vpn.getAlwaysOnPackage();
4517 }
4518 }
4519
Wink Savilleab9321d2013-06-29 21:10:57 -07004520 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004521 public boolean isVpnLockdownEnabled(int userId) {
4522 enforceControlAlwaysOnVpnPermission();
4523 enforceCrossUserPermission(userId);
4524
4525 synchronized (mVpns) {
4526 Vpn vpn = mVpns.get(userId);
4527 if (vpn == null) {
4528 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4529 return false;
4530 }
4531 return vpn.getLockdown();
4532 }
4533 }
4534
4535 @Override
4536 public List<String> getVpnLockdownWhitelist(int userId) {
4537 enforceControlAlwaysOnVpnPermission();
4538 enforceCrossUserPermission(userId);
4539
4540 synchronized (mVpns) {
4541 Vpn vpn = mVpns.get(userId);
4542 if (vpn == null) {
4543 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4544 return null;
4545 }
4546 return vpn.getLockdownWhitelist();
4547 }
4548 }
4549
4550 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004551 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004552 // TODO: Remove? Any reason to trigger a provisioning check?
4553 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004554 }
4555
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004556 /** Location to an updatable file listing carrier provisioning urls.
4557 * An example:
4558 *
4559 * <?xml version="1.0" encoding="utf-8"?>
4560 * <provisioningUrls>
4561 * <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 -07004562 * </provisioningUrls>
4563 */
4564 private static final String PROVISIONING_URL_PATH =
4565 "/data/misc/radio/provisioning_urls.xml";
4566 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004567
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004568 /** XML tag for root element. */
4569 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4570 /** XML tag for individual url */
4571 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004572 /** XML attribute for mcc */
4573 private static final String ATTR_MCC = "mcc";
4574 /** XML attribute for mnc */
4575 private static final String ATTR_MNC = "mnc";
4576
Paul Jensen434dde82015-06-11 09:43:30 -04004577 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004578 FileReader fileReader = null;
4579 XmlPullParser parser = null;
4580 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004581
4582 try {
4583 fileReader = new FileReader(mProvisioningUrlFile);
4584 parser = Xml.newPullParser();
4585 parser.setInput(fileReader);
4586 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4587
4588 while (true) {
4589 XmlUtils.nextElement(parser);
4590
4591 String element = parser.getName();
4592 if (element == null) break;
4593
Paul Jensen434dde82015-06-11 09:43:30 -04004594 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004595 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4596 try {
4597 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4598 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4599 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4600 parser.next();
4601 if (parser.getEventType() == XmlPullParser.TEXT) {
4602 return parser.getText();
4603 }
4604 }
4605 }
4606 } catch (NumberFormatException e) {
4607 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4608 }
4609 }
4610 }
4611 return null;
4612 } catch (FileNotFoundException e) {
4613 loge("Carrier Provisioning Urls file not found");
4614 } catch (XmlPullParserException e) {
4615 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4616 } catch (IOException e) {
4617 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4618 } finally {
4619 if (fileReader != null) {
4620 try {
4621 fileReader.close();
4622 } catch (IOException e) {}
4623 }
4624 }
4625 return null;
4626 }
4627
Wink Saville42d4f082013-07-20 20:31:59 -07004628 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004629 public String getMobileProvisioningUrl() {
4630 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004631 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004632 if (TextUtils.isEmpty(url)) {
4633 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004634 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004635 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004636 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004637 }
Wink Saville8cf35602013-07-10 23:00:07 -07004638 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004639 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004640 String phoneNumber = mTelephonyManager.getLine1Number();
4641 if (TextUtils.isEmpty(phoneNumber)) {
4642 phoneNumber = "0000000000";
4643 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004644 url = String.format(url,
4645 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4646 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004647 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004648 }
4649
Wink Savilleab9321d2013-06-29 21:10:57 -07004650 return url;
4651 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004652
Wink Saville948282b2013-08-29 08:55:16 -07004653 @Override
4654 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004655 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004656 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004657 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4658 return;
4659 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004660 final long ident = Binder.clearCallingIdentity();
4661 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004662 // Concatenate the range of types onto the range of NetIDs.
4663 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4664 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004665 } finally {
4666 Binder.restoreCallingIdentity(ident);
4667 }
Wink Saville948282b2013-08-29 08:55:16 -07004668 }
Wink Saville7788c612013-08-29 14:57:08 -07004669
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004670 @Override
4671 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004672 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004673 final long ident = Binder.clearCallingIdentity();
4674 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004675 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004676 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004677 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4678 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004679 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004680 } finally {
4681 Binder.restoreCallingIdentity(ident);
4682 }
4683 }
4684
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004685 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004686 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004687 Vpn userVpn = mVpns.get(userId);
4688 if (userVpn != null) {
4689 loge("Starting user already has a VPN");
4690 return;
4691 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004692 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004693 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004694 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4695 updateLockdownVpn();
4696 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004697 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004698 }
4699
4700 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004701 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004702 Vpn userVpn = mVpns.get(userId);
4703 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004704 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004705 return;
4706 }
Robin Lee17e61832016-05-09 13:46:28 +01004707 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004708 mVpns.delete(userId);
4709 }
4710 }
4711
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004712 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004713 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004714 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004715 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004716 final int vpnsSize = mVpns.size();
4717 for (int i = 0; i < vpnsSize; i++) {
4718 Vpn vpn = mVpns.valueAt(i);
4719 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004720 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4721 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004722 }
4723 }
4724 }
4725
4726 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004727 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004728 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004729 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004730 final int vpnsSize = mVpns.size();
4731 for (int i = 0; i < vpnsSize; i++) {
4732 Vpn vpn = mVpns.valueAt(i);
4733 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004734 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4735 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004736 }
4737 }
4738 }
4739
junyulai2454b692018-11-01 17:16:31 +08004740 private void onPackageAdded(String packageName, int uid) {
4741 if (TextUtils.isEmpty(packageName) || uid < 0) {
4742 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4743 return;
4744 }
4745 mPermissionMonitor.onPackageAdded(packageName, uid);
4746 }
4747
junyulaiefb04d32018-11-12 22:39:30 +08004748 private void onPackageReplaced(String packageName, int uid) {
4749 if (TextUtils.isEmpty(packageName) || uid < 0) {
4750 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4751 return;
4752 }
4753 final int userId = UserHandle.getUserId(uid);
4754 synchronized (mVpns) {
4755 final Vpn vpn = mVpns.get(userId);
4756 if (vpn == null) {
4757 return;
4758 }
4759 // Legacy always-on VPN won't be affected since the package name is not set.
4760 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4761 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4762 + userId);
4763 vpn.startAlwaysOnVpn();
4764 }
4765 }
4766 }
4767
4768 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004769 if (TextUtils.isEmpty(packageName) || uid < 0) {
4770 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4771 return;
4772 }
4773 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004774
4775 final int userId = UserHandle.getUserId(uid);
4776 synchronized (mVpns) {
4777 final Vpn vpn = mVpns.get(userId);
4778 if (vpn == null) {
4779 return;
4780 }
4781 // Legacy always-on VPN won't be affected since the package name is not set.
4782 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4783 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4784 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004785 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004786 }
4787 }
junyulai2454b692018-11-01 17:16:31 +08004788 }
4789
Robin Lee89e7a692016-02-29 14:38:17 +00004790 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004791 synchronized (mVpns) {
4792 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4793 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4794 updateLockdownVpn();
4795 } else {
4796 startAlwaysOnVpn(userId);
4797 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004798 }
4799 }
4800
junyulai2454b692018-11-01 17:16:31 +08004801 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004802 @Override
4803 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004804 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004805 final String action = intent.getAction();
4806 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004807 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4808 final Uri packageData = intent.getData();
4809 final String packageName =
4810 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004811 if (userId == UserHandle.USER_NULL) return;
4812
Robin Lee323f29d2016-05-04 16:38:06 +01004813 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004814 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004815 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004816 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004817 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4818 onUserAdded(userId);
4819 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4820 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004821 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4822 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004823 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4824 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004825 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4826 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004827 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004828 final boolean isReplacing = intent.getBooleanExtra(
4829 Intent.EXTRA_REPLACING, false);
4830 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004831 }
4832 }
4833 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004834
Robin Lee95204e02017-01-27 11:59:22 +00004835 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4836 @Override
4837 public void onReceive(Context context, Intent intent) {
4838 // Try creating lockdown tracker, since user present usually means
4839 // unlocked keystore.
4840 updateLockdownVpn();
4841 mContext.unregisterReceiver(this);
4842 }
4843 };
4844
Chalard Jean4133a122018-06-04 13:33:12 +09004845 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4846 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004847
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004848 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4849 // Map from UID to number of NetworkRequests that UID has filed.
4850 @GuardedBy("mUidToNetworkRequestCount")
4851 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4852
Robert Greenwalta67be032014-05-16 15:49:14 -07004853 private static class NetworkFactoryInfo {
4854 public final String name;
4855 public final Messenger messenger;
4856 public final AsyncChannel asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004857 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004858
Chalard Jean05ab6812018-05-02 21:14:54 +09004859 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4860 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004861 this.name = name;
4862 this.messenger = messenger;
4863 this.asyncChannel = asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004864 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004865 }
4866 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004867
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004868 private void ensureNetworkRequestHasType(NetworkRequest request) {
4869 if (request.type == NetworkRequest.Type.NONE) {
4870 throw new IllegalArgumentException(
4871 "All NetworkRequests in ConnectivityService must have a type");
4872 }
4873 }
4874
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004875 /**
4876 * Tracks info about the requester.
4877 * Also used to notice when the calling process dies so we can self-expire
4878 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004879 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004880 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004881 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004882 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004883 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004884 final int mPid;
4885 final int mUid;
4886 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004887
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004888 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004889 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004890 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004891 mPendingIntent = pi;
4892 messenger = null;
4893 mBinder = null;
4894 mPid = getCallingPid();
4895 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004896 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004897 }
4898
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004899 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004900 super();
4901 messenger = m;
4902 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004903 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004904 mBinder = binder;
4905 mPid = getCallingPid();
4906 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004907 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004908 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004909
4910 try {
4911 mBinder.linkToDeath(this, 0);
4912 } catch (RemoteException e) {
4913 binderDied();
4914 }
4915 }
4916
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004917 private void enforceRequestCountLimit() {
4918 synchronized (mUidToNetworkRequestCount) {
4919 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4920 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004921 throw new ServiceSpecificException(
4922 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004923 }
4924 mUidToNetworkRequestCount.put(mUid, networkRequests);
4925 }
4926 }
4927
Robert Greenwalt9258c642014-03-26 16:47:06 -07004928 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004929 if (mBinder != null) {
4930 mBinder.unlinkToDeath(this, 0);
4931 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004932 }
4933
4934 public void binderDied() {
4935 log("ConnectivityService NetworkRequestInfo binderDied(" +
4936 request + ", " + mBinder + ")");
4937 releaseNetworkRequest(request);
4938 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004939
4940 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004941 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004942 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004943 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004944 }
4945
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004946 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4947 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4948 if (badCapability != null) {
4949 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004950 }
4951 }
4952
Chalard Jeanb03a6222018-04-11 21:09:10 +09004953 // This checks that the passed capabilities either do not request a specific SSID, or the
4954 // calling app has permission to do so.
4955 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4956 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004957 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004958 throw new SecurityException("Insufficient permissions to request a specific SSID");
4959 }
4960 }
4961
Erik Kline9d598e12015-07-13 16:37:51 +09004962 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004963 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004964 synchronized (nai) {
4965 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4966 if (nri.request.networkCapabilities.hasSignalStrength() &&
4967 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4968 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4969 }
4970 }
4971 }
Chalard Jean4133a122018-06-04 13:33:12 +09004972 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004973 }
4974
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004975 private void updateSignalStrengthThresholds(
4976 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4977 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004978 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004979 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4980
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004981 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004982 String detail;
4983 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4984 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4985 } else {
4986 detail = reason;
4987 }
4988 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4989 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4990 }
4991
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004992 nai.asyncChannel.sendMessage(
4993 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004994 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004995 }
4996
Etan Cohen859748f2017-04-03 17:42:34 -07004997 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4998 if (nc == null) {
4999 return;
5000 }
5001 NetworkSpecifier ns = nc.getNetworkSpecifier();
5002 if (ns == null) {
5003 return;
5004 }
5005 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5006 ns.assertValidFromUid(Binder.getCallingUid());
5007 }
5008
Robert Greenwalt9258c642014-03-26 16:47:06 -07005009 @Override
5010 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005011 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005012 final NetworkRequest.Type type = (networkCapabilities == null)
5013 ? NetworkRequest.Type.TRACK_DEFAULT
5014 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005015 // If the requested networkCapabilities is null, take them instead from
5016 // the default network request. This allows callers to keep track of
5017 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005018 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005019 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005020 enforceAccessPermission();
5021 } else {
5022 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5023 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005024 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5025 // of the app when the request is filed, but we never change the request if the app
5026 // changes network state. http://b/29964605
5027 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005028 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005029 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005030 ensureSufficientPermissionsForRequest(networkCapabilities,
5031 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005032 // Set the UID range for this request to the single UID of the requester, or to an empty
5033 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005034 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5035 // are no visible methods to set the UIDs, an app could use reflection to try and get
5036 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005037 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005038
Etan Cohenba07c8c2017-02-05 10:42:27 -08005039 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005040 throw new IllegalArgumentException("Bad timeout specified");
5041 }
Etan Cohen859748f2017-04-03 17:42:34 -07005042 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005043
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005044 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005045 nextNetworkRequestId(), type);
5046 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005047 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005048
5049 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005050 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005051 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005052 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005053 }
5054 return networkRequest;
5055 }
5056
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005057 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005058 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005059 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005060 } else {
5061 enforceChangePermission();
5062 }
5063 }
5064
fenglub15e72b2015-03-20 11:29:56 -07005065 @Override
fengludb571472015-04-21 17:12:05 -07005066 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005067 enforceAccessPermission();
5068 NetworkAgentInfo nai = null;
5069 if (network == null) {
5070 return false;
5071 }
5072 synchronized (mNetworkForNetId) {
5073 nai = mNetworkForNetId.get(network.netId);
5074 }
5075 if (nai != null) {
5076 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005077 synchronized (mBandwidthRequests) {
5078 final int uid = Binder.getCallingUid();
5079 Integer uidReqs = mBandwidthRequests.get(uid);
5080 if (uidReqs == null) {
5081 uidReqs = new Integer(0);
5082 }
5083 mBandwidthRequests.put(uid, ++uidReqs);
5084 }
fenglub15e72b2015-03-20 11:29:56 -07005085 return true;
5086 }
5087 return false;
5088 }
5089
Felipe Lemeee27cab2016-06-20 16:36:29 -07005090 private boolean isSystem(int uid) {
5091 return uid < Process.FIRST_APPLICATION_UID;
5092 }
fenglub15e72b2015-03-20 11:29:56 -07005093
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005094 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005095 final int uid = Binder.getCallingUid();
5096 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005097 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005098 return;
5099 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005100 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5101 // Policy already enforced.
5102 return;
5103 }
5104 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5105 // If UID is restricted, don't allow them to bring up metered APNs.
5106 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005107 }
5108 }
5109
Robert Greenwalt9258c642014-03-26 16:47:06 -07005110 @Override
5111 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5112 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005113 checkNotNull(operation, "PendingIntent cannot be null.");
5114 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5115 enforceNetworkRequestPermissions(networkCapabilities);
5116 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005117 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005118 ensureSufficientPermissionsForRequest(networkCapabilities,
5119 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005120 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005121 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005122
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005123 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005124 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5125 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005126 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5128 nri));
5129 return networkRequest;
5130 }
5131
Jeremy Joslin79294842014-12-03 17:15:28 -08005132 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5133 mHandler.sendMessageDelayed(
5134 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5135 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5136 }
5137
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005138 @Override
5139 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005140 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005141 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5142 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005143 }
5144
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005145 // In order to implement the compatibility measure for pre-M apps that call
5146 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5147 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5148 // This ensures it has permission to do so.
5149 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5150 if (nc == null) {
5151 return false;
5152 }
5153 int[] transportTypes = nc.getTransportTypes();
5154 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5155 return false;
5156 }
5157 try {
5158 mContext.enforceCallingOrSelfPermission(
5159 android.Manifest.permission.ACCESS_WIFI_STATE,
5160 "ConnectivityService");
5161 } catch (SecurityException e) {
5162 return false;
5163 }
5164 return true;
5165 }
5166
Robert Greenwalt9258c642014-03-26 16:47:06 -07005167 @Override
5168 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5169 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005170 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5171 enforceAccessPermission();
5172 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005173
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005174 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005175 ensureSufficientPermissionsForRequest(networkCapabilities,
5176 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005177 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005178 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5179 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5180 // onLost and onAvailable callbacks when networks move in and out of the background.
5181 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5182 // can't request networks.
5183 restrictBackgroundRequestForCaller(nc);
5184 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005185
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005186 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005187 NetworkRequest.Type.LISTEN);
5188 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005189 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005190
5191 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5192 return networkRequest;
5193 }
5194
5195 @Override
5196 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5197 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005198 checkNotNull(operation, "PendingIntent cannot be null.");
5199 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5200 enforceAccessPermission();
5201 }
Etan Cohen859748f2017-04-03 17:42:34 -07005202 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005203 ensureSufficientPermissionsForRequest(networkCapabilities,
5204 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005205
Chalard Jeandda156a2018-01-10 21:19:32 +09005206 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005207 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005208
5209 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005210 NetworkRequest.Type.LISTEN);
5211 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005212 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005213
5214 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005215 }
5216
Erik Klineacdd6392016-07-07 16:50:58 +09005217 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005218 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005219 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005220 mHandler.sendMessage(mHandler.obtainMessage(
5221 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005222 }
5223
5224 @Override
Chalard Jean05ab6812018-05-02 21:14:54 +09005225 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005226 enforceConnectivityInternalPermission();
Chalard Jean05ab6812018-05-02 21:14:54 +09005227 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5228 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005229 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean05ab6812018-05-02 21:14:54 +09005230 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005231 }
5232
Robert Greenwalta67be032014-05-16 15:49:14 -07005233 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005234 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005235 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5236 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5237 }
5238
5239 @Override
5240 public void unregisterNetworkFactory(Messenger messenger) {
5241 enforceConnectivityInternalPermission();
5242 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5243 }
5244
5245 private void handleUnregisterNetworkFactory(Messenger messenger) {
5246 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5247 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005248 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005249 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005250 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005251 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005252 }
5253
Robert Greenwalt7b816022014-04-18 15:25:25 -07005254 /**
5255 * NetworkAgentInfo supporting a request by requestId.
5256 * These have already been vetted (their Capabilities satisfy the request)
5257 * and the are the highest scored network available.
5258 * the are keyed off the Requests requestId.
5259 */
Hugo Benichicd952782017-09-20 11:20:14 +09005260 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5261 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005262 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005263
Paul Jensen31a94f42015-02-13 14:18:39 -05005264 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5265 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005266 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005267 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5268 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5269 // there may not be a strict 1:1 correlation between the two.
5270 @GuardedBy("mNetworkForNetId")
5271 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005272
Robert Greenwalt7b816022014-04-18 15:25:25 -07005273 // NetworkAgentInfo keyed off its connecting messenger
5274 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005275 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005276 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005277
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005278 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005279 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005280
Paul Jensen2c311d62014-11-17 12:34:51 -05005281 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005282 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005283
Erik Klineda4bfa82015-04-30 12:58:40 +09005284 // Request used to optionally keep mobile data active even when higher
5285 // priority networks like Wi-Fi are active.
5286 private final NetworkRequest mDefaultMobileDataRequest;
5287
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005288 // Request used to optionally keep wifi data active even when higher
5289 // priority networks like ethernet are active.
5290 private final NetworkRequest mDefaultWifiRequest;
5291
Hugo Benichicd952782017-09-20 11:20:14 +09005292 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5293 synchronized (mNetworkForRequestId) {
5294 return mNetworkForRequestId.get(requestId);
5295 }
5296 }
5297
5298 private void clearNetworkForRequest(int requestId) {
5299 synchronized (mNetworkForRequestId) {
5300 mNetworkForRequestId.remove(requestId);
5301 }
5302 }
5303
5304 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5305 synchronized (mNetworkForRequestId) {
5306 mNetworkForRequestId.put(requestId, nai);
5307 }
5308 }
5309
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005310 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005311 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005312 }
5313
Varun Anand4fa80e82019-02-06 10:13:38 -08005314 @Nullable
5315 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5316 return nai != null ? nai.network : null;
5317 }
5318
5319 private void ensureRunningOnConnectivityServiceThread() {
5320 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5321 throw new IllegalStateException(
5322 "Not running on ConnectivityService thread: "
5323 + Thread.currentThread().getName());
5324 }
5325 }
5326
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005327 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005328 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005329 }
5330
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005331 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5332 return nri.request.requestId == mDefaultRequest.requestId;
5333 }
5334
Chalard Jean05ab6812018-05-02 21:14:54 +09005335 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5336 // changes that would conflict throughout the automerger graph. Having this method temporarily
5337 // helps with the process of going through with all these dependent changes across the entire
5338 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005339 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005340 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005341 int currentScore, NetworkMisc networkMisc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005342 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5343 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5344 }
5345
5346 /**
5347 * Register a new agent with ConnectivityService to handle a network.
5348 *
5349 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5350 * @param networkInfo the initial info associated with this network. It can be updated later :
5351 * see {@link #updateNetworkInfo}.
5352 * @param linkProperties the initial link properties of this network. They can be updated
5353 * later : see {@link #updateLinkProperties}.
5354 * @param networkCapabilities the initial capabilites of this network. They can be updated
5355 * later : see {@link #updateNetworkCapabilities}.
5356 * @param currentScore the initial score of the network. See
5357 * {@link NetworkAgentInfo#getCurrentScore}.
5358 * @param networkMisc metadata about the network. This is never updated.
5359 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5360 */
5361 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5362 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5363 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005364 enforceConnectivityInternalPermission();
5365
Rubin Xu1bb5c082017-09-05 18:40:49 +01005366 LinkProperties lp = new LinkProperties(linkProperties);
5367 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005368 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5369 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005370 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005371 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005372 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean05ab6812018-05-02 21:14:54 +09005373 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5374 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005375 // Make sure the network capabilities reflect what the agent info says.
5376 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005377 final String extraInfo = networkInfo.getExtraInfo();
5378 final String name = TextUtils.isEmpty(extraInfo)
5379 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005380 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005381 final long token = Binder.clearCallingIdentity();
5382 try {
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005383 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +09005384 toStableParcelable(nai.network), name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005385 } finally {
5386 Binder.restoreCallingIdentity(token);
5387 }
5388 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5389 // If the network disconnects or sends any other event before that, messages are deferred by
5390 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5391 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005392 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005393 }
5394
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005395 @VisibleForTesting
5396 protected NetworkStackClient getNetworkStack() {
5397 return NetworkStackClient.getInstance();
5398 }
5399
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005400 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5401 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005402 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005403 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005404 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005405 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005406 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005407 synchronized (this) {
5408 if (mSystemReady) {
5409 try {
5410 networkMonitor.notifySystemReady();
5411 } catch (RemoteException e) {
5412 e.rethrowFromSystemServer();
5413 }
5414 }
5415 }
5416
5417 try {
5418 networkMonitor.start();
5419 } catch (RemoteException e) {
5420 e.rethrowFromSystemServer();
5421 }
Erik Klinee5dac902018-03-04 21:01:01 +09005422 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5423 NetworkInfo networkInfo = nai.networkInfo;
5424 nai.networkInfo = null;
5425 updateNetworkInfo(nai, networkInfo);
5426 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005427 }
5428
lucaslin25a4ec32018-11-28 12:51:55 +08005429 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5430 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005431 int netId = networkAgent.network.netId;
5432
Lorenzo Colittidf595632019-01-08 14:43:37 +09005433 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5434 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5435 // are accurate.
5436 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005437
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005438 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005439 updateMtu(newLp, oldLp);
5440 // TODO - figure out what to do for clat
5441// for (LinkProperties lp : newLp.getStackedLinks()) {
5442// updateMtu(lp, null);
5443// }
lucaslin041a1af2018-11-28 19:27:52 +08005444 if (isDefaultNetwork(networkAgent)) {
5445 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5446 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005447
Erik Kline94887872016-04-05 13:30:49 +09005448 updateRoutes(newLp, oldLp, netId);
5449 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005450 // Make sure LinkProperties represents the latest private DNS status.
5451 // This does not need to be done before updateDnses because the
5452 // LinkProperties are not the source of the private DNS configuration.
5453 // updateDnses will fetch the private DNS configuration from DnsManager.
5454 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005455
Paul Jensene0bef712014-12-10 15:12:18 -05005456 if (isDefaultNetwork(networkAgent)) {
5457 handleApplyDefaultProxy(newLp.getHttpProxy());
5458 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005459 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005460 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005461 // TODO - move this check to cover the whole function
5462 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005463 synchronized (networkAgent) {
5464 networkAgent.linkProperties = newLp;
5465 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005466 // Start or stop DNS64 detection and 464xlat according to network state.
5467 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005468 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005469 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005470 try {
5471 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5472 } catch (RemoteException e) {
5473 e.rethrowFromSystemServer();
5474 }
lucaslin25a4ec32018-11-28 12:51:55 +08005475 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5476 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005477 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005478
5479 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005480 }
5481
Joel Scherpelz668370b2017-06-08 15:35:21 +09005482 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005483 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005484 // marks on unsupported interfaces is harmless.
5485 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5486 return;
5487 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005488
Joel Scherpelz668370b2017-06-08 15:35:21 +09005489 int mark = mContext.getResources().getInteger(
5490 com.android.internal.R.integer.config_networkWakeupPacketMark);
5491 int mask = mContext.getResources().getInteger(
5492 com.android.internal.R.integer.config_networkWakeupPacketMask);
5493
5494 // Mask/mark of zero will not detect anything interesting.
5495 // Don't install rules unless both values are nonzero.
5496 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005497 return;
5498 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005499
5500 final String prefix = "iface:" + iface;
5501 try {
5502 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005503 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005504 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005505 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005506 }
5507 } catch (Exception e) {
5508 loge("Exception modifying wakeup packet monitoring: " + e);
5509 }
5510
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005511 }
5512
5513 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5514 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005515 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005516 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5517 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005518 for (String iface : interfaceDiff.added) {
5519 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005520 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005521 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005522 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005523 } catch (Exception e) {
5524 loge("Exception adding interface: " + e);
5525 }
5526 }
5527 for (String iface : interfaceDiff.removed) {
5528 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005529 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005530 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005531 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005532 } catch (Exception e) {
5533 loge("Exception removing interface: " + e);
5534 }
5535 }
5536 }
5537
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005538 /**
5539 * Have netd update routes from oldLp to newLp.
5540 * @return true if routes changed between oldLp and newLp
5541 */
5542 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005543 // Compare the route diff to determine which routes should be added and removed.
5544 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5545 oldLp != null ? oldLp.getAllRoutes() : null,
5546 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005547
5548 // add routes before removing old in case it helps with continuous connectivity
5549
Chalard Jean4d660112018-06-04 16:52:49 +09005550 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005551 for (RouteInfo route : routeDiff.added) {
5552 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005553 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005554 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005555 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005556 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005557 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5558 loge("Exception in addRoute for non-gateway: " + e);
5559 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005560 }
5561 }
5562 for (RouteInfo route : routeDiff.added) {
5563 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005564 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005565 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005566 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005567 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005568 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5569 loge("Exception in addRoute for gateway: " + e);
5570 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005571 }
5572 }
5573
5574 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005575 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005576 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005577 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005578 } catch (Exception e) {
5579 loge("Exception in removeRoute: " + e);
5580 }
5581 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005582 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005583 }
Erik Kline41368502015-06-17 13:19:54 +09005584
Erik Kline94887872016-04-05 13:30:49 +09005585 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5586 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5587 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005588 }
Erik Kline94887872016-04-05 13:30:49 +09005589
Erik Kline1742fe12017-12-13 19:40:49 +09005590 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5591 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5592
Erik Klinea24d4592018-01-11 21:07:29 +09005593 if (DBG) {
5594 final Collection<InetAddress> dnses = newLp.getDnsServers();
5595 log("Setting DNS servers for network " + netId + " to " + dnses);
5596 }
Erik Kline94887872016-04-05 13:30:49 +09005597 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005598 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005599 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005600 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005601 }
Erik Kline4edba012017-04-07 15:29:29 +09005602 }
5603
Luke Huang8a462ec2018-08-24 20:33:16 +08005604 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005605 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005606 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005607 }
5608 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005609 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005610 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005611 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005612 }
5613
Paul Jensen3d194ea2015-06-16 14:27:36 -04005614 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005615 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5616 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5617 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005618 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005619 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005620 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005621 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5622 // causing a connect/teardown loop.
5623 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5624 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005625 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005626 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005627 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5628 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005629 // does not cause any request (that is not a listen) currently matching that agent to
5630 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005631 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005632 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005633 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005634 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005635 }
5636
Paul Jensen3d194ea2015-06-16 14:27:36 -04005637 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005638 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005639 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005640 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005641 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005642 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005643 }
Paul Jensene0988542015-06-25 15:30:08 -04005644 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005645 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005646 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005647 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005648 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005649 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005650 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005651 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005652 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005653 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005654 if (nai.isSuspended()) {
5655 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5656 } else {
5657 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5658 }
lucasline252a742019-03-12 13:08:03 +08005659 if (nai.partialConnectivity) {
5660 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5661 } else {
5662 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5663 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005664
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005665 return newNc;
5666 }
5667
5668 /**
5669 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5670 *
5671 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5672 * capabilities we manage and store in {@code nai}, such as validated status and captive
5673 * portal status)
5674 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5675 * potentially triggers rematches.
5676 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5677 * change.)
5678 *
5679 * @param oldScore score of the network before any of the changes that prompted us
5680 * to call this function.
5681 * @param nai the network having its capabilities updated.
5682 * @param nc the new network capabilities.
5683 */
5684 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5685 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5686
5687 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005688
Luke Huang8a462ec2018-08-24 20:33:16 +08005689 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5690 final int newPermission = getNetworkPermission(newNc);
5691 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005692 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005693 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005694 } catch (RemoteException e) {
5695 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005696 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005697 }
5698
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005699 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005700 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005701 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005702 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005703 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005704
Chalard Jeanf213ca12018-01-16 18:43:05 +09005705 updateUids(nai, prevNc, newNc);
5706
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005707 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005708 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5709 // the change we're processing can't affect any requests, it can only affect the listens
5710 // on this network. We might have been called by rematchNetworkAndRequests when a
5711 // network changed foreground state.
5712 processListenRequests(nai, true);
5713 } else {
5714 // If the requestable capabilities have changed or the score changed, we can't have been
5715 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005716 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005717 try {
5718 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5719 } catch (RemoteException e) {
5720 e.rethrowFromSystemServer();
5721 }
Paul Jensene0988542015-06-25 15:30:08 -04005722 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005723 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005724
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005725 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005726 final boolean oldMetered = prevNc.isMetered();
5727 final boolean newMetered = newNc.isMetered();
5728 final boolean meteredChanged = oldMetered != newMetered;
5729
5730 if (meteredChanged) {
5731 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5732 mRestrictBackground);
5733 }
5734
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005735 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005736 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005737
5738 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005739 if (meteredChanged || roamingChanged) {
5740 notifyIfacesChangedForNetworkStats();
5741 }
5742 }
5743
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005744 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005745 // Tell VPNs about updated capabilities, since they may need to
5746 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005747 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005748 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005749 }
5750
Chalard Jeanf213ca12018-01-16 18:43:05 +09005751 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5752 NetworkCapabilities newNc) {
5753 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5754 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5755 if (null == prevRanges) prevRanges = new ArraySet<>();
5756 if (null == newRanges) newRanges = new ArraySet<>();
5757 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5758
5759 prevRanges.removeAll(newRanges);
5760 newRanges.removeAll(prevRangesCopy);
5761
5762 try {
5763 if (!newRanges.isEmpty()) {
5764 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5765 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005766 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005767 }
5768 if (!prevRanges.isEmpty()) {
5769 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5770 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005771 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005772 }
5773 } catch (Exception e) {
5774 // Never crash!
5775 loge("Exception in updateUids: " + e);
5776 }
5777 }
5778
Hugo Benichief502882017-09-01 01:23:32 +00005779 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005780 ensureRunningOnConnectivityServiceThread();
5781
Erik Kline736353a2018-03-21 07:18:33 -07005782 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005783 // Ignore updates for disconnected networks
5784 return;
5785 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005786 // newLp is already a defensive copy.
5787 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005788 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005789 log("Update of LinkProperties for " + nai.name() +
5790 "; created=" + nai.created +
5791 "; everConnected=" + nai.everConnected);
5792 }
lucaslin25a4ec32018-11-28 12:51:55 +08005793 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005794 }
5795
Paul Jensenc8b9a742014-09-30 15:37:41 -04005796 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005797 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5798 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005799 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005800 if (nr.isListen()) continue;
Chalard Jean05ab6812018-05-02 21:14:54 +09005801 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005802 }
5803 }
5804
Chalard Jean05ab6812018-05-02 21:14:54 +09005805 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5806 int score = 0;
5807 int serial = 0;
5808 if (nai != null) {
5809 score = nai.getCurrentScore();
5810 serial = nai.factorySerialNumber;
5811 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005812 if (VDBG || DDBG){
5813 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5814 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005815 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005816 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5817 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005818 }
5819 }
5820
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005821 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5822 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005823 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005824 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005825 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5826 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005827 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005828 sendIntent(nri.mPendingIntent, intent);
5829 }
5830 // else not handled
5831 }
5832
5833 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5834 mPendingIntentWakeLock.acquire();
5835 try {
5836 if (DBG) log("Sending " + pendingIntent);
5837 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5838 } catch (PendingIntent.CanceledException e) {
5839 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5840 mPendingIntentWakeLock.release();
5841 releasePendingNetworkRequest(pendingIntent);
5842 }
5843 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5844 }
5845
5846 @Override
5847 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5848 String resultData, Bundle resultExtras) {
5849 if (DBG) log("Finished sending " + pendingIntent);
5850 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005851 // Release with a delay so the receiving client has an opportunity to put in its
5852 // own request.
5853 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005854 }
5855
Chalard Jeanf19db372018-01-26 19:24:40 +09005856 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005857 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005858 if (nri.messenger == null) {
5859 return; // Default request has no msgr
5860 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005861 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005862 // TODO: check if defensive copies of data is needed.
5863 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005864 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005865 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5866 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005867 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005868 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005869 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005870 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5871 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005872 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005873 // For this notification, arg1 contains the blocked status.
5874 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005875 break;
5876 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005877 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005878 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005879 break;
5880 }
5881 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005882 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005883 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005884 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005885 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005886 break;
5887 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005888 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005889 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005890 break;
5891 }
junyulai05986c62018-08-07 19:50:45 +08005892 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005893 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005894 msg.arg1 = arg1;
5895 break;
5896 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005897 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005898 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005899 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005900 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005901 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005902 String notification = ConnectivityManager.getCallbackName(notificationType);
5903 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005904 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005905 nri.messenger.send(msg);
5906 } catch (RemoteException e) {
5907 // may occur naturally in the race of binder death.
5908 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5909 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005910 }
5911
Hugo Benichidba33db2017-03-23 22:40:44 +09005912 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5913 bundle.putParcelable(t.getClass().getSimpleName(), t);
5914 }
5915
Paul Jensenc8b9a742014-09-30 15:37:41 -04005916 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005917 if (nai.numRequestNetworkRequests() != 0) {
5918 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5919 NetworkRequest nr = nai.requestAt(i);
5920 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005921 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005922 loge("Dead network still had at least " + nr);
5923 break;
5924 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005925 }
5926 nai.asyncChannel.disconnect();
5927 }
5928
Robert Greenwalt7b816022014-04-18 15:25:25 -07005929 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5930 if (oldNetwork == null) {
5931 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5932 return;
5933 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005934 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005935
5936 // If we get here it means that the last linger timeout for this network expired. So there
5937 // must be no other active linger timers, and we must stop lingering.
5938 oldNetwork.clearLingerState();
5939
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005940 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005941 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005942 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005943 } else {
5944 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005945 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5946 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005947 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005948 }
5949
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005950 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005951 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005952
Paul Jensen27b02b72014-07-14 12:03:33 -04005953 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005954 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005955 } catch (Exception e) {
5956 loge("Exception setting default network :" + e);
5957 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005958
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005959 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005960 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005961 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005962 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005963 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005964 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5965 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005966 }
5967
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005968 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005969 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5970 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5971 NetworkRequest nr = nri.request;
5972 if (!nr.isListen()) continue;
5973 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5974 nai.removeRequest(nri.request.requestId);
5975 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5976 }
5977 }
5978
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005979 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005980 try {
5981 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5982 } catch (RemoteException e) {
5983 e.rethrowFromSystemServer();
5984 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005985 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5986 }
5987
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005988 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5989 NetworkRequest nr = nri.request;
5990 if (!nr.isListen()) continue;
5991 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5992 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005993 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005994 }
5995 }
5996 }
5997
Paul Jensen2161a8e2014-09-11 11:00:39 -04005998 // Handles a network appearing or improving its score.
5999 //
6000 // - Evaluates all current NetworkRequests that can be
6001 // satisfied by newNetwork, and reassigns to newNetwork
6002 // any such requests for which newNetwork is the best.
6003 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006004 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006005 // needed. A network is needed if it is the best network for
6006 // one or more NetworkRequests, or if it is a VPN.
6007 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006008 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006009 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006010 //
6011 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6012 // networks that have no chance (i.e. even if validated)
6013 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006014 //
6015 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6016 // it does not remove NetworkRequests that other Networks could better satisfy.
6017 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6018 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6019 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006020 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006021 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006022 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6023 // performed to tear down unvalidated networks that have no chance (i.e. even if
6024 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006025 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006026 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006027 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006028 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006029 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006030 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006031
6032 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6033 final int score = newNetwork.getCurrentScore();
6034
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006035 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006036
Paul Jensen2161a8e2014-09-11 11:00:39 -04006037 // Find and migrate to this Network any NetworkRequests for
6038 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006039 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6040 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006041 NetworkCapabilities nc = newNetwork.networkCapabilities;
6042 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006043 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006044 // Process requests in the first pass and listens in the second pass. This allows us to
6045 // change a network's capabilities depending on which requests it has. This is only
6046 // correct if the change in capabilities doesn't affect whether the network satisfies
6047 // requests or not, and doesn't affect the network's score.
6048 if (nri.request.isListen()) continue;
6049
Hugo Benichicd952782017-09-20 11:20:14 +09006050 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006051 final boolean satisfies = newNetwork.satisfies(nri.request);
6052 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006053 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006054 log("Network " + newNetwork.name() + " was already satisfying" +
6055 " request " + nri.request.requestId + ". No change.");
6056 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006057 keep = true;
6058 continue;
6059 }
6060
6061 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006062 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006063 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006064 // next check if it's better than any current network we're using for
6065 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006066 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006067 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006068 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006069 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006070 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006071 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006072 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006073 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006074 if (VDBG || DDBG){
6075 log(" accepting network in place of " + currentNetwork.name());
6076 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006077 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006078 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006079 affectedNetworks.add(currentNetwork);
6080 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006081 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006082 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006083 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006084 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006085 if (!newNetwork.addRequest(nri.request)) {
6086 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6087 }
6088 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006089 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006090 // Tell NetworkFactories about the new score, so they can stop
6091 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006092 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006093 // network. Think about if there is a way to reduce this. Push
6094 // netid->request mapping to each factory?
Chalard Jean05ab6812018-05-02 21:14:54 +09006095 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006096 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006097 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006098 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006099 if (currentNetwork != null) {
6100 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6101 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006102 }
6103 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006104 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006105 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6106 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006107 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006108 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6109 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6110 // This means this code doesn't have to handle the case where "currentNetwork" no
6111 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6112 if (DBG) {
6113 log("Network " + newNetwork.name() + " stopped satisfying" +
6114 " request " + nri.request.requestId);
6115 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006116 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006117 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006118 clearNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09006119 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006120 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006121 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6122 newNetwork.name() +
6123 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006124 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006125 // TODO: Technically, sending CALLBACK_LOST here is
6126 // incorrect if there is a replacement network currently
6127 // connected that can satisfy nri, which is a request
6128 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006129 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6130 // so this code is only incorrect for a network that loses
6131 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006132 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006133 }
6134 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006135 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006136 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006137 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006138 makeDefault(newNetwork);
6139 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006140 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006141 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006142 // Have a new default network, release the transition wakelock in
6143 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006144 }
6145
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006146 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6147 Slog.wtf(TAG, String.format(
6148 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006149 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006150 }
6151 if (newNetwork.getCurrentScore() != score) {
6152 Slog.wtf(TAG, String.format(
6153 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006154 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006155 }
6156
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006157 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006158 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6159 // If the network went from background to foreground or vice versa, we need to update
6160 // its foreground state. It is safe to do this after rematching the requests because
6161 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6162 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006163 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006164 } else {
6165 processListenRequests(newNetwork, false);
6166 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006167
Paul Jensencf4c2c62015-07-01 14:16:32 -04006168 // do this after the default net is switched, but
6169 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006170 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006171
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006172 // Linger any networks that are no longer needed. This should be done after sending the
6173 // available callback for newNetwork.
6174 for (NetworkAgentInfo nai : affectedNetworks) {
6175 updateLingerState(nai, now);
6176 }
6177 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6178 // does not need to be done in any particular order.
6179 updateLingerState(newNetwork, now);
6180
Paul Jensencf4c2c62015-07-01 14:16:32 -04006181 if (isNewDefault) {
6182 // Maintain the illusion: since the legacy API only
6183 // understands one network at a time, we must pretend
6184 // that the current default network disconnected before
6185 // the new one connected.
6186 if (oldDefaultNetwork != null) {
6187 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6188 oldDefaultNetwork, true);
6189 }
6190 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6191 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6192 notifyLockdownVpn(newNetwork);
6193 }
6194
Robert Greenwalt7b816022014-04-18 15:25:25 -07006195 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006196 // Notify battery stats service about this network, both the normal
6197 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006198 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006199 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006200 final IBatteryStats bs = BatteryStatsService.getService();
6201 final int type = newNetwork.networkInfo.getType();
6202
6203 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6204 bs.noteNetworkInterfaceType(baseIface, type);
6205 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6206 final String stackedIface = stacked.getInterfaceName();
6207 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006208 }
6209 } catch (RemoteException ignored) {
6210 }
6211
Robert Greenwalt152ed372014-12-17 17:19:53 -08006212 // This has to happen after the notifyNetworkCallbacks as that tickles each
6213 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006214 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006215 // and will generally do a dns request so they can ensureRouteToHost and if
6216 // they do that before the callbacks happen they'll use the default network.
6217 //
6218 // TODO: Is there still a race here? We send the broadcast
6219 // after sending the callback, but if the app can receive the
6220 // broadcast before the callback, it might still break.
6221 //
6222 // This *does* introduce a race where if the user uses the new api
6223 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6224 // they may get old info. Reverse this after the old startUsing api is removed.
6225 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006226 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6227 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006228 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006229 // legacy type tracker filters out repeat adds
6230 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6231 }
6232 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006233
6234 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6235 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6236 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6237 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6238 if (newNetwork.isVPN()) {
6239 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6240 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006241 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006242 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6243 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006244 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006245 if (nai.getLingerExpiry() > 0) {
6246 // This network has active linger timers and no requests, but is not
6247 // lingering. Linger it.
6248 //
6249 // One way (the only way?) this can happen if this network is unvalidated
6250 // and became unneeded due to another network improving its score to the
6251 // point where this network will no longer be able to satisfy any requests
6252 // even if it validates.
6253 updateLingerState(nai, now);
6254 } else {
6255 if (DBG) log("Reaping " + nai.name());
6256 teardownUnneededNetwork(nai);
6257 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006258 }
6259 }
6260 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006261 }
6262
Paul Jensen1c7ba022015-06-16 14:27:36 -04006263 /**
6264 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6265 * being disconnected.
6266 * @param changed If only one Network's score or capabilities have been modified since the last
6267 * time this function was called, pass this Network in this argument, otherwise pass
6268 * null.
6269 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6270 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6271 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6272 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6273 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006274 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006275 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006276 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6277 // to avoid the slowness. It is not simply enough to process just "changed", for
6278 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006279 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006280
6281 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6282 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6283 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006284 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006285 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006286 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006287 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006288 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6289 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6290 // Rematch higher scoring networks first to prevent requests first matching a lower
6291 // scoring network and then a higher scoring network, which could produce multiple
6292 // callbacks and inadvertently unlinger networks.
6293 Arrays.sort(nais);
6294 for (NetworkAgentInfo nai : nais) {
6295 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006296 // Only reap the last time through the loop. Reaping before all rematching
6297 // is complete could incorrectly teardown a network that hasn't yet been
6298 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006299 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006300 : ReapUnvalidatedNetworks.REAP,
6301 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006302 }
6303 }
6304 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006305
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006306 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006307 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006308 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006309 // For now only update icons for default connection.
6310 // TODO: Update WiFi and cellular icons separately. b/17237507
6311 if (!isDefaultNetwork(nai)) return;
6312
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006313 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006314 // Don't repeat publish.
6315 if (newInetCondition == mDefaultInetConditionPublished) return;
6316
6317 mDefaultInetConditionPublished = newInetCondition;
6318 sendInetConditionBroadcast(nai.networkInfo);
6319 }
6320
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006321 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006322 synchronized (mVpns) {
6323 if (mLockdownTracker != null) {
6324 if (nai != null && nai.isVPN()) {
6325 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6326 } else {
6327 mLockdownTracker.onNetworkInfoChanged();
6328 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006329 }
6330 }
6331 }
6332
Robert Greenwalt7b816022014-04-18 15:25:25 -07006333 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006334 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006335 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006336 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006337 synchronized (networkAgent) {
6338 oldInfo = networkAgent.networkInfo;
6339 networkAgent.networkInfo = newInfo;
6340 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006341 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006342
Robert Greenwalt7b816022014-04-18 15:25:25 -07006343 if (DBG) {
6344 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6345 (oldInfo == null ? "null" : oldInfo.getState()) +
6346 " to " + state);
6347 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006348
Robin Lee585e2482016-05-01 23:00:00 +01006349 if (!networkAgent.created
6350 && (state == NetworkInfo.State.CONNECTED
6351 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006352
6353 // A network that has just connected has zero requests and is thus a foreground network.
6354 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6355
Robert Greenwalt7b816022014-04-18 15:25:25 -07006356 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006357 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006358 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006359 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006360 (networkAgent.networkMisc == null ||
6361 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006362 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006363 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006364 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006365 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006366 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006367 loge("Error creating network " + networkAgent.network.netId + ": "
6368 + e.getMessage());
6369 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006370 }
Paul Jenseneec75412014-08-04 12:21:19 -04006371 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006372 }
6373
6374 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6375 networkAgent.everConnected = true;
6376
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006377 if (networkAgent.linkProperties == null) {
6378 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6379 }
6380
Erik Kline736353a2018-03-21 07:18:33 -07006381 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006382 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6383 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006384
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006385 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6386 // command must be sent after updating LinkProperties to maximize chances of
6387 // NetworkMonitor seeing the correct LinkProperties when starting.
6388 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6389 try {
6390 networkAgent.networkMonitor().notifyNetworkConnected();
6391 } catch (RemoteException e) {
6392 e.rethrowFromSystemServer();
6393 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006394 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006395
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006396 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6397 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6398 // capabilities, so it only needs to be done once on initial connect, not every time the
6399 // network's capabilities change. Note that we do this before rematching the network,
6400 // so we could decide to tear it down immediately afterwards. That's fine though - on
6401 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6402 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006403 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006404
Varun Anand4fa80e82019-02-06 10:13:38 -08006405 if (networkAgent.isVPN()) {
6406 updateAllVpnsCapabilities();
6407 }
6408
Paul Jensen2161a8e2014-09-11 11:00:39 -04006409 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006410 final long now = SystemClock.elapsedRealtime();
6411 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006412
6413 // This has to happen after matching the requests, because callbacks are just requests.
6414 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006415 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006416 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006417 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006418 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006419 }
Chalard Jean392971c2018-05-11 20:19:20 +09006420 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006421 if (networkAgent.isVPN()) {
6422 // As the active or bound network changes for apps, broadcast the default proxy, as
6423 // apps may need to update their proxy data. This is called after disconnecting from
6424 // VPN to make sure we do not broadcast the old proxy data.
6425 // TODO(b/122649188): send the broadcast only to VPN users.
6426 mProxyTracker.sendProxyBroadcast();
6427 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006428 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6429 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006430 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006431 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006432 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006433 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006434 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6435 networkAgent.networkCapabilities);
6436 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6437 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006438 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6439 ConnectivityManager.CALLBACK_SUSPENDED :
6440 ConnectivityManager.CALLBACK_RESUMED));
6441 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006442 }
6443 }
6444
Robert Greenwaltac96c522014-06-03 16:43:57 -07006445 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006446 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006447 if (score < 0) {
6448 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6449 "). Bumping score to min of 0");
6450 score = 0;
6451 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006452
Paul Jensen2161a8e2014-09-11 11:00:39 -04006453 final int oldScore = nai.getCurrentScore();
6454 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006455
Paul Jensen85cf78e2015-06-25 13:25:07 -04006456 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006457
Paul Jensenc8b9a742014-09-30 15:37:41 -04006458 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006459 }
6460
Erik Klinec75d4fa2017-02-15 19:59:17 +09006461 // Notify only this one new request of the current state. Transfer all the
6462 // current state by calling NetworkCapabilities and LinkProperties callbacks
6463 // so that callers can be guaranteed to have as close to atomicity in state
6464 // transfer as can be supported by this current API.
6465 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006466 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006467 if (nri.mPendingIntent != null) {
6468 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6469 // Attempt no subsequent state pushes where intents are involved.
6470 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006471 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006472
junyulai05986c62018-08-07 19:50:45 +08006473 final boolean metered = nai.networkCapabilities.isMetered();
6474 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6475 metered, mRestrictBackground);
6476 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6477 }
6478
6479 /**
6480 * Notify of the blocked state apps with a registered callback matching a given NAI.
6481 *
6482 * Unlike other callbacks, blocked status is different between each individual uid. So for
6483 * any given nai, all requests need to be considered according to the uid who filed it.
6484 *
6485 * @param nai The target NetworkAgentInfo.
6486 * @param oldMetered True if the previous network capabilities is metered.
6487 * @param newRestrictBackground True if data saver is enabled.
6488 */
6489 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6490 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6491
6492 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6493 NetworkRequest nr = nai.requestAt(i);
6494 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6495 final int uidRules = mUidRules.get(nri.mUid);
6496 final boolean oldBlocked, newBlocked;
6497 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6498 // between these two calls.
6499 synchronized (mVpns) {
6500 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6501 oldRestrictBackground);
6502 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6503 newRestrictBackground);
6504 }
6505 if (oldBlocked != newBlocked) {
6506 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6507 encodeBool(newBlocked));
6508 }
6509 }
6510 }
6511
6512 /**
6513 * Notify apps with a given UID of the new blocked state according to new uid rules.
6514 * @param uid The uid for which the rules changed.
6515 * @param newRules The new rules to apply.
6516 */
6517 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6518 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6519 final boolean metered = nai.networkCapabilities.isMetered();
6520 final boolean oldBlocked, newBlocked;
6521 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6522 // rules changed event. And this function actually loop through all connected nai and
6523 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6524 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6525 synchronized (mVpns) {
6526 oldBlocked = isUidNetworkingWithVpnBlocked(
6527 uid, mUidRules.get(uid), metered, mRestrictBackground);
6528 newBlocked = isUidNetworkingWithVpnBlocked(
6529 uid, newRules, metered, mRestrictBackground);
6530 }
6531 if (oldBlocked == newBlocked) {
6532 return;
6533 }
6534 final int arg = encodeBool(newBlocked);
6535 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6536 NetworkRequest nr = nai.requestAt(i);
6537 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6538 if (nri != null && nri.mUid == uid) {
6539 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6540 }
6541 }
6542 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006543 }
6544
Robert Greenwalt8d482522015-06-24 13:23:42 -07006545 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006546 // The NetworkInfo we actually send out has no bearing on the real
6547 // state of affairs. For example, if the default connection is mobile,
6548 // and a request for HIPRI has just gone away, we need to pretend that
6549 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6550 // the state to DISCONNECTED, even though the network is of type MOBILE
6551 // and is still connected.
6552 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6553 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006554 if (state != DetailedState.DISCONNECTED) {
6555 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006556 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006557 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006558 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006559 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6560 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6561 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6562 if (info.isFailover()) {
6563 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6564 nai.networkInfo.setFailover(false);
6565 }
6566 if (info.getReason() != null) {
6567 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6568 }
6569 if (info.getExtraInfo() != null) {
6570 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6571 }
6572 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006573 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006574 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006575 if (newDefaultAgent != null) {
6576 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6577 newDefaultAgent.networkInfo);
6578 } else {
6579 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6580 }
6581 }
6582 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6583 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006584 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006585 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006586 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006587 }
6588 }
6589 }
6590
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006591 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006592 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006593 String notification = ConnectivityManager.getCallbackName(notifyType);
6594 log("notifyType " + notification + " for " + networkAgent.name());
6595 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006596 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6597 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006598 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6599 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006600 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6601 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006602 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006603 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006604 } else {
6605 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6606 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006607 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006608 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006609
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006610 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6611 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6612 }
6613
Jeff Sharkey69736342014-12-08 14:50:12 -08006614 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006615 * Returns the list of all interfaces that could be used by network traffic that does not
6616 * explicitly specify a network. This includes the default network, but also all VPNs that are
6617 * currently connected.
6618 *
6619 * Must be called on the handler thread.
6620 */
6621 private Network[] getDefaultNetworks() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006622 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006623 ArrayList<Network> defaultNetworks = new ArrayList<>();
6624 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6625 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6626 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6627 defaultNetworks.add(nai.network);
6628 }
6629 }
6630 return defaultNetworks.toArray(new Network[0]);
6631 }
6632
6633 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006634 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6635 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006636 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006637 private void notifyIfacesChangedForNetworkStats() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006638 ensureRunningOnConnectivityServiceThread();
6639 String activeIface = null;
6640 LinkProperties activeLinkProperties = getActiveLinkProperties();
6641 if (activeLinkProperties != null) {
6642 activeIface = activeLinkProperties.getInterfaceName();
6643 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006644 try {
Varun Anandd33cbc62019-02-07 14:13:13 -08006645 mStatsService.forceUpdateIfaces(
6646 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006647 } catch (Exception ignored) {
6648 }
6649 }
6650
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006651 @Override
6652 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006653 int user = UserHandle.getUserId(Binder.getCallingUid());
6654 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006655 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006656 return mVpns.get(user).addAddress(address, prefixLength);
6657 }
6658 }
6659
6660 @Override
6661 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006662 int user = UserHandle.getUserId(Binder.getCallingUid());
6663 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006664 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006665 return mVpns.get(user).removeAddress(address, prefixLength);
6666 }
6667 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006668
6669 @Override
6670 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006671 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006672 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006673 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006674 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006675 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006676 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006677 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006678 mHandler.post(() -> {
6679 // Update VPN's capabilities based on updated underlying network set.
6680 updateAllVpnsCapabilities();
6681 notifyIfacesChangedForNetworkStats();
6682 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006683 }
6684 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006685 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006686
6687 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006688 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006689 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006690 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006691 }
6692
6693 @Override
junyulai7c469172019-01-16 20:23:34 +08006694 public void startNattKeepalive(Network network, int intervalSeconds,
6695 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006696 enforceKeepalivePermission();
6697 mKeepaliveTracker.startNattKeepalive(
6698 getNetworkAgentInfoForNetwork(network),
junyulai7c469172019-01-16 20:23:34 +08006699 intervalSeconds, cb,
junyulai06835112019-01-03 18:50:15 +08006700 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006701 }
6702
6703 @Override
junyulai215b8772019-01-15 11:32:44 +08006704 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006705 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006706 String dstAddr) {
6707 enforceKeepalivePermission();
6708 mKeepaliveTracker.startNattKeepalive(
6709 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006710 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006711 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6712 }
6713
6714 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006715 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006716 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006717 enforceKeepalivePermission();
6718 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006719 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006720 }
6721
6722 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006723 public void stopKeepalive(Network network, int slot) {
6724 mHandler.sendMessage(mHandler.obtainMessage(
junyulai06835112019-01-03 18:50:15 +08006725 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006726 }
6727
6728 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006729 public void factoryReset() {
6730 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006731
6732 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6733 return;
6734 }
6735
Robin Lee3b3dd942015-05-12 18:14:58 +01006736 final int userId = UserHandle.getCallingUserId();
6737
Stuart Scottf1fb3972015-04-02 18:00:02 -07006738 // Turn airplane mode off
6739 setAirplaneMode(false);
6740
Stuart Scotte3e314d2015-04-20 14:07:45 -07006741 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6742 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006743 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006744 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006745 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006746 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006747 }
6748
Stuart Scotte3e314d2015-04-20 14:07:45 -07006749 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006750 // Remove always-on package
6751 synchronized (mVpns) {
6752 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6753 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006754 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006755 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6756 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006757
Hugo Benichi69744342017-11-27 10:57:16 +09006758 // Turn Always-on VPN off
6759 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6760 final long ident = Binder.clearCallingIdentity();
6761 try {
6762 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6763 mLockdownEnabled = false;
6764 setLockdownTracker(null);
6765 } finally {
6766 Binder.restoreCallingIdentity(ident);
6767 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006768 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006769
Hugo Benichi69744342017-11-27 10:57:16 +09006770 // Turn VPN off
6771 VpnConfig vpnConfig = getVpnConfig(userId);
6772 if (vpnConfig != null) {
6773 if (vpnConfig.legacy) {
6774 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6775 } else {
6776 // Prevent this app (packagename = vpnConfig.user) from initiating
6777 // VPN connections in the future without user intervention.
6778 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006779
Hugo Benichi69744342017-11-27 10:57:16 +09006780 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6781 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006782 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006783 }
6784 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006785
6786 Settings.Global.putString(mContext.getContentResolver(),
6787 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006788 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006789
Ricky Wai44dcbde2018-01-23 04:09:45 +00006790 @Override
6791 public byte[] getNetworkWatchlistConfigHash() {
6792 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6793 if (nwm == null) {
6794 loge("Unable to get NetworkWatchlistManager");
6795 return null;
6796 }
6797 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6798 return nwm.getWatchlistConfigHash();
6799 }
6800
Paul Jensencf4c2c62015-07-01 14:16:32 -04006801 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006802 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6803 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006804 }
6805
6806 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006807 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6808 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6809 }
6810
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006811 @VisibleForTesting
6812 public boolean hasService(String name) {
6813 return ServiceManager.checkService(name) != null;
6814 }
6815
Hugo Benichi64901e52017-10-19 14:42:40 +09006816 @VisibleForTesting
6817 protected IpConnectivityMetrics.Logger metricsLogger() {
6818 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6819 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006820 }
6821
6822 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006823 int[] transports = nai.networkCapabilities.getTransportTypes();
6824 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006825 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006826
6827 private static boolean toBool(int encodedBoolean) {
6828 return encodedBoolean != 0; // Only 0 means false.
6829 }
6830
6831 private static int encodeBool(boolean b) {
6832 return b ? 1 : 0;
6833 }
mswest46386886f2018-03-12 10:34:34 -07006834
6835 @Override
6836 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6837 FileDescriptor err, String[] args, ShellCallback callback,
6838 ResultReceiver resultReceiver) {
6839 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6840 }
6841
6842 private class ShellCmd extends ShellCommand {
6843
6844 @Override
6845 public int onCommand(String cmd) {
6846 if (cmd == null) {
6847 return handleDefaultCommands(cmd);
6848 }
6849 final PrintWriter pw = getOutPrintWriter();
6850 try {
6851 switch (cmd) {
6852 case "airplane-mode":
6853 final String action = getNextArg();
6854 if ("enable".equals(action)) {
6855 setAirplaneMode(true);
6856 return 0;
6857 } else if ("disable".equals(action)) {
6858 setAirplaneMode(false);
6859 return 0;
6860 } else if (action == null) {
6861 final ContentResolver cr = mContext.getContentResolver();
6862 final int enabled = Settings.Global.getInt(cr,
6863 Settings.Global.AIRPLANE_MODE_ON);
6864 pw.println(enabled == 0 ? "disabled" : "enabled");
6865 return 0;
6866 } else {
6867 onHelp();
6868 return -1;
6869 }
6870 default:
6871 return handleDefaultCommands(cmd);
6872 }
6873 } catch (Exception e) {
6874 pw.println(e);
6875 }
6876 return -1;
6877 }
6878
6879 @Override
6880 public void onHelp() {
6881 PrintWriter pw = getOutPrintWriter();
6882 pw.println("Connectivity service commands:");
6883 pw.println(" help");
6884 pw.println(" Print this help text.");
6885 pw.println(" airplane-mode [enable|disable]");
6886 pw.println(" Turn airplane mode on or off.");
6887 pw.println(" airplane-mode");
6888 pw.println(" Get airplane mode.");
6889 }
6890 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006891
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006892 @GuardedBy("mVpns")
6893 private Vpn getVpnIfOwner() {
6894 final int uid = Binder.getCallingUid();
6895 final int user = UserHandle.getUserId(uid);
6896
6897 final Vpn vpn = mVpns.get(user);
6898 if (vpn == null) {
6899 return null;
6900 } else {
6901 final VpnInfo info = vpn.getVpnInfo();
6902 return (info == null || info.ownerUid != uid) ? null : vpn;
6903 }
6904 }
6905
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006906 /**
6907 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6908 * for testing.
6909 */
6910 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6911 if (checkNetworkStackPermission()) {
6912 return null;
6913 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006914 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006915 Vpn vpn = getVpnIfOwner();
6916 if (vpn != null) {
6917 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006918 }
6919 }
6920 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6921 + "permission");
6922 }
6923
6924 /**
6925 * @param connectionInfo the connection to resolve.
6926 * @return {@code uid} if the connection is found and the app has permission to observe it
6927 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6928 * connection is not found.
6929 */
6930 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6931 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6932 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6933 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6934 }
6935
6936 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6937 connectionInfo.local, connectionInfo.remote);
6938
6939 /* Filter out Uids not associated with the VPN. */
6940 if (vpn != null && !vpn.appliesToUid(uid)) {
6941 return INVALID_UID;
6942 }
6943
6944 return uid;
6945 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006946
6947 @Override
6948 public boolean isCallerCurrentAlwaysOnVpnApp() {
6949 synchronized (mVpns) {
6950 Vpn vpn = getVpnIfOwner();
6951 return vpn != null && vpn.getAlwaysOn();
6952 }
6953 }
6954
6955 @Override
6956 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6957 synchronized (mVpns) {
6958 Vpn vpn = getVpnIfOwner();
6959 return vpn != null && vpn.getLockdown();
6960 }
6961 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006962}