blob: bb7406a56772b2249da3b18f8bcea559647adbc3 [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;
Xiao Maed25f9c2019-06-12 16:31:14 +090023import static android.net.ConnectivityManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090024import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070025import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070026import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070027import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070028import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslin783f2212019-10-22 18:27:33 +080029import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wang8ea15c962019-05-23 16:29:30 +080030import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
31import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040032import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090033import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
35import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
36import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090038import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090039import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
lucasline252a742019-03-12 13:08:03 +080040import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090041import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060042import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080043import static android.net.NetworkPolicyManager.RULE_NONE;
44import static android.net.NetworkPolicyManager.uidRulesToString;
Lorenzo Colitti80986d92019-03-22 00:28:28 +090045import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070046import static android.os.Process.INVALID_UID;
47import static android.system.OsConstants.IPPROTO_TCP;
48import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060049
Hugo Benichia0385682017-03-22 17:07:57 +090050import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060051
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +000052import android.annotation.NonNull;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080053import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080054import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090055import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070056import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070057import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.ContentResolver;
59import android.content.Context;
60import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070061import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070062import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070063import android.database.ContentObserver;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090064import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070065import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.ConnectivityManager;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090067import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.IConnectivityManager;
Luke Huang65914772019-03-16 00:31:46 +080069import android.net.IDnsResolver;
dalyk7301aa42018-03-05 12:42:22 -050070import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080071import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050072import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070073import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090074import android.net.INetworkMonitor;
75import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070076import android.net.INetworkPolicyListener;
77import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070078import android.net.INetworkStatsService;
junyulai7c469172019-01-16 20:23:34 +080079import android.net.ISocketKeepaliveCallback;
markchien26299ed2019-02-27 14:56:11 +080080import android.net.ITetheringEventCallback;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090081import android.net.InetAddresses;
Xiao Mad91ec092019-04-10 19:01:52 +090082import android.net.IpMemoryStore;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090083import android.net.IpPrefix;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080084import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070085import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010086import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080087import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070088import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070089import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070090import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070091import android.net.NetworkConfig;
Chalard Jean05ab6812018-05-02 21:14:54 +090092import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070095import android.net.NetworkMisc;
Lorenzo Colittiac955b32019-05-31 15:41:29 +090096import android.net.NetworkMonitorManager;
Jeff Sharkey75d31892018-01-18 22:01:59 +090097import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070098import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070099import android.net.NetworkRequest;
lucaslinc2bac512019-11-07 16:47:56 +0800100import android.net.NetworkScore;
Etan Cohen859748f2017-04-03 17:42:34 -0700101import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900102import android.net.NetworkStack;
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +0900103import android.net.NetworkStackClient;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700104import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700105import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +0000106import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900107import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -0400108import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -0700109import android.net.RouteInfo;
junyulai06835112019-01-03 18:50:15 +0800110import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400111import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -0400112import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600113import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900114import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900115import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700116import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900117import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900118import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900119import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800121import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700122import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700124import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700125import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700126import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.os.Looper;
128import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700129import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700130import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900131import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700132import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700133import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700134import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800135import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900136import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900137import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700138import android.os.ShellCallback;
139import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900140import android.os.SystemClock;
Anil Admal4661b742019-04-05 10:06:37 -0700141import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700142import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400143import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700145import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700146import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700147import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700148import android.text.TextUtils;
Chalard Jean8dcbaa52019-11-07 17:39:53 +0900149import android.util.ArrayMap;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900150import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700151import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600152import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900153import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800154import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700155import android.util.SparseArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700156import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700157import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Wink Savilleab9321d2013-06-29 21:10:57 -0700159import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400160import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400161import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700162import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANde602212019-01-30 15:22:01 +0900163import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700164import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700165import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800166import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700167import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900168import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700169import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600170import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700171import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900172import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700173import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700174import com.android.server.am.BatteryStatsService;
Chalard Jeand5603302019-05-30 14:58:29 +0900175import com.android.server.connectivity.AutodestructReference;
John Spurlockbf991a82013-06-24 14:20:23 -0400176import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900177import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500178import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900179import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900180import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100181import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700182import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900183import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700184import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600185import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900186import com.android.server.connectivity.NetworkNotificationManager;
187import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700188import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900189import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800190import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700191import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100192import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500193import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700194import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700195import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900196import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700197import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600198
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700199import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700200
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700201import org.xmlpull.v1.XmlPullParser;
202import org.xmlpull.v1.XmlPullParserException;
203
204import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700206import java.io.FileNotFoundException;
207import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700208import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700210import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700211import java.net.InetAddress;
212import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700214import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700215import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900216import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800217import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700218import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700219import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700220import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700221import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700222import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900223import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600224import java.util.SortedSet;
225import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
227/**
228 * @hide
229 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800230public class ConnectivityService extends IConnectivityManager.Stub
231 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900232 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
Chalard Jean4133a122018-06-04 13:33:12 +0900234 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900235 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900236 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900237 private static final String NETWORK_ARG = "networks";
238 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900239
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900240 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900241 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
242 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900244 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700245
Niklas Lindgrenafc5f9b2018-12-07 11:08:04 +0100246 /**
247 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
248 * by OEMs for configuration purposes, as this value is overridden by
249 * Settings.Global.CAPTIVE_PORTAL_HTTP_URL.
250 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
251 * (preferably via runtime resource overlays).
252 */
253 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
254 "http://connectivitycheck.gstatic.com/generate_204";
255
Jeff Sharkey899223b2012-08-04 15:24:58 -0700256 // TODO: create better separation between radio types and network types
257
Robert Greenwalt42acef32009-08-12 16:08:25 -0700258 // how long to wait before switching back to a radio's default network
259 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
260 // system property that can override the above value
261 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
262 "android.telephony.apn-restore";
263
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900264 // How long to wait before putting up a "This network doesn't have an Internet connection,
265 // connect anyway?" dialog after the user selects a network that doesn't validate.
266 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
267
lucaslind2e045e02019-01-24 15:55:30 +0800268 // How long to dismiss network notification.
269 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
270
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900271 // Default to 30s linger time-out. Modifiable only for testing.
272 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
273 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
274 @VisibleForTesting
275 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
276
Jeremy Joslin79294842014-12-03 17:15:28 -0800277 // How long to delay to removal of a pending intent based request.
278 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
279 private final int mReleasePendingIntentDelayMs;
280
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900281 private MockableSystemProperties mSystemProperties;
282
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800283 private Tethering mTethering;
284
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +0000285 @VisibleForTesting
286 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700287
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700288 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700289
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900290 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700291 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900292 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700293
Hugo Benichi69744342017-11-27 10:57:16 +0900294 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
295 // a direct call to LockdownVpnTracker.isEnabled().
296 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700297 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900298 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700299 private LockdownVpnTracker mLockdownTracker;
300
junyulai05986c62018-08-07 19:50:45 +0800301 /**
302 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
303 * handler thread, they don't need a lock.
304 */
305 private SparseIntArray mUidRules = new SparseIntArray();
306 /** Flag indicating if background data is restricted. */
307 private boolean mRestrictBackground;
308
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900309 private final Context mContext;
310 private final Dependencies mDeps;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700311 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700312 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
Luke Huang4e25ec62018-09-27 16:58:23 +0800314 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800315 @VisibleForTesting
Luke Huang65914772019-03-16 00:31:46 +0800316 protected IDnsResolver mDnsResolver;
317 @VisibleForTesting
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800318 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800319 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700320 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900321 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700322
Benedict Wonga341fbc2018-11-09 14:45:34 -0800323 /**
324 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
325 * instances.
326 */
327 @GuardedBy("mTNSLock")
328 private TestNetworkService mTNS;
329
330 private final Object mTNSLock = new Object();
331
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700332 private String mCurrentTcpBufferSizes;
333
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900334 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900335 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
336 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900337
Paul Jensenb10e37f2014-11-25 12:33:08 -0500338 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400339 // Tear down networks that have no chance (e.g. even if validated) of becoming
340 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500341 // all networks have been rematched against all NetworkRequests.
342 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400343 // Don't reap networks. This should be passed when some networks have not yet been
344 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500345 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900346 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500347
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900348 private enum UnneededFor {
349 LINGER, // Determine whether this network is unneeded and should be lingered.
350 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
351 }
352
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700353 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700354 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700355 * from one net to another. Clear happens when we get a new
356 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
357 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700358 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700359 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700360
Robert Greenwalt434203a2010-10-11 16:00:27 -0700361 /**
362 * used internally to reload global proxy settings
363 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700365
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700366 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400367 * PAC manager has received new port.
368 */
369 private static final int EVENT_PROXY_HAS_CHANGED = 16;
370
Robert Greenwalte049c232014-04-11 15:53:27 -0700371 /**
372 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700373 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700374 */
375 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
376
Robert Greenwalt7b816022014-04-18 15:25:25 -0700377 /**
378 * used internally when registering NetworkAgents
379 * obj = Messenger
380 */
381 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
382
Robert Greenwalt9258c642014-03-26 16:47:06 -0700383 /**
384 * used to add a network request
385 * includes a NetworkRequestInfo
386 */
387 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
388
389 /**
390 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900391 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700392 * cancel it.
393 * includes a NetworkRequestInfo
394 */
395 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
396
397 /**
398 * used to add a network listener - no request
399 * includes a NetworkRequestInfo
400 */
401 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
402
403 /**
404 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400405 * arg1 = UID of caller
406 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700407 */
408 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
409
Robert Greenwalta67be032014-05-16 15:49:14 -0700410 /**
411 * used internally when registering NetworkFactories
412 * obj = Messenger
413 */
414 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
415
Robert Greenwalt27711812014-06-25 16:45:57 -0700416 /**
417 * used internally to expire a wakelock when transitioning
418 * from one net to another. Expire happens when we fail to find
419 * a new network (typically after 1 minute) -
420 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
421 * a replacement network.
422 */
423 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
424
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700425 /**
426 * Used internally to indicate the system is ready.
427 */
428 private static final int EVENT_SYSTEM_READY = 25;
429
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800430 /**
431 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400432 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800433 */
434 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
435
436 /**
437 * used to remove a pending intent and its associated network request.
438 * arg1 = UID of caller
439 * obj = PendingIntent
440 */
441 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
442
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900443 /**
444 * used to specify whether a network should be used even if unvalidated.
445 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
446 * arg2 = whether to remember this choice in the future (1 or 0)
447 * obj = network
448 */
449 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
450
451 /**
452 * used to ask the user to confirm a connection to an unvalidated network.
453 * obj = network
454 */
455 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700456
Erik Klineda4bfa82015-04-30 12:58:40 +0900457 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700458 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900459 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700460 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900461
Paul Jensen694f2b82015-06-17 14:15:39 -0400462 /**
463 * used to add a network listener with a pending intent
464 * obj = NetworkRequestInfo
465 */
466 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
467
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900468 /**
469 * used to specify whether a network should not be penalized when it becomes unvalidated.
470 */
471 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
472
473 /**
474 * used to trigger revalidation of a network.
475 */
476 private static final int EVENT_REVALIDATE_NETWORK = 36;
477
Erik Klinea24d4592018-01-11 21:07:29 +0900478 // Handle changes in Private DNS settings.
479 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
480
dalyk7301aa42018-03-05 12:42:22 -0500481 // Handle private DNS validation status updates.
482 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
483
junyulai05986c62018-08-07 19:50:45 +0800484 /**
485 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
486 */
487 private static final int EVENT_UID_RULES_CHANGED = 39;
488
489 /**
490 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
491 */
492 private static final int EVENT_DATA_SAVER_CHANGED = 40;
493
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900494 /**
495 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
496 * been tested.
497 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
498 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
499 * arg2 = NetID.
500 */
Chalard Jeanafdecd52019-09-26 18:03:47 +0900501 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900502
503 /**
504 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
505 * config was resolved.
506 * obj = PrivateDnsConfig
507 * arg2 = netid
508 */
Chalard Jeanafdecd52019-09-26 18:03:47 +0900509 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900510
511 /**
512 * Request ConnectivityService display provisioning notification.
513 * arg1 = Whether to make the notification visible.
514 * arg2 = NetID.
515 * obj = Intent to be launched when notification selected by user, null if !arg1.
516 */
Chalard Jeanafdecd52019-09-26 18:03:47 +0900517 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900518
519 /**
lucaslind2e045e02019-01-24 15:55:30 +0800520 * This event can handle dismissing notification by given network id.
521 */
Chalard Jeanafdecd52019-09-26 18:03:47 +0900522 private static final int EVENT_TIMEOUT_NOTIFICATION = 44;
lucaslind2e045e02019-01-24 15:55:30 +0800523
524 /**
lucasline252a742019-03-12 13:08:03 +0800525 * Used to specify whether a network should be used even if connectivity is partial.
526 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
527 * false)
528 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
529 * obj = network
530 */
531 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
532
533 /**
lucaslin783f2212019-10-22 18:27:33 +0800534 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
535 * Both of the arguments are bitmasks, and the value of bits come from
536 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
537 * arg1 = A bitmask to describe which probes are completed.
538 * arg2 = A bitmask to describe which probes are successful.
539 */
540 public static final int EVENT_PROBE_STATUS_CHANGED = 46;
541
542 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900543 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
544 * should be shown.
545 */
Chalard Jeanafdecd52019-09-26 18:03:47 +0900546 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900547
548 /**
549 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
550 * should be hidden.
551 */
Chalard Jeanafdecd52019-09-26 18:03:47 +0900552 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900553
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900554 private static String eventName(int what) {
555 return sMagicDecoderRing.get(what, Integer.toString(what));
556 }
557
Luke Huang65914772019-03-16 00:31:46 +0800558 private static IDnsResolver getDnsResolver() {
559 return IDnsResolver.Stub
560 .asInterface(ServiceManager.getService("dnsresolver"));
561 }
562
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900563 /** Handler thread used for both of the handlers below. */
564 @VisibleForTesting
565 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700566 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700567 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700568 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700569 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900570 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700571
Mike Lockwood0f79b542009-08-14 14:18:49 -0400572 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800573 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400574
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700575 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700576 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800577 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700578
Chalard Jean52c2aa72018-06-07 16:44:04 +0900579 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
580 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000581 @VisibleForTesting
582 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400583
Erik Klineda4bfa82015-04-30 12:58:40 +0900584 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700585
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400586 private UserManager mUserManager;
587
Chalard Jean4133a122018-06-04 13:33:12 +0900588 private NetworkConfig[] mNetConfigs;
589 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700590
Robert Greenwalt50393202011-06-21 17:26:14 -0700591 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900592 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700593
Valentin Iftimec86ebba2019-09-24 13:32:13 +0200594 private Set<String> mWolSupportedInterfaces;
595
Chalard Jean4133a122018-06-04 13:33:12 +0900596 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400597
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900598 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900599 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900600 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900601
Robert Greenwalt34524f02014-05-18 16:22:10 -0700602 // sequence number of NetworkRequests
603 private int mNextNetworkRequestId = 1;
604
Erik Kline7523eb32015-07-09 18:24:03 +0900605 // NetworkRequest activity String log entries.
606 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
607 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
608
Hugo Benichic2ae2872016-07-11 11:05:12 +0900609 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900610 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900611 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
612
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900613 private static final int MAX_WAKELOCK_LOGS = 20;
614 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900615 private int mTotalWakelockAcquisitions = 0;
616 private int mTotalWakelockReleases = 0;
617 private long mTotalWakelockDurationMs = 0;
618 private long mMaxWakelockDurationMs = 0;
619 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900620
Hugo Benichif9fdf872016-07-28 17:53:06 +0900621 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900622
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700623 @GuardedBy("mBandwidthRequests")
624 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
625
Erik Kline065ab6e2016-10-02 18:02:14 +0900626 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900627 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900628
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900629 @VisibleForTesting
630 final MultipathPolicyTracker mMultipathPolicyTracker;
631
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 /**
633 * Implements support for the legacy "one network per network type" model.
634 *
635 * We used to have a static array of NetworkStateTrackers, one for each
636 * network type, but that doesn't work any more now that we can have,
637 * for example, more that one wifi network. This class stores all the
638 * NetworkAgentInfo objects that support a given type, but the legacy
639 * API will only see the first one.
640 *
641 * It serves two main purposes:
642 *
643 * 1. Provide information about "the network for a given type" (since this
644 * API only supports one).
645 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
646 * the first network for a given type changes, or if the default network
647 * changes.
648 */
Chalard Jean612522b2019-04-10 23:07:55 +0900649 @VisibleForTesting
650 static class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900652 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900653 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900654
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 /**
656 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
657 * Each list holds references to all NetworkAgentInfos that are used to
658 * satisfy requests for that network type.
659 *
660 * This array is built out at startup such that an unsupported network
661 * doesn't get an ArrayList instance, making this a tristate:
662 * unsupported, supported but not active and active.
663 *
664 * The actual lists are populated when we scan the network types that
665 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900666 *
667 * Threading model:
668 * - addSupportedType() is only called in the constructor
669 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
670 * They are therefore not thread-safe with respect to each other.
671 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
672 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
673 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700674 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900675 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean612522b2019-04-10 23:07:55 +0900676 @NonNull
677 private final ConnectivityService mService;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700678
Chalard Jean612522b2019-04-10 23:07:55 +0900679 LegacyTypeTracker(@NonNull ConnectivityService service) {
680 mService = service;
681 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700682 }
683
684 public void addSupportedType(int type) {
685 if (mTypeLists[type] != null) {
686 throw new IllegalStateException(
687 "legacy list for type " + type + "already initialized");
688 }
Chalard Jean4133a122018-06-04 13:33:12 +0900689 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
691
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700692 public boolean isTypeSupported(int type) {
693 return isNetworkTypeValid(type) && mTypeLists[type] != null;
694 }
695
696 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900697 synchronized (mTypeLists) {
698 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
699 return mTypeLists[type].get(0);
700 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700701 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900702 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700703 }
704
Robert Greenwalt8d482522015-06-24 13:23:42 -0700705 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900706 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900707 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700708 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900709 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900710 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900711 }
712 }
713
714 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700715 public void add(int type, NetworkAgentInfo nai) {
716 if (!isTypeSupported(type)) {
717 return; // Invalid network type.
718 }
719 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
720
721 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
722 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700723 return;
724 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900725 synchronized (mTypeLists) {
726 list.add(nai);
727 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900728
729 // Send a broadcast if this is the first network of its type or if it's the default.
Chalard Jean612522b2019-04-10 23:07:55 +0900730 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900731 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700732 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
Chalard Jean612522b2019-04-10 23:07:55 +0900733 mService.sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700734 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700735 }
736
Lorenzo Colittia793a672014-07-31 23:20:17 +0900737 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900738 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900739 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
740 if (list == null || list.isEmpty()) {
741 return;
742 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900743 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900744
Hugo Benichi78caa2582016-06-21 09:48:07 +0900745 synchronized (mTypeLists) {
746 if (!list.remove(nai)) {
747 return;
748 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900749 }
750
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900751 if (wasFirstNetwork || wasDefault) {
Chalard Jean72102e52019-04-11 14:09:07 +0900752 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
753 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900754 }
755
756 if (!list.isEmpty() && wasFirstNetwork) {
757 if (DBG) log("Other network available for type " + type +
758 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900759 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean72102e52019-04-11 14:09:07 +0900760 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
761 mService.isDefaultNetwork(replacement));
762 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900763 }
764 }
765
766 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900767 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
768 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700769 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900770 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700771 }
772 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700773
Robert Greenwalt8d482522015-06-24 13:23:42 -0700774 // send out another legacy broadcast - currently only used for suspend/unsuspend
775 // toggle
776 public void update(NetworkAgentInfo nai) {
Chalard Jean612522b2019-04-10 23:07:55 +0900777 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700778 final DetailedState state = nai.networkInfo.getDetailedState();
779 for (int type = 0; type < mTypeLists.length; type++) {
780 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700781 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900782 final boolean isFirst = contains && (nai == list.get(0));
783 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700784 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean612522b2019-04-10 23:07:55 +0900785 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700786 }
787 }
788 }
789
Lorenzo Colittia793a672014-07-31 23:20:17 +0900790 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900791 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900792 String state = (nai.networkInfo != null) ?
793 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
794 "???/???";
795 return name + " " + state;
796 }
797
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700798 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900799 pw.println("mLegacyTypeTracker:");
800 pw.increaseIndent();
801 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700802 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900803 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700804 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900805 pw.println();
806 pw.println("Current state:");
807 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900808 synchronized (mTypeLists) {
809 for (int type = 0; type < mTypeLists.length; type++) {
810 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
811 for (NetworkAgentInfo nai : mTypeLists[type]) {
812 pw.println(type + " " + naiToString(nai));
813 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900814 }
815 }
816 pw.decreaseIndent();
817 pw.decreaseIndent();
818 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700819 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700820 }
Chalard Jean612522b2019-04-10 23:07:55 +0900821 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700822
Vishnu Nair5c010902017-10-26 10:08:50 -0700823 /**
824 * Helper class which parses out priority arguments and dumps sections according to their
825 * priority. If priority arguments are omitted, function calls the legacy dump command.
826 */
827 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
828 @Override
829 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
830 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
831 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
832 }
833
834 @Override
835 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
836 doDump(fd, pw, args, asProto);
837 }
838
839 @Override
840 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
841 doDump(fd, pw, args, asProto);
842 }
843 };
844
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900845 /**
846 * Dependencies of ConnectivityService, for injection in tests.
847 */
848 @VisibleForTesting
849 public static class Dependencies {
850 /**
851 * Get system properties to use in ConnectivityService.
852 */
853 public MockableSystemProperties getSystemProperties() {
854 return new MockableSystemProperties();
855 }
856
857 /**
858 * Create a HandlerThread to use in ConnectivityService.
859 */
860 public HandlerThread makeHandlerThread() {
861 return new HandlerThread("ConnectivityServiceThread");
862 }
863
864 /**
865 * Get a reference to the NetworkStackClient.
866 */
867 public NetworkStackClient getNetworkStack() {
868 return NetworkStackClient.getInstance();
869 }
870
871 /**
872 * @see Tethering
873 */
874 public Tethering makeTethering(@NonNull Context context,
875 @NonNull INetworkManagementService nms,
876 @NonNull INetworkStatsService statsService,
877 @NonNull INetworkPolicyManager policyManager,
878 @NonNull TetheringDependencies tetheringDeps) {
879 return new Tethering(context, nms, statsService, policyManager,
880 IoThread.get().getLooper(), getSystemProperties(), tetheringDeps);
881 }
882
883 /**
884 * @see ProxyTracker
885 */
886 public ProxyTracker makeProxyTracker(@NonNull Context context,
887 @NonNull Handler connServiceHandler) {
888 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
889 }
890
891 /**
892 * @see NetIdManager
893 */
894 public NetIdManager makeNetIdManager() {
895 return new NetIdManager();
896 }
897
898 /**
899 * @see NetworkUtils#queryUserAccess(int, int)
900 */
901 public boolean queryUserAccess(int uid, int netId) {
902 return NetworkUtils.queryUserAccess(uid, netId);
903 }
904
905 /**
906 * @see MultinetworkPolicyTracker
907 */
908 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
909 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
910 return new MultinetworkPolicyTracker(c, h, r);
911 }
912
913 /**
914 * @see ServiceManager#checkService(String)
915 */
916 public boolean hasService(@NonNull String name) {
917 return ServiceManager.checkService(name) != null;
918 }
919
920 /**
921 * @see IpConnectivityMetrics.Logger
922 */
923 public IpConnectivityMetrics.Logger getMetricsLogger() {
924 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
925 "no IpConnectivityMetrics service");
926 }
927
928 /**
929 * @see IpConnectivityMetrics
930 */
931 public IIpConnectivityMetrics getIpConnectivityMetrics() {
932 return IIpConnectivityMetrics.Stub.asInterface(
933 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
934 }
935 }
936
Jeff Sharkey899223b2012-08-04 15:24:58 -0700937 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700938 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900939 this(context, netManager, statsService, policyManager, getDnsResolver(),
940 new IpConnectivityLog(), NetdService.getInstance(), new Dependencies());
Hugo Benichif9fdf872016-07-28 17:53:06 +0900941 }
942
943 @VisibleForTesting
944 protected ConnectivityService(Context context, INetworkManagementService netManager,
945 INetworkStatsService statsService, INetworkPolicyManager policyManager,
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900946 IDnsResolver dnsresolver, IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800947 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800948
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900949 mDeps = checkNotNull(deps, "missing Dependencies");
950 mSystemProperties = mDeps.getSystemProperties();
951 mNetIdManager = mDeps.makeNetIdManager();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900952
Hugo Benichif9fdf872016-07-28 17:53:06 +0900953 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900954 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900955 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900956 mNetworkRequests.put(mDefaultRequest, defaultNRI);
957 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900958
Chalard Jeandda156a2018-01-10 21:19:32 +0900959 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900960 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700961
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700962 // The default WiFi request is a background request so that apps using WiFi are
963 // migrated to a better network (typically ethernet) when one comes up, instead
964 // of staying on WiFi forever.
965 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
966 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
967
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900968 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900969 mHandlerThread.start();
970 mHandler = new InternalHandler(mHandlerThread.getLooper());
971 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700972
Jeremy Joslin79294842014-12-03 17:15:28 -0800973 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
974 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
975
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900976 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900977
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800979 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800980 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700981 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900982 mPolicyManagerInternal = checkNotNull(
983 LocalServices.getService(NetworkPolicyManagerInternal.class),
984 "missing NetworkPolicyManagerInternal");
Luke Huang65914772019-03-16 00:31:46 +0800985 mDnsResolver = checkNotNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900986 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900987
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +0000988 mNetd = netd;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700989 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700990 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700991
junyulai05986c62018-08-07 19:50:45 +0800992 // To ensure uid rules are synchronized with Network Policy, register for
993 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
994 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700995 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900996 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700997 } catch (RemoteException e) {
998 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700999 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001000 }
1001
1002 final PowerManager powerManager = (PowerManager) context.getSystemService(
1003 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001004 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1005 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
1006 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08001007 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001008
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001009 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001010
Wink Saville51f456f2013-04-23 14:26:51 -07001011 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001012 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -07001013 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001014 String[] naStrings = context.getResources().getStringArray(
1015 com.android.internal.R.array.networkAttributes);
1016 for (String naString : naStrings) {
1017 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001018 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -07001019 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -07001020 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001021 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -07001022 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001023 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001024 }
Wink Saville51f456f2013-04-23 14:26:51 -07001025 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
1026 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
1027 n.type);
1028 continue;
1029 }
Wink Saville975c8482011-04-07 14:23:45 -07001030 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001031 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -07001032 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001033 continue;
1034 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001035 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001036
Wink Saville975c8482011-04-07 14:23:45 -07001037 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001038 mNetworksDefined++;
1039 } catch(Exception e) {
1040 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -07001041 }
1042 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07001043
1044 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
1045 if (mNetConfigs[TYPE_VPN] == null) {
1046 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
1047 // don't need to add TYPE_VPN to mNetConfigs.
1048 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
1049 mNetworksDefined++; // used only in the log() statement below.
1050 }
1051
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09001052 // Do the same for Ethernet, since it's often not specified in the configs, although many
1053 // devices can use it via USB host adapters.
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09001054 if (mNetConfigs[TYPE_ETHERNET] == null && mDeps.hasService(Context.ETHERNET_SERVICE)) {
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09001055 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
1056 mNetworksDefined++;
1057 }
1058
Wink Saville5e56bc52013-07-29 15:00:57 -07001059 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001060
Robert Greenwalt50393202011-06-21 17:26:14 -07001061 mProtectedNetworks = new ArrayList<Integer>();
1062 int[] protectedNetworks = context.getResources().getIntArray(
1063 com.android.internal.R.array.config_protectedNetworks);
1064 for (int p : protectedNetworks) {
1065 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
1066 mProtectedNetworks.add(p);
1067 } else {
1068 if (DBG) loge("Ignoring protectedNetwork " + p);
1069 }
1070 }
1071
Valentin Iftimec86ebba2019-09-24 13:32:13 +02001072 mWolSupportedInterfaces = new ArraySet(
1073 mContext.getResources().getStringArray(
1074 com.android.internal.R.array.config_wakeonlan_supported_interfaces));
1075
soma, kawata0f1cd1d2019-05-23 09:30:40 +09001076 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1077
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09001078 mTethering = deps.makeTethering(mContext, mNMS, mStatsService, mPolicyManager,
1079 makeTetheringDependencies());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08001080
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00001081 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001082
Varun Anand4fa80e82019-02-06 10:13:38 -08001083 // Set up the listener for user state for creating user VPNs.
1084 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001085 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +01001086 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07001087 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07001088 intentFilter.addAction(Intent.ACTION_USER_ADDED);
1089 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +00001090 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07001091 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -08001092 mIntentReceiver,
1093 UserHandle.ALL,
1094 intentFilter,
1095 null /* broadcastPermission */,
1096 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +00001097 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
1098 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +09001099
junyulai2454b692018-11-01 17:16:31 +08001100 // Listen to package add and removal events for all users.
1101 intentFilter = new IntentFilter();
1102 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +08001103 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +08001104 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1105 intentFilter.addDataScheme("package");
1106 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -08001107 mIntentReceiver,
1108 UserHandle.ALL,
1109 intentFilter,
1110 null /* broadcastPermission */,
1111 mHandler);
junyulai2454b692018-11-01 17:16:31 +08001112
Chia-chi Yeh008ff392011-05-23 15:08:29 -07001113 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001114 mNMS.registerObserver(mTethering);
1115 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -07001116 } catch (RemoteException e) {
1117 loge("Error registering observer :" + e);
1118 }
1119
Erik Klineda4bfa82015-04-30 12:58:40 +09001120 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1121 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -08001122
Remi NGUYEN VANf9354792019-08-27 20:21:58 +09001123 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext, mHandler);
Chalard Jean4133a122018-06-04 13:33:12 +09001124 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -04001125
junyulai0c666972019-03-04 22:45:36 +08001126 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +09001127 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
1128 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +09001129
1130 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1131 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1132 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1133 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1134 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1135 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1136 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09001137
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09001138 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +09001139 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001140 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +09001141
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001142 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1143
Luke Huang65914772019-03-16 00:31:46 +08001144 mDnsManager = new DnsManager(mContext, mDnsResolver, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001145 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001147
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09001148 private TetheringDependencies makeTetheringDependencies() {
1149 return new TetheringDependencies() {
Erik Kline465ff3a2018-03-09 14:18:02 +09001150 @Override
1151 public boolean isTetheringSupported() {
1152 return ConnectivityService.this.isTetheringSupported();
1153 }
Erik Kline72302902018-06-14 17:36:40 +09001154 @Override
1155 public NetworkRequest getDefaultNetworkRequest() {
1156 return mDefaultRequest;
1157 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001158 };
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001159 }
1160
Chalard Jean26400492018-04-18 20:18:38 +09001161 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1162 final NetworkCapabilities netCap = new NetworkCapabilities();
1163 netCap.addCapability(NET_CAPABILITY_INTERNET);
Chalard Jean26400492018-04-18 20:18:38 +09001164 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1165 netCap.setSingleUid(uid);
1166 return netCap;
1167 }
1168
Chalard Jeandda156a2018-01-10 21:19:32 +09001169 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001170 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001171 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001172 netCap.addCapability(NET_CAPABILITY_INTERNET);
Erik Klineda4bfa82015-04-30 12:58:40 +09001173 if (transportType > -1) {
1174 netCap.addTransportType(transportType);
1175 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001176 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001177 }
1178
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001179 // Used only for testing.
1180 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001181 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001182 // changing ContentResolver to make registerContentObserver non-final).
1183 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1184 // by subclassing SettingsObserver.
1185 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001186 void updateAlwaysOnNetworks() {
1187 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001188 }
1189
Erik Kline736353a2018-03-21 07:18:33 -07001190 // See FakeSettingsProvider comment above.
1191 @VisibleForTesting
1192 void updatePrivateDnsSettings() {
1193 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1194 }
1195
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001196 private void handleAlwaysOnNetworkRequest(
1197 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001198 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001199 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1200 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001201 if (enable == isEnabled) {
1202 return; // Nothing to do.
1203 }
1204
1205 if (enable) {
1206 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001207 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001208 } else {
Etan Cohenddb720a2019-01-08 12:09:18 -08001209 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1210 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001211 }
1212 }
1213
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001214 private void handleConfigureAlwaysOnNetworks() {
1215 handleAlwaysOnNetworkRequest(
1216 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1217 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1218 false);
1219 }
1220
Erik Klineda4bfa82015-04-30 12:58:40 +09001221 private void registerSettingsCallbacks() {
1222 // Watch for global HTTP proxy changes.
1223 mSettingsObserver.observe(
1224 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1225 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1226
1227 // Watch for whether or not to keep mobile data always on.
1228 mSettingsObserver.observe(
1229 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001230 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1231
1232 // Watch for whether or not to keep wifi always on.
1233 mSettingsObserver.observe(
1234 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1235 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001236 }
1237
Erik Klinea24d4592018-01-11 21:07:29 +09001238 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001239 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1240 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001241 }
1242 }
1243
Robert Greenwalt34524f02014-05-18 16:22:10 -07001244 private synchronized int nextNetworkRequestId() {
1245 return mNextNetworkRequestId++;
1246 }
1247
Chalard Jeanc0982912018-06-07 16:11:34 +09001248 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001249 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001250 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1251 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001253 state = nai.getNetworkState();
1254 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001256 final NetworkInfo info = new NetworkInfo(networkType, 0,
1257 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1259 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001260 final NetworkCapabilities capabilities = new NetworkCapabilities();
1261 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1262 !info.isRoaming());
1263 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001264 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001265 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001266 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001267 return state;
1268 } else {
1269 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001270 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001271 }
1272
junyulai4a192e22018-06-13 15:00:37 +08001273 @VisibleForTesting
1274 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001275 if (network == null) {
1276 return null;
1277 }
Erik Kline736353a2018-03-21 07:18:33 -07001278 return getNetworkAgentInfoForNetId(network.netId);
1279 }
1280
1281 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001282 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001283 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001284 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001285 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001286
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001287 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001288 synchronized (mVpns) {
1289 if (!mLockdownEnabled) {
1290 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001291 Vpn vpn = mVpns.get(user);
1292 if (vpn != null && vpn.appliesToUid(uid)) {
1293 return vpn.getUnderlyingNetworks();
1294 }
1295 }
1296 }
1297 return null;
1298 }
1299
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001300 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001301 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001302
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001303 final Network[] networks = getVpnUnderlyingNetworks(uid);
1304 if (networks != null) {
1305 // getUnderlyingNetworks() returns:
1306 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1307 // empty array => the VPN explicitly said "no default network".
1308 // non-empty array => the VPN specified one or more default networks; we use the
1309 // first one.
1310 if (networks.length > 0) {
1311 nai = getNetworkAgentInfoForNetwork(networks[0]);
1312 } else {
1313 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001314 }
1315 }
1316
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001317 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001318 return nai.getNetworkState();
1319 } else {
1320 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001321 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001322 }
1323
1324 /**
1325 * Check if UID should be blocked from using the network with the given LinkProperties.
1326 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001327 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1328 boolean ignoreBlocked) {
1329 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001330 if (ignoreBlocked) {
1331 return false;
1332 }
Robin Lee17e61832016-05-09 13:46:28 +01001333 synchronized (mVpns) {
1334 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001335 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001336 return true;
1337 }
1338 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001339 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001340 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001341 }
1342
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001343 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001344 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1345 return;
1346 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001347 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001348 synchronized (mBlockedAppUids) {
1349 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001350 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001351 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001352 blocked = false;
1353 } else {
1354 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001355 }
1356 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001357 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1358 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1359 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001360 }
1361
junyulai05986c62018-08-07 19:50:45 +08001362 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1363 boolean blocked) {
1364 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1365 return;
1366 }
1367 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1368 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1369 nri.mUid, nri.request.requestId, net.netId));
1370 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1371 }
1372
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001373 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001374 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1375 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001376 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001377 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001378 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001379 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1380
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001381 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001382 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001383 }
Hugo Benichi69744342017-11-27 10:57:16 +09001384 synchronized (mVpns) {
1385 if (mLockdownTracker != null) {
1386 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1387 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001388 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001389 }
1390
1391 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 * Return NetworkInfo for the active (i.e., connected) network interface.
1393 * It is assumed that at most one network is active at a time. If more
1394 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001395 * @return the info for the active network, or {@code null} if none is
1396 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001398 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001400 enforceAccessPermission();
1401 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001402 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001403 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001404 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1405 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
1407
Paul Jensen31a94f42015-02-13 14:18:39 -05001408 @Override
1409 public Network getActiveNetwork() {
1410 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001411 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001412 }
1413
1414 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001415 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001416 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001417 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001418 }
1419
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001420 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001421 final int user = UserHandle.getUserId(uid);
1422 int vpnNetId = NETID_UNSET;
1423 synchronized (mVpns) {
1424 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001425 // TODO : now that capabilities contain the UID, the appliesToUid test should
1426 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001427 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1428 }
1429 NetworkAgentInfo nai;
1430 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001431 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001432 if (nai != null) {
1433 final NetworkCapabilities requiredCaps =
1434 createDefaultNetworkCapabilitiesForUid(uid);
1435 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1436 return nai.network;
1437 }
1438 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001439 }
1440 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001441 if (nai != null
1442 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1443 nai = null;
1444 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001445 return nai != null ? nai.network : null;
1446 }
1447
Lorenzo Colitti18660282016-07-04 12:55:44 +09001448 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001449 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1450 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001451 final int uid = Binder.getCallingUid();
1452 NetworkState state = getUnfilteredActiveNetworkState(uid);
1453 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001454 }
1455
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001456 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001457 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001458 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001459 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001460 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001461 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001462 }
1463
1464 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 public NetworkInfo getNetworkInfo(int networkType) {
1466 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001467 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001468 if (getVpnUnderlyingNetworks(uid) != null) {
1469 // A VPN is active, so we may need to return one of its underlying networks. This
1470 // information is not available in LegacyTypeTracker, so we have to get it from
1471 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001472 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001473 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001474 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001475 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001476 }
1477 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001478 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001479 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001482 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001483 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001484 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001485 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001486 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001487 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001488 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001489 return state.networkInfo;
1490 } else {
1491 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001492 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001493 }
1494
1495 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 public NetworkInfo[] getAllNetworkInfo() {
1497 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001498 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001499 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1500 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001501 NetworkInfo info = getNetworkInfo(networkType);
1502 if (info != null) {
1503 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001506 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 }
1508
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001509 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001510 public Network getNetworkForType(int networkType) {
1511 enforceAccessPermission();
1512 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001513 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001514 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001515 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001516 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001517 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001518 }
1519
1520 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001521 public Network[] getAllNetworks() {
1522 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001523 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001524 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001525 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001526 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001527 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001528 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001529 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001530 }
1531
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001532 @Override
1533 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1534 // The basic principle is: if an app's traffic could possibly go over a
1535 // network, without the app doing anything multinetwork-specific,
1536 // (hence, by "default"), then include that network's capabilities in
1537 // the array.
1538 //
1539 // In the normal case, app traffic only goes over the system's default
1540 // network connection, so that's the only network returned.
1541 //
1542 // With a VPN in force, some app traffic may go into the VPN, and thus
1543 // over whatever underlying networks the VPN specifies, while other app
1544 // traffic may go over the system default network (e.g.: a split-tunnel
1545 // VPN, or an app disallowed by the VPN), so the set of networks
1546 // returned includes the VPN's underlying networks and the system
1547 // default.
1548 enforceAccessPermission();
1549
Chalard Jean4133a122018-06-04 13:33:12 +09001550 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001551
1552 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001553 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001554 if (nc != null) {
1555 result.put(nai.network, nc);
1556 }
1557
Hugo Benichi69744342017-11-27 10:57:16 +09001558 synchronized (mVpns) {
1559 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001560 Vpn vpn = mVpns.get(userId);
1561 if (vpn != null) {
1562 Network[] networks = vpn.getUnderlyingNetworks();
1563 if (networks != null) {
1564 for (Network network : networks) {
1565 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001566 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001567 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001568 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001569 }
1570 }
1571 }
1572 }
1573 }
1574 }
1575
1576 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1577 out = result.values().toArray(out);
1578 return out;
1579 }
1580
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001581 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001582 public boolean isNetworkSupported(int networkType) {
1583 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001584 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001585 }
1586
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001587 /**
1588 * Return LinkProperties for the active (i.e., connected) default
1589 * network interface. It is assumed that at most one default network
1590 * is active at a time. If more than one is active, it is indeterminate
1591 * which will be returned.
1592 * @return the ip properties for the active network, or {@code null} if
1593 * none is active
1594 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001595 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001596 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001597 enforceAccessPermission();
1598 final int uid = Binder.getCallingUid();
1599 NetworkState state = getUnfilteredActiveNetworkState(uid);
1600 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001601 }
1602
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001603 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001604 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001605 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001606 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1607 if (nai != null) {
1608 synchronized (nai) {
1609 return new LinkProperties(nai.linkProperties);
1610 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001611 }
1612 return null;
1613 }
1614
Robert Greenwalt12e67352014-05-13 21:41:06 -07001615 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001616 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001617 public LinkProperties getLinkProperties(Network network) {
1618 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001619 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1620 }
1621
1622 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1623 if (nai == null) {
1624 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001625 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001626 synchronized (nai) {
1627 return new LinkProperties(nai.linkProperties);
1628 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001629 }
1630
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001631 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001632 if (nai != null) {
1633 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001634 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001635 return networkCapabilitiesRestrictedForCallerPermissions(
1636 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001637 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001638 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001639 }
1640 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001641 return null;
1642 }
1643
1644 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001645 public NetworkCapabilities getNetworkCapabilities(Network network) {
1646 enforceAccessPermission();
1647 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1648 }
1649
Chalard Jeanb03a6222018-04-11 21:09:10 +09001650 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001651 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001652 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001653 if (!checkSettingsPermission(callerPid, callerUid)) {
1654 newNc.setUids(null);
1655 newNc.setSSID(null);
1656 }
Etan Cohen836ad572018-12-30 17:59:59 -08001657 if (newNc.getNetworkSpecifier() != null) {
1658 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1659 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001660 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001661 }
1662
Chalard Jeanb552c462018-02-21 18:43:54 +09001663 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1664 if (!checkSettingsPermission()) {
1665 nc.setSingleUid(Binder.getCallingUid());
1666 }
1667 }
1668
Chalard Jean26aa91a2018-03-20 19:13:57 +09001669 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1670 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1671 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1672 }
1673 }
1674
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001675 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001676 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001677 // Require internal since we're handing out IMSI details
1678 enforceConnectivityInternalPermission();
1679
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001680 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001681 for (Network network : getAllNetworks()) {
1682 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1683 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001684 // TODO (b/73321673) : NetworkState contains a copy of the
1685 // NetworkCapabilities, which may contain UIDs of apps to which the
1686 // network applies. Should the UIDs be cleared so as not to leak or
1687 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001688 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001689 }
1690 }
1691 return result.toArray(new NetworkState[result.size()]);
1692 }
1693
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001694 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001695 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001696 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001697 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1698 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1699 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001700 }
1701
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001702 @Override
1703 public boolean isActiveNetworkMetered() {
1704 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001705
Varun Anandc51b06d2019-02-25 17:22:02 -08001706 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001707 if (caps != null) {
1708 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1709 } else {
1710 // Always return the most conservative value
1711 return true;
1712 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001713 }
1714
Jeff Sharkey216c1812012-08-05 14:29:23 -07001715 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1716 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001717 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001718 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001719 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001720 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001721 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001722
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001723 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001724 * Ensures that the system cannot call a particular method.
1725 */
1726 private boolean disallowedBecauseSystemCaller() {
1727 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admal4661b742019-04-05 10:06:37 -07001728 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
1729 // for devices launched with Q and above. However, existing devices upgrading to Q and
1730 // above must continued to be supported for few more releases.
1731 if (isSystem(Binder.getCallingUid()) && SystemProperties.getInt(
1732 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001733 log("This method exists only for app backwards compatibility"
1734 + " and must not be called by system services.");
1735 return true;
1736 }
1737 return false;
1738 }
1739
1740 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 * Ensure that a network route exists to deliver traffic to the specified
1742 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001743 * @param networkType the type of the network over which traffic to the
1744 * specified host is to be routed
1745 * @param hostAddress the IP address of the host to which the route is
1746 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 * @return {@code true} on success, {@code false} on failure
1748 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001749 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001750 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001751 if (disallowedBecauseSystemCaller()) {
1752 return false;
1753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001755 if (mProtectedNetworks.contains(networkType)) {
1756 enforceConnectivityInternalPermission();
1757 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001758
Chad Brubakerc0234532014-02-14 13:24:29 -08001759 InetAddress addr;
1760 try {
1761 addr = InetAddress.getByAddress(hostAddress);
1762 } catch (UnknownHostException e) {
1763 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1764 return false;
1765 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001768 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 return false;
1770 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001771
1772 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1773 if (nai == null) {
1774 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1775 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1776 } else {
1777 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1778 }
1779 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001780 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001781
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001782 DetailedState netState;
1783 synchronized (nai) {
1784 netState = nai.networkInfo.getDetailedState();
1785 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001786
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001787 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001788 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001789 log("requestRouteToHostAddress on down network "
1790 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001791 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001792 }
1793 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001795
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001796 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001797 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001798 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001799 LinkProperties lp;
1800 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001801 synchronized (nai) {
1802 lp = nai.linkProperties;
1803 netId = nai.network.netId;
1804 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001805 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001806 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1807 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001808 } finally {
1809 Binder.restoreCallingIdentity(token);
1810 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001811 }
1812
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001813 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001814 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001815 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001816 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001817 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001818 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001819 if (bestRoute.getGateway().equals(addr)) {
1820 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001821 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001822 } else {
1823 // if we will connect to this through another route, add a direct route
1824 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001825 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001826 }
1827 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001828 if (DBG) log("Adding legacy route " + bestRoute +
1829 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001830 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001831 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001832 } catch (Exception e) {
1833 // never crash - catch them all
1834 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001835 return false;
1836 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001837 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839
dalyk7301aa42018-03-05 12:42:22 -05001840 @VisibleForTesting
1841 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1842 @Override
1843 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1844 String hostname, boolean validated) {
1845 try {
1846 mHandler.sendMessage(mHandler.obtainMessage(
1847 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1848 new PrivateDnsValidationUpdate(netId,
1849 InetAddress.parseNumericAddress(ipAddress),
1850 hostname, validated)));
1851 } catch (IllegalArgumentException e) {
1852 loge("Error parsing ip address in validation event");
1853 }
1854 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001855
1856 @Override
1857 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1858 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1859 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1860 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1861 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1862 // event callback for certain nai. e.g. cellular. Register here to pass to
1863 // NetworkMonitor instead.
Remi NGUYEN VANd68c0252019-02-04 10:25:11 +09001864 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
1865 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
1866 // multiple NetworkMonitor registrants.
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001867 if (nai != null && nai.satisfies(mDefaultRequest)) {
Lorenzo Colittiac955b32019-05-31 15:41:29 +09001868 nai.networkMonitor().notifyDnsResponse(returnCode);
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001869 }
1870 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001871
1872 @Override
1873 public void onNat64PrefixEvent(int netId, boolean added,
1874 String prefixString, int prefixLength) {
1875 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1876 }
dalyk7301aa42018-03-05 12:42:22 -05001877 };
1878
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09001879 private void registerNetdEventCallback() {
1880 final IIpConnectivityMetrics ipConnectivityMetrics = mDeps.getIpConnectivityMetrics();
Chalard Jean4133a122018-06-04 13:33:12 +09001881 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001882 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001883 return;
dalyk7301aa42018-03-05 12:42:22 -05001884 }
1885
1886 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001887 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001888 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1889 mNetdEventCallback);
1890 } catch (Exception e) {
1891 loge("Error registering netd callback: " + e);
1892 }
1893 }
1894
Jeff Sharkey75d31892018-01-18 22:01:59 +09001895 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001896 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001897 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001898 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001899 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001900 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001901 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001902 // caller is NPMS, since we only register with them
1903 if (LOGD_BLOCKED_NETWORKINFO) {
1904 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1905 }
1906 mHandler.sendMessage(mHandler.obtainMessage(
1907 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1908
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001909 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001910 if (restrictBackground) {
1911 log("onRestrictBackgroundChanged(true): disabling tethering");
1912 mTethering.untetherAll();
1913 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001914 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001915 };
1916
junyulai05986c62018-08-07 19:50:45 +08001917 void handleUidRulesChanged(int uid, int newRules) {
1918 // skip update when we've already applied rules
1919 final int oldRules = mUidRules.get(uid, RULE_NONE);
1920 if (oldRules == newRules) return;
1921
1922 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1923
1924 if (newRules == RULE_NONE) {
1925 mUidRules.delete(uid);
1926 } else {
1927 mUidRules.put(uid, newRules);
1928 }
1929 }
1930
1931 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1932 if (mRestrictBackground == restrictBackground) return;
1933
1934 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1935 final boolean curMetered = nai.networkCapabilities.isMetered();
1936 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1937 restrictBackground);
1938 }
1939
1940 mRestrictBackground = restrictBackground;
1941 }
1942
1943 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1944 boolean isBackgroundRestricted) {
1945 synchronized (mVpns) {
1946 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1947 // Because the return value of this function depends on the list of UIDs the
1948 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1949 // list all state depending on the return value of this function has to be recomputed.
1950 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1951 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001952 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001953 return true;
1954 }
1955 }
1956
Chalard Jeanafdecd52019-09-26 18:03:47 +09001957 return NetworkPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
junyulai05986c62018-08-07 19:50:45 +08001958 isNetworkMetered, isBackgroundRestricted);
1959 }
1960
Robin Lee3b3dd942015-05-12 18:14:58 +01001961 /**
1962 * Require that the caller is either in the same user or has appropriate permission to interact
1963 * across users.
1964 *
1965 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1966 */
1967 private void enforceCrossUserPermission(int userId) {
1968 if (userId == UserHandle.getCallingUserId()) {
1969 // Not a cross-user call.
1970 return;
1971 }
1972 mContext.enforceCallingOrSelfPermission(
1973 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1974 "ConnectivityService");
1975 }
1976
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001977 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001978 for (String permission : permissions) {
1979 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001980 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001981 }
1982 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001983 return false;
1984 }
1985
paulhu3d67f532019-03-22 16:35:06 +08001986 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
1987 for (String permission : permissions) {
1988 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
1989 return true;
1990 }
1991 }
1992 return false;
1993 }
1994
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001995 private void enforceAnyPermissionOf(String... permissions) {
1996 if (!checkAnyPermissionOf(permissions)) {
1997 throw new SecurityException("Requires one of the following permissions: "
1998 + String.join(", ", permissions) + ".");
1999 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09002000 }
2001
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002002 private void enforceInternetPermission() {
2003 mContext.enforceCallingOrSelfPermission(
2004 android.Manifest.permission.INTERNET,
2005 "ConnectivityService");
2006 }
2007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002009 mContext.enforceCallingOrSelfPermission(
2010 android.Manifest.permission.ACCESS_NETWORK_STATE,
2011 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 }
2013
2014 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09002015 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017
Charles He36738632017-05-15 17:07:18 +01002018 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002019 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01002020 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002021 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01002022 }
2023
Chalard Jeanb552c462018-02-21 18:43:54 +09002024 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002025 return checkAnyPermissionOf(
2026 android.Manifest.permission.NETWORK_SETTINGS,
2027 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09002028 }
2029
2030 private boolean checkSettingsPermission(int pid, int uid) {
2031 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002032 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2033 || PERMISSION_GRANTED == mContext.checkPermission(
2034 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09002035 }
2036
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002037 private void enforceTetherAccessPermission() {
2038 mContext.enforceCallingOrSelfPermission(
2039 android.Manifest.permission.ACCESS_NETWORK_STATE,
2040 "ConnectivityService");
2041 }
2042
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002043 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002044 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002045 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002046 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002047 }
2048
Pavel Grafova462bcb2019-01-25 08:50:06 +00002049 private void enforceControlAlwaysOnVpnPermission() {
2050 mContext.enforceCallingOrSelfPermission(
2051 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
2052 "ConnectivityService");
2053 }
2054
Lorenzo Colittif5845d12018-10-09 18:55:11 +09002055 private void enforceNetworkStackSettingsOrSetup() {
2056 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002057 android.Manifest.permission.NETWORK_SETTINGS,
2058 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00002059 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002060 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00002061 }
2062
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07002063 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09002064 return checkAnyPermissionOf(
2065 android.Manifest.permission.NETWORK_STACK,
2066 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07002067 }
2068
paulhu3d67f532019-03-22 16:35:06 +08002069 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2070 return checkAnyPermissionOf(pid, uid,
2071 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
2072 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2073 }
2074
Hugo Benichi514da602016-07-19 15:59:27 +09002075 private void enforceConnectivityRestrictedNetworksPermission() {
2076 try {
2077 mContext.enforceCallingOrSelfPermission(
2078 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2079 "ConnectivityService");
2080 return;
2081 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2082 enforceConnectivityInternalPermission();
2083 }
2084
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002085 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09002086 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002087 }
2088
Lorenzo Colitti18660282016-07-04 12:55:44 +09002089 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002090 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08002091 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07002092 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002093 }
2094
2095 private void sendInetConditionBroadcast(NetworkInfo info) {
2096 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2097 }
2098
Wink Saville628b0852011-08-04 15:01:58 -07002099 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09002100 synchronized (mVpns) {
2101 if (mLockdownTracker != null) {
2102 info = new NetworkInfo(info);
2103 mLockdownTracker.augmentNetworkInfo(info);
2104 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002105 }
2106
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002107 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002108 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002109 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 if (info.isFailover()) {
2111 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2112 info.setFailover(false);
2113 }
2114 if (info.getReason() != null) {
2115 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2116 }
2117 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002118 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2119 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002121 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002122 return intent;
2123 }
2124
2125 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2126 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2127 }
2128
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002129 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002130 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2131 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2132 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002133 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002134 final long ident = Binder.clearCallingIdentity();
2135 try {
2136 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2137 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2138 } finally {
2139 Binder.restoreCallingIdentity(ident);
2140 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002141 }
2142
Mike Lockwood0f79b542009-08-14 14:18:49 -04002143 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002144 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002145 if (!mSystemReady
2146 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002147 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002148 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002149 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002150 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002151 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002152 }
2153
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002154 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002155 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002156 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002157 final NetworkInfo ni = intent.getParcelableExtra(
2158 ConnectivityManager.EXTRA_NETWORK_INFO);
2159 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2160 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2161 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002162 } else {
2163 BroadcastOptions opts = BroadcastOptions.makeBasic();
2164 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2165 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002166 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002167 final IBatteryStats bs = BatteryStatsService.getService();
2168 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002169 bs.noteConnectivityChanged(intent.getIntExtra(
2170 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002171 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002172 } catch (RemoteException e) {
2173 }
Chad Brubakerac925012018-03-08 10:37:09 -08002174 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002175 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002176 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002177 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002178 } finally {
2179 Binder.restoreCallingIdentity(ident);
2180 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002181 }
2182 }
2183
Remi NGUYEN VANbb592532019-06-20 18:29:36 +09002184 /**
2185 * Called when the system is ready and ConnectivityService can initialize remaining components.
2186 */
2187 @VisibleForTesting
2188 public void systemReady() {
paulhuf2d73702019-11-19 17:55:31 +08002189 // Let PermissionMonitor#startMonitoring() running in the beginning of the systemReady
2190 // before MultipathPolicyTracker.start(). Since mApps in PermissionMonitor needs to be
2191 // populated first to ensure that listening network request which is sent by
2192 // MultipathPolicyTracker won't be added NET_CAPABILITY_FOREGROUND capability.
2193 mPermissionMonitor.startMonitoring();
Chalard Jean655ad152018-06-08 12:47:42 +09002194 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002195 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002196 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002197
Hugo Benichi20035e02017-04-26 14:53:28 +09002198 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002199 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002200 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002201 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002202 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002203 }
2204 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002205
Robin Lee244ce8e2016-01-05 18:03:46 +00002206 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2207 // for user to unlock device too.
2208 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002209
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002210 // Create network requests for always-on networks.
2211 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002212
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
2215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002217 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002218 *
2219 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002220 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002221 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002222 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2223 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002224
2225 final int timeout;
Chalard Jeanafdecd52019-09-26 18:03:47 +09002226 final int type;
Haoyu Bai04124232012-06-28 15:26:19 -07002227
Robert Greenwalt7b816022014-04-18 15:25:25 -07002228 if (networkAgent.networkCapabilities.hasTransport(
2229 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002230 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2231 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002232 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002233 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002234 } else if (networkAgent.networkCapabilities.hasTransport(
2235 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002236 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2237 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002238 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002239 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002240 } else {
Chalard Jeanafdecd52019-09-26 18:03:47 +09002241 return; // do not track any other networks
Haoyu Bai04124232012-06-28 15:26:19 -07002242 }
2243
Chalard Jeanafdecd52019-09-26 18:03:47 +09002244 if (timeout > 0 && iface != null) {
Haoyu Bai04124232012-06-28 15:26:19 -07002245 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002246 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002247 } catch (Exception e) {
2248 // You shall not crash!
2249 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002250 }
2251 }
2252 }
2253
2254 /**
2255 * Remove data activity tracking when network disconnects.
2256 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002257 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2258 final String iface = networkAgent.linkProperties.getInterfaceName();
2259 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002260
Robert Greenwalt7b816022014-04-18 15:25:25 -07002261 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2262 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002263 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002264 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002265 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002266 } catch (Exception e) {
2267 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002268 }
2269 }
2270 }
2271
2272 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002273 * Update data activity tracking when network state is updated.
2274 */
2275 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2276 NetworkAgentInfo oldNetwork) {
2277 if (newNetwork != null) {
2278 setupDataActivityTracking(newNetwork);
2279 }
2280 if (oldNetwork != null) {
2281 removeDataActivityTracking(oldNetwork);
2282 }
2283 }
2284 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002285 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002286 * and set it on it's iface.
2287 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002288 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2289 final String iface = newLp.getInterfaceName();
2290 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002291 if (oldLp == null && mtu == 0) {
2292 // Silently ignore unset MTU value.
2293 return;
2294 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002295 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2296 if (VDBG) log("identical MTU - not setting");
2297 return;
2298 }
paulhud9736de2019-03-08 16:35:20 +08002299 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002300 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002301 return;
2302 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002303
w1997615afd812014-08-05 15:18:11 -07002304 // Cannot set MTU without interface name
2305 if (TextUtils.isEmpty(iface)) {
2306 loge("Setting MTU size with null iface.");
2307 return;
2308 }
2309
Robert Greenwalt7b816022014-04-18 15:25:25 -07002310 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002311 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002312 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002313 } catch (Exception e) {
2314 Slog.e(TAG, "exception in setMtu()" + e);
2315 }
2316 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002317
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002318 @VisibleForTesting
2319 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002320
lucaslin041a1af2018-11-28 19:27:52 +08002321 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002322 String[] values = null;
2323 if (tcpBufferSizes != null) {
2324 values = tcpBufferSizes.split(",");
2325 }
2326
2327 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002328 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002329 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2330 values = tcpBufferSizes.split(",");
2331 }
2332
2333 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2334
2335 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002336 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002337
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002338 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2339 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2340 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002341 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002342 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002343 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002344 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002345
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002346 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002347 Settings.Global.TCP_DEFAULT_INIT_RWND,
2348 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002349 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2350 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002351 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002352 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002353 }
2354
Robert Greenwalt562cc542014-05-15 18:07:26 -07002355 @Override
2356 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002357 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002358 NETWORK_RESTORE_DELAY_PROP_NAME);
2359 if(restoreDefaultNetworkDelayStr != null &&
2360 restoreDefaultNetworkDelayStr.length() != 0) {
2361 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002362 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002363 } catch (NumberFormatException e) {
2364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002366 // if the system property isn't set, use the value for the apn type
2367 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2368
2369 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2370 (mNetConfigs[networkType] != null)) {
2371 ret = mNetConfigs[networkType].restoreTime;
2372 }
2373 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 }
2375
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002376 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2377 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2378 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002379 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002380 // Start gathering diagnostic information.
2381 netDiags.add(new NetworkDiagnostics(
2382 nai.network,
2383 new LinkProperties(nai.linkProperties), // Must be a copy.
2384 DIAG_TIME_MS));
2385 }
2386
2387 for (NetworkDiagnostics netDiag : netDiags) {
2388 pw.println();
2389 netDiag.waitForMeasurements();
2390 netDiag.dump(pw);
2391 }
2392 }
2393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 @Override
Chalard Jeanafdecd52019-09-26 18:03:47 +09002395 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2396 @Nullable String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002397 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2398 }
2399
2400 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002401 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002402 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002403 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002404
Erik Kline3f8306b2018-05-01 16:51:44 +09002405 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002406 dumpNetworkDiagnostics(pw);
2407 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002408 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002409 mTethering.dump(fd, pw, args);
2410 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002411 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2412 dumpNetworks(pw);
2413 return;
2414 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2415 dumpNetworkRequests(pw);
2416 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002417 }
Erik Kline379747a2015-06-05 17:47:34 +09002418
Lorenzo Colittie3805462015-06-03 11:18:24 +09002419 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002420 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002421 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002422 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002423 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002424 pw.println();
2425
Paul Jensen85cf78e2015-06-25 13:25:07 -04002426 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002427 pw.print("Active default network: ");
2428 if (defaultNai == null) {
2429 pw.println("none");
2430 } else {
2431 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002433 pw.println();
2434
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002435 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002436 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002437 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002438 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002439 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002440
junyulai05986c62018-08-07 19:50:45 +08002441 pw.print("Restrict background: ");
2442 pw.println(mRestrictBackground);
2443 pw.println();
2444
2445 pw.println("Status for known UIDs:");
2446 pw.increaseIndent();
2447 final int size = mUidRules.size();
2448 for (int i = 0; i < size; i++) {
2449 // Don't crash if the array is modified while dumping in bugreports.
2450 try {
2451 final int uid = mUidRules.keyAt(i);
2452 final int uidRules = mUidRules.get(uid, RULE_NONE);
2453 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2454 } catch (ArrayIndexOutOfBoundsException e) {
2455 pw.println(" ArrayIndexOutOfBoundsException");
2456 } catch (ConcurrentModificationException e) {
2457 pw.println(" ConcurrentModificationException");
2458 }
2459 }
2460 pw.println();
2461 pw.decreaseIndent();
2462
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002463 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002464 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002465 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002466 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002467 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002468
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002469 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002470
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002471 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002472 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002473
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002474 pw.println();
2475 mKeepaliveTracker.dump(pw);
2476
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002477 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002478 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002479
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002480 pw.println();
2481 mMultipathPolicyTracker.dump(pw);
2482
Erik Kline3f8306b2018-05-01 16:51:44 +09002483 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002484 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002485 pw.println("mNetworkRequestInfoLogs (most recent first):");
2486 pw.increaseIndent();
2487 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2488 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002489
2490 pw.println();
2491 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2492 pw.increaseIndent();
2493 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2494 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002495
2496 pw.println();
2497 pw.println("NetTransition WakeLock activity (most recent first):");
2498 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002499 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2500 pw.println("total releases: " + mTotalWakelockReleases);
2501 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2502 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2503 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2504 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2505 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2506 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002507 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002508
2509 pw.println();
2510 pw.println("bandwidth update requests (by uid):");
2511 pw.increaseIndent();
2512 synchronized (mBandwidthRequests) {
2513 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2514 pw.println("[" + mBandwidthRequests.keyAt(i)
2515 + "]: " + mBandwidthRequests.valueAt(i));
2516 }
2517 }
2518 pw.decreaseIndent();
2519
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002520 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002521 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002522
2523 pw.println();
2524 pw.println("NetworkStackClient logs:");
2525 pw.increaseIndent();
2526 NetworkStackClient.getInstance().dump(pw);
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00002527 pw.decreaseIndent();
2528
2529 pw.println();
2530 pw.println("Permission Monitor:");
2531 pw.increaseIndent();
2532 mPermissionMonitor.dump(pw);
2533 pw.decreaseIndent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
2535
Hugo Benichi14683812018-09-03 08:32:56 +09002536 private void dumpNetworks(IndentingPrintWriter pw) {
2537 for (NetworkAgentInfo nai : networksSortedById()) {
2538 pw.println(nai.toString());
2539 pw.increaseIndent();
2540 pw.println(String.format(
2541 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2542 nai.numForegroundNetworkRequests(),
2543 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2544 nai.numBackgroundNetworkRequests(),
2545 nai.numNetworkRequests()));
2546 pw.increaseIndent();
2547 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2548 pw.println(nai.requestAt(i).toString());
2549 }
2550 pw.decreaseIndent();
2551 pw.println("Lingered:");
2552 pw.increaseIndent();
2553 nai.dumpLingerTimers(pw);
2554 pw.decreaseIndent();
2555 pw.decreaseIndent();
2556 }
2557 }
2558
2559 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2560 for (NetworkRequestInfo nri : requestsSortedById()) {
2561 pw.println(nri.toString());
2562 }
2563 }
2564
Hugo Benichia2a917c2018-09-03 08:19:02 +09002565 /**
2566 * Return an array of all current NetworkAgentInfos sorted by network id.
2567 */
2568 private NetworkAgentInfo[] networksSortedById() {
2569 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2570 networks = mNetworkAgentInfos.values().toArray(networks);
2571 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2572 return networks;
2573 }
2574
2575 /**
2576 * Return an array of all current NetworkRequest sorted by request id.
2577 */
2578 private NetworkRequestInfo[] requestsSortedById() {
2579 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2580 requests = mNetworkRequests.values().toArray(requests);
2581 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2582 return requests;
2583 }
2584
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002585 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002586 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002587 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002588 if (officialNai != null && officialNai.equals(nai)) return true;
2589 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002590 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002591 " - " + nai);
2592 }
2593 return false;
2594 }
2595
Robert Greenwalt42acef32009-08-12 16:08:25 -07002596 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002597 private class NetworkStateTrackerHandler extends Handler {
2598 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002599 super(looper);
2600 }
2601
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002602 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002604 default:
2605 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002606 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002607 handleAsyncChannelHalfConnect(msg);
2608 break;
2609 }
2610 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2611 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2612 if (nai != null) nai.asyncChannel.disconnect();
2613 break;
2614 }
2615 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2616 handleAsyncChannelDisconnected(msg);
2617 break;
2618 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002619 }
2620 return true;
2621 }
2622
2623 private void maybeHandleNetworkAgentMessage(Message msg) {
2624 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2625 if (nai == null) {
2626 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002627 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002628 }
2629 return;
2630 }
2631
2632 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002633 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002634 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002635 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002636 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002637 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002638 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002639 break;
2640 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002641 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002642 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002643 break;
2644 }
2645 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002646 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002647 updateNetworkInfo(nai, info);
2648 break;
2649 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002650 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
lucaslinc2bac512019-11-07 16:47:56 +08002651 final NetworkScore ns = (NetworkScore) msg.obj;
2652 updateNetworkScore(nai, ns);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002653 break;
2654 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002655 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colitti091de3f2019-06-04 14:37:26 +09002656 if (nai.everConnected) {
2657 loge("ERROR: cannot call explicitlySelected on already-connected network");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002658 }
Lorenzo Colittib5ad6132019-06-04 22:15:33 +09002659 nai.networkMisc.explicitlySelected = toBool(msg.arg1);
2660 nai.networkMisc.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucasline252a742019-03-12 13:08:03 +08002661 // Mark the network as temporarily accepting partial connectivity so that it
2662 // will be validated (and possibly become default) even if it only provides
2663 // partial internet access. Note that if user connects to partial connectivity
2664 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2665 // out of wifi coverage) and if the same wifi is available again, the device
2666 // will auto connect to this wifi even though the wifi has "no internet".
2667 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittib5ad6132019-06-04 22:15:33 +09002668 nai.networkMisc.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte73cc462014-09-07 16:50:01 -07002669 break;
2670 }
junyulai06835112019-01-03 18:50:15 +08002671 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2672 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002673 break;
2674 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002675 }
2676 }
2677
2678 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2679 switch (msg.what) {
2680 default:
2681 return false;
lucaslin783f2212019-10-22 18:27:33 +08002682 case EVENT_PROBE_STATUS_CHANGED: {
2683 final Integer netId = (Integer) msg.obj;
2684 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
2685 if (nai == null) {
2686 break;
2687 }
2688 final boolean probePrivateDnsCompleted =
2689 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
2690 final boolean privateDnsBroken =
2691 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
2692 if (probePrivateDnsCompleted) {
2693 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
2694 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
2695 final int oldScore = nai.getCurrentScore();
2696 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2697 }
2698 // Only show the notification when the private DNS is broken and the
2699 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
2700 if (privateDnsBroken && !nai.networkMisc.hasShownBroken) {
2701 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
2702 }
2703 nai.networkMisc.hasShownBroken = privateDnsBroken;
2704 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
2705 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
2706 // private DNS is broken, it means this network is being reevaluated.
2707 // Either probing private DNS is not necessary any more or it hasn't been
2708 // done yet. In either case, the networkCapabilities should be updated to
2709 // reflect the new status.
2710 nai.networkCapabilities.setPrivateDnsBroken(false);
2711 final int oldScore = nai.getCurrentScore();
2712 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2713 nai.networkMisc.hasShownBroken = false;
2714 }
2715 break;
2716 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002717 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002718 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002719 if (nai == null) break;
2720
Chiachang Wang8ea15c962019-05-23 16:29:30 +08002721 final boolean wasPartial = nai.partialConnectivity;
2722 nai.partialConnectivity = ((msg.arg1 & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
lucaslin43338992019-03-20 18:21:59 +08002723 final boolean partialConnectivityChanged =
Chiachang Wang8ea15c962019-05-23 16:29:30 +08002724 (wasPartial != nai.partialConnectivity);
lucasline252a742019-03-12 13:08:03 +08002725
Chiachang Wang8ea15c962019-05-23 16:29:30 +08002726 final boolean valid = ((msg.arg1 & NETWORK_VALIDATION_RESULT_VALID) != 0);
Erik Klinea24d4592018-01-11 21:07:29 +09002727 final boolean wasValidated = nai.lastValidated;
2728 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN0839a192019-06-17 11:28:27 +09002729 // Only show a connected notification if the network is pending validation
2730 // after the captive portal app was open, and it has now validated.
2731 if (nai.captivePortalValidationPending && valid) {
2732 // User is now logged in, network validated.
2733 nai.captivePortalValidationPending = false;
lucaslind2e045e02019-01-24 15:55:30 +08002734 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2735 }
Erik Klinea24d4592018-01-11 21:07:29 +09002736
Erik Klinea24d4592018-01-11 21:07:29 +09002737 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2738
Erik Klinea24d4592018-01-11 21:07:29 +09002739 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002740 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2741 ? " with redirect to " + redirectUrl
2742 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002743 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2744 }
Erik Klinea24d4592018-01-11 21:07:29 +09002745 if (valid != nai.lastValidated) {
2746 if (wasDefault) {
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09002747 mDeps.getMetricsLogger()
2748 .defaultNetworkMetrics().logDefaultNetworkValidity(
2749 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002750 }
Erik Klinea24d4592018-01-11 21:07:29 +09002751 final int oldScore = nai.getCurrentScore();
2752 nai.lastValidated = valid;
2753 nai.everValidated |= valid;
2754 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2755 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2756 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002757 if (valid) {
2758 handleFreshlyValidatedNetwork(nai);
lucaslin783f2212019-10-22 18:27:33 +08002759 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
2760 // LOST_INTERNET notifications if network becomes valid.
lucaslind2e045e02019-01-24 15:55:30 +08002761 mNotifier.clearNotification(nai.network.netId,
2762 NotificationType.NO_INTERNET);
2763 mNotifier.clearNotification(nai.network.netId,
2764 NotificationType.LOST_INTERNET);
Chiachang Wang8ea15c962019-05-23 16:29:30 +08002765 mNotifier.clearNotification(nai.network.netId,
2766 NotificationType.PARTIAL_CONNECTIVITY);
lucaslin783f2212019-10-22 18:27:33 +08002767 mNotifier.clearNotification(nai.network.netId,
2768 NotificationType.PRIVATE_DNS_BROKEN);
2769 // If network becomes valid, the hasShownBroken should be reset for
2770 // that network so that the notification will be fired when the private
2771 // DNS is broken again.
2772 nai.networkMisc.hasShownBroken = false;
lucaslind2e045e02019-01-24 15:55:30 +08002773 }
lucaslin43338992019-03-20 18:21:59 +08002774 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002775 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002776 }
2777 updateInetCondition(nai);
2778 // Let the NetworkAgent know the state of its network
2779 Bundle redirectUrlBundle = new Bundle();
2780 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
Chiachang Wang8ea15c962019-05-23 16:29:30 +08002781 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Erik Klinea24d4592018-01-11 21:07:29 +09002782 nai.asyncChannel.sendMessage(
2783 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2784 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2785 0, redirectUrlBundle);
Chiachang Wangaedf04792019-06-03 15:16:27 +08002786
2787 // If NetworkMonitor detects partial connectivity before
2788 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
2789 // immediately. Re-notify partial connectivity silently if no internet
2790 // notification already there.
2791 if (!wasPartial && nai.partialConnectivity) {
2792 // Remove delayed message if there is a pending message.
2793 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
2794 handlePromptUnvalidated(nai.network);
2795 }
2796
Erik Klinea24d4592018-01-11 21:07:29 +09002797 if (wasValidated && !nai.lastValidated) {
2798 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002799 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002800 break;
2801 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002802 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002803 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002804 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002805 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002806 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002807 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002808 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002809 nai.lastCaptivePortalDetected = visible;
2810 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002811 if (nai.lastCaptivePortalDetected &&
2812 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2813 if (DBG) log("Avoiding captive portal network: " + nai.name());
2814 nai.asyncChannel.sendMessage(
2815 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2816 teardownUnneededNetwork(nai);
2817 break;
2818 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002819 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002820 }
2821 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002822 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002823 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002824 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2825 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002826 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002827 if (nai == null) {
2828 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2829 break;
2830 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002831 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002832 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002833 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002834 }
Paul Jensen869868be2014-05-15 10:33:05 -04002835 }
Paul Jensen869868be2014-05-15 10:33:05 -04002836 break;
2837 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002838 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002839 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002840 if (nai == null) break;
2841
Erik Kline736353a2018-03-21 07:18:33 -07002842 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002843 break;
2844 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002845 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002846 return true;
2847 }
2848
Calvin Onbe96da12016-10-11 15:10:46 -07002849 private int getCaptivePortalMode() {
2850 return Settings.Global.getInt(mContext.getContentResolver(),
2851 Settings.Global.CAPTIVE_PORTAL_MODE,
2852 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2853 }
2854
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002855 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2856 switch (msg.what) {
2857 default:
2858 return false;
2859 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2860 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2861 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2862 handleLingerComplete(nai);
2863 }
2864 break;
2865 }
2866 }
2867 return true;
2868 }
2869
Etan Cohenddb720a2019-01-08 12:09:18 -08002870 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2871 switch (msg.what) {
2872 default:
2873 return false;
Etan Cohenae574a82019-01-08 12:09:18 -08002874 case NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
Etan Cohenddb720a2019-01-08 12:09:18 -08002875 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2876 /* callOnUnavailable */ true);
2877 break;
2878 }
2879 }
2880 return true;
2881 }
2882
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002883 @Override
2884 public void handleMessage(Message msg) {
Etan Cohenddb720a2019-01-08 12:09:18 -08002885 if (!maybeHandleAsyncChannelMessage(msg)
2886 && !maybeHandleNetworkMonitorMessage(msg)
2887 && !maybeHandleNetworkAgentInfoMessage(msg)
2888 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002889 maybeHandleNetworkAgentMessage(msg);
2890 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002891 }
2892 }
2893
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002894 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jeand5603302019-05-30 14:58:29 +09002895 private final int mNetId;
2896 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002897
2898 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Chalard Jeand5603302019-05-30 14:58:29 +09002899 mNetId = nai.network.netId;
Chalard Jeanafdecd52019-09-26 18:03:47 +09002900 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002901 }
2902
2903 @Override
2904 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2905 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jeand5603302019-05-30 14:58:29 +09002906 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002907 }
2908
2909 @Override
2910 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2911 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
Chalard Jeand5603302019-05-30 14:58:29 +09002912 testResult, mNetId, redirectUrl));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002913 }
2914
2915 @Override
2916 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2917 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2918 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jeand5603302019-05-30 14:58:29 +09002919 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002920 }
2921
2922 @Override
lucaslin783f2212019-10-22 18:27:33 +08002923 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
2924 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2925 EVENT_PROBE_STATUS_CHANGED,
2926 probesCompleted, probesSucceeded, new Integer(mNetId)));
2927 }
2928
2929 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002930 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002931 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002932 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002933
2934 final PendingIntent pendingIntent;
2935 // Only the system server can register notifications with package "android"
2936 final long token = Binder.clearCallingIdentity();
2937 try {
2938 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2939 } finally {
2940 Binder.restoreCallingIdentity(token);
2941 }
2942 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2943 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jeand5603302019-05-30 14:58:29 +09002944 mNetId, pendingIntent));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002945 }
2946
2947 @Override
2948 public void hideProvisioningNotification() {
2949 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jeand5603302019-05-30 14:58:29 +09002950 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002951 }
Remi NGUYEN VAN1232fe32019-04-05 15:15:48 +09002952
2953 @Override
2954 public int getInterfaceVersion() {
2955 return this.VERSION;
2956 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002957 }
2958
Lorenzo Colitti80986d92019-03-22 00:28:28 +09002959 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
2960 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002961 }
2962
Erik Klinec6d00222018-06-26 18:53:43 +09002963 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2964 if (nai == null) return;
2965 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2966 // in order to restart a validation pass from within netd.
2967 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2968 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2969 updateDnses(nai.linkProperties, null, nai.network.netId);
2970 }
2971 }
2972
Erik Klinea24d4592018-01-11 21:07:29 +09002973 private void handlePrivateDnsSettingsChanged() {
2974 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2975
2976 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002977 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti80986d92019-03-22 00:28:28 +09002978 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk7301aa42018-03-05 12:42:22 -05002979 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2980 }
Erik Klinea24d4592018-01-11 21:07:29 +09002981 }
2982 }
2983
Erik Kline736353a2018-03-21 07:18:33 -07002984 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2985 // Private DNS only ever applies to networks that might provide
2986 // Internet access and therefore also require validation.
Lorenzo Colitti80986d92019-03-22 00:28:28 +09002987 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002988
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002989 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002990 // schedule DNS resolutions. If a DNS resolution is required the
2991 // result will be sent back to us.
Lorenzo Colittiac955b32019-05-31 15:41:29 +09002992 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline736353a2018-03-21 07:18:33 -07002993
2994 // With Private DNS bypass support, we can proceed to update the
2995 // Private DNS config immediately, even if we're in strict mode
2996 // and have not yet resolved the provider name into a set of IPs.
2997 updatePrivateDns(nai, cfg);
2998 }
2999
3000 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3001 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09003002 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09003003 }
3004
dalyk7301aa42018-03-05 12:42:22 -05003005 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3006 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3007 if (nai == null) {
3008 return;
3009 }
3010 mDnsManager.updatePrivateDnsValidation(update);
3011 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3012 }
3013
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09003014 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
3015 int prefixLength) {
3016 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3017 if (nai == null) return;
3018
3019 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
3020 (added ? "added" : "removed"), netId, prefixString, prefixLength));
3021
3022 IpPrefix prefix = null;
3023 if (added) {
3024 try {
3025 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
3026 prefixLength);
3027 } catch (IllegalArgumentException e) {
3028 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
3029 return;
3030 }
3031 }
3032
3033 nai.clatd.setNat64Prefix(prefix);
3034 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3035 }
3036
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003037 private void updateLingerState(NetworkAgentInfo nai, long now) {
3038 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
3039 // 2. If the network was lingering and there are now requests, unlinger it.
3040 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
3041 // one lingered request, start lingering.
3042 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003043 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003044 if (DBG) log("Unlingering " + nai.name());
3045 nai.unlinger();
3046 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003047 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003048 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003049 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003050 nai.linger();
3051 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
3052 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
3053 }
Paul Jensen0cc17322014-11-25 15:26:53 -05003054 }
3055
Robert Greenwalt7b816022014-04-18 15:25:25 -07003056 private void handleAsyncChannelHalfConnect(Message msg) {
Chalard Jean11293a92019-11-05 14:40:23 +09003057 ensureRunningOnConnectivityServiceThread();
3058 final AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07003059 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003060 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3061 if (VDBG) log("NetworkFactory connected");
Etan Cohenddb720a2019-01-08 12:09:18 -08003062 // Finish setting up the full connection
3063 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
3064 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003065 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003066 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003067 if (nri.request.isListen()) continue;
Chalard Jeancf904232019-11-05 15:10:49 +09003068 ensureRunningOnConnectivityServiceThread();
3069 NetworkAgentInfo nai = nri.mSatisfier;
Chalard Jean05ab6812018-05-02 21:14:54 +09003070 final int score;
3071 final int serial;
3072 if (nai != null) {
3073 score = nai.getCurrentScore();
3074 serial = nai.factorySerialNumber;
3075 } else {
3076 score = 0;
3077 serial = NetworkFactory.SerialNumber.NONE;
3078 }
3079 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
3080 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003081 }
3082 } else {
3083 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003084 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003085 }
3086 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
3087 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3088 if (VDBG) log("NetworkAgent connected");
3089 // A network agent has requested a connection. Establish the connection.
3090 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
3091 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
3092 } else {
3093 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07003094 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003095 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09003096 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003097 synchronized (mNetworkForNetId) {
3098 mNetworkForNetId.remove(nai.network.netId);
3099 }
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09003100 mNetIdManager.releaseNetId(nai.network.netId);
Lorenzo Colittia793a672014-07-31 23:20:17 +09003101 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09003102 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003103 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003104 }
3105 }
3106 }
Paul Jensen0cc17322014-11-25 15:26:53 -05003107
Chalard Jean392971c2018-05-11 20:19:20 +09003108 // This is a no-op if it's called with a message designating a network that has
3109 // already been destroyed, because its reference will not be found in the relevant
3110 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003111 private void handleAsyncChannelDisconnected(Message msg) {
3112 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3113 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09003114 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04003115 } else {
3116 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
3117 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003118 }
3119 }
3120
Chalard Jean392971c2018-05-11 20:19:20 +09003121 // Destroys a network, remove references to it from the internal state managed by
3122 // ConnectivityService, free its interfaces and clean up.
3123 // Must be called on the Handler thread.
3124 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean11293a92019-11-05 14:40:23 +09003125 ensureRunningOnConnectivityServiceThread();
Chalard Jean392971c2018-05-11 20:19:20 +09003126 if (DBG) {
3127 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
3128 }
lucaslinf80b83b2019-02-12 15:30:13 +08003129 // Clear all notifications of this network.
3130 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003131 // A network agent has disconnected.
3132 // TODO - if we move the logic to the network agent (have them disconnect
3133 // because they lost all their requests or because their score isn't good)
3134 // then they would disconnect organically, report their new state and then
3135 // disconnect the channel.
3136 if (nai.networkInfo.isConnected()) {
3137 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3138 null, null);
3139 }
3140 final boolean wasDefault = isDefaultNetwork(nai);
3141 if (wasDefault) {
3142 mDefaultInetConditionPublished = 0;
3143 // Log default network disconnection before required book-keeping.
3144 // Let rematchAllNetworksAndRequests() below record a new default network event
3145 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
3146 // whose timestamps tell how long it takes to recover a default network.
3147 long now = SystemClock.elapsedRealtime();
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09003148 mDeps.getMetricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003149 }
3150 notifyIfacesChangedForNetworkStats();
3151 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3152 // by other networks that are already connected. Perhaps that can be done by
3153 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3154 // of rematchAllNetworksAndRequests
3155 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai06835112019-01-03 18:50:15 +08003156 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09003157 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3158 // Disable wakeup packet monitoring for each interface.
3159 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3160 }
Lorenzo Colittiac955b32019-05-31 15:41:29 +09003161 nai.networkMonitor().notifyNetworkDisconnected();
Chalard Jean392971c2018-05-11 20:19:20 +09003162 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09003163 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09003164 synchronized (mNetworkForNetId) {
3165 // Remove the NetworkAgent, but don't mark the netId as
3166 // available until we've told netd to delete it below.
3167 mNetworkForNetId.remove(nai.network.netId);
3168 }
3169 // Remove all previously satisfied requests.
3170 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3171 NetworkRequest request = nai.requestAt(i);
Chalard Jean68602592019-11-05 15:07:09 +09003172 final NetworkRequestInfo nri = mNetworkRequests.get(request);
Chalard Jeancf904232019-11-05 15:10:49 +09003173 ensureRunningOnConnectivityServiceThread();
3174 final NetworkAgentInfo currentNetwork = nri.mSatisfier;
Chalard Jean392971c2018-05-11 20:19:20 +09003175 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Chalard Jeancf904232019-11-05 15:10:49 +09003176 nri.mSatisfier = null;
Chalard Jean05ab6812018-05-02 21:14:54 +09003177 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003178 }
3179 }
3180 nai.clearLingerState();
3181 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chalard Jeancf904232019-11-05 15:10:49 +09003182 mDefaultNetworkNai = null;
Chiachang Wanga6093042018-09-28 22:42:48 +08003183 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003184 notifyLockdownVpn(nai);
3185 ensureNetworkTransitionWakelock(nai.name());
3186 }
3187 mLegacyTypeTracker.remove(nai, wasDefault);
3188 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3189 updateAllVpnsCapabilities();
3190 }
Chalard Jean1a4548c2019-11-07 18:54:49 +09003191 rematchAllNetworksAndRequests();
Chalard Jean392971c2018-05-11 20:19:20 +09003192 mLingerMonitor.noteDisconnect(nai);
3193 if (nai.created) {
3194 // Tell netd to clean up the configuration for this network
3195 // (routing rules, DNS, etc).
3196 // This may be slow as it requires a lot of netd shelling out to ip and
3197 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3198 // after we've rematched networks with requests which should make a potential
3199 // fallback network the default or requested a new network from the
3200 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3201 // long time.
Luke Huanga24d5d82019-04-09 18:41:49 +08003202 destroyNativeNetwork(nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003203 mDnsManager.removeNetwork(nai.network);
3204 }
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09003205 mNetIdManager.releaseNetId(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003206 }
3207
Luke Huanga24d5d82019-04-09 18:41:49 +08003208 private boolean createNativeNetwork(@NonNull NetworkAgentInfo networkAgent) {
3209 try {
3210 // This should never fail. Specifying an already in use NetID will cause failure.
3211 if (networkAgent.isVPN()) {
3212 mNetd.networkCreateVpn(networkAgent.network.netId,
3213 (networkAgent.networkMisc == null
3214 || !networkAgent.networkMisc.allowBypass));
3215 } else {
3216 mNetd.networkCreatePhysical(networkAgent.network.netId,
3217 getNetworkPermission(networkAgent.networkCapabilities));
3218 }
3219 mDnsResolver.createNetworkCache(networkAgent.network.netId);
3220 return true;
3221 } catch (RemoteException | ServiceSpecificException e) {
3222 loge("Error creating network " + networkAgent.network.netId + ": "
3223 + e.getMessage());
3224 return false;
3225 }
3226 }
3227
3228 private void destroyNativeNetwork(@NonNull NetworkAgentInfo networkAgent) {
3229 try {
3230 mNetd.networkDestroy(networkAgent.network.netId);
3231 mDnsResolver.destroyNetworkCache(networkAgent.network.netId);
3232 } catch (RemoteException | ServiceSpecificException e) {
3233 loge("Exception destroying network: " + e);
3234 }
3235 }
3236
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003237 // If this method proves to be too slow then we can maintain a separate
3238 // pendingIntent => NetworkRequestInfo map.
3239 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3240 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3241 Intent intent = pendingIntent.getIntent();
3242 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3243 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3244 if (existingPendingIntent != null &&
3245 existingPendingIntent.getIntent().filterEquals(intent)) {
3246 return entry.getValue();
3247 }
3248 }
3249 return null;
3250 }
3251
3252 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3253 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3254
3255 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3256 if (existingRequest != null) { // remove the existing request.
3257 if (DBG) log("Replacing " + existingRequest.request + " with "
3258 + nri.request + " because their intents matched.");
Etan Cohenddb720a2019-01-08 12:09:18 -08003259 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3260 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003261 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003262 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003263 }
3264
Erik Klineda4bfa82015-04-30 12:58:40 +09003265 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Chalard Jean11293a92019-11-05 14:40:23 +09003266 ensureRunningOnConnectivityServiceThread();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003267 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003268 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003269 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003270 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003271 if (nri.request.networkCapabilities.hasSignalStrength() &&
3272 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3273 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003274 }
3275 }
3276 }
Chalard Jean1a4548c2019-11-07 18:54:49 +09003277 rematchAllNetworksAndRequests();
Chalard Jeancf904232019-11-05 15:10:49 +09003278 if (nri.request.isRequest() && nri.mSatisfier == null) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003279 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003280 }
3281 }
3282
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003283 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3284 int callingUid) {
3285 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3286 if (nri != null) {
Etan Cohenddb720a2019-01-08 12:09:18 -08003287 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003288 }
3289 }
3290
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003291 // Determines whether the network is the best (or could become the best, if it validated), for
3292 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3293 // on the value of reason:
3294 //
3295 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3296 // then it should be torn down.
3297 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3298 // then it should be lingered.
3299 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean11293a92019-11-05 14:40:23 +09003300 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003301 final int numRequests;
3302 switch (reason) {
3303 case TEARDOWN:
3304 numRequests = nai.numRequestNetworkRequests();
3305 break;
3306 case LINGER:
3307 numRequests = nai.numForegroundNetworkRequests();
3308 break;
3309 default:
3310 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3311 return true;
3312 }
3313
3314 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003315 return false;
3316 }
Paul Jensene0988542015-06-25 15:30:08 -04003317 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003318 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3319 // Background requests don't affect lingering.
3320 continue;
3321 }
3322
Paul Jensene0988542015-06-25 15:30:08 -04003323 // If this Network is already the highest scoring Network for a request, or if
3324 // there is hope for it to become one if it validated, then it is needed.
Chalard Jeancf904232019-11-05 15:10:49 +09003325 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003326 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003327 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003328 // Note that this catches two important cases:
3329 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3330 // is currently satisfying the request. This is desirable when
3331 // cellular ends up validating but WiFi does not.
3332 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003333 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003334 // WiFi ends up validating and out scoring cellular.
Chalard Jeancf904232019-11-05 15:10:49 +09003335 nri.mSatisfier.getCurrentScore()
Chalard Jean68602592019-11-05 15:07:09 +09003336 < nai.getCurrentScoreAsValidated())) {
Paul Jensene0988542015-06-25 15:30:08 -04003337 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003338 }
3339 }
Paul Jensene0988542015-06-25 15:30:08 -04003340 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003341 }
3342
Erik Klineacdd6392016-07-07 16:50:58 +09003343 private NetworkRequestInfo getNriForAppRequest(
3344 NetworkRequest request, int callingUid, String requestedOperation) {
3345 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3346
Robert Greenwalt9258c642014-03-26 16:47:06 -07003347 if (nri != null) {
Roshan Piuse896c6d2019-10-04 06:33:37 -07003348 if (Process.SYSTEM_UID != callingUid && Process.NETWORK_STACK_UID != callingUid
3349 && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003350 log(String.format("UID %d attempted to %s for unowned request %s",
3351 callingUid, requestedOperation, nri));
3352 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003353 }
Erik Klineacdd6392016-07-07 16:50:58 +09003354 }
3355
3356 return nri;
3357 }
3358
Erik Kline57faba92015-11-25 12:49:38 +09003359 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Chalard Jean11293a92019-11-05 14:40:23 +09003360 ensureRunningOnConnectivityServiceThread();
Hugo Benichidba33db2017-03-23 22:40:44 +09003361 if (mNetworkRequests.get(nri.request) == null) {
3362 return;
Erik Kline57faba92015-11-25 12:49:38 +09003363 }
Chalard Jeancf904232019-11-05 15:10:49 +09003364 ensureRunningOnConnectivityServiceThread();
3365 if (nri.mSatisfier != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003366 return;
3367 }
3368 if (VDBG || (DBG && nri.request.isRequest())) {
3369 log("releasing " + nri.request + " (timeout)");
3370 }
3371 handleRemoveNetworkRequest(nri);
3372 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003373 }
3374
Etan Cohenddb720a2019-01-08 12:09:18 -08003375 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3376 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003377 final NetworkRequestInfo nri =
3378 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3379 if (nri == null) {
3380 return;
Erik Kline57faba92015-11-25 12:49:38 +09003381 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003382 if (VDBG || (DBG && nri.request.isRequest())) {
3383 log("releasing " + nri.request + " (release request)");
3384 }
3385 handleRemoveNetworkRequest(nri);
Etan Cohenddb720a2019-01-08 12:09:18 -08003386 if (callOnUnavailable) {
3387 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3388 }
Erik Kline57faba92015-11-25 12:49:38 +09003389 }
Erik Klineacdd6392016-07-07 16:50:58 +09003390
Hugo Benichidba33db2017-03-23 22:40:44 +09003391 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Chalard Jean11293a92019-11-05 14:40:23 +09003392 ensureRunningOnConnectivityServiceThread();
3393
Erik Klineacdd6392016-07-07 16:50:58 +09003394 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003395 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003396
Erik Klineacdd6392016-07-07 16:50:58 +09003397 synchronized (mUidToNetworkRequestCount) {
3398 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3399 if (requests < 1) {
3400 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3401 nri.mUid);
3402 } else if (requests == 1) {
3403 mUidToNetworkRequestCount.removeAt(
3404 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3405 } else {
3406 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3407 }
3408 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003409
Erik Klineacdd6392016-07-07 16:50:58 +09003410 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3411 if (nri.request.isRequest()) {
3412 boolean wasKept = false;
Chalard Jeancf904232019-11-05 15:10:49 +09003413 ensureRunningOnConnectivityServiceThread();
3414 final NetworkAgentInfo nai = nri.mSatisfier;
Erik Klineacdd6392016-07-07 16:50:58 +09003415 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003416 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003417 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003418 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003419 log(" Removing from current network " + nai.name() +
3420 ", leaving " + nai.numNetworkRequests() + " requests.");
3421 }
3422 // If there are still lingered requests on this network, don't tear it down,
3423 // but resume lingering instead.
3424 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003425 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003426 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3427 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003428 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003429 wasKept = true;
3430 }
Chalard Jeancf904232019-11-05 15:10:49 +09003431 nri.mSatisfier = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003432 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3433 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003434 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003435 }
Erik Klineacdd6392016-07-07 16:50:58 +09003436 }
3437
Erik Klineacdd6392016-07-07 16:50:58 +09003438 // Maintain the illusion. When this request arrived, we might have pretended
3439 // that a network connected to serve it, even though the network was already
3440 // connected. Now that this request has gone away, we might have to pretend
3441 // that the network disconnected. LegacyTypeTracker will generate that
3442 // phantom disconnect for this type.
3443 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3444 boolean doRemove = true;
3445 if (wasKept) {
3446 // check if any of the remaining requests for this network are for the
3447 // same legacy type - if so, don't remove the nai
3448 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3449 NetworkRequest otherRequest = nai.requestAt(i);
3450 if (otherRequest.legacyType == nri.request.legacyType &&
3451 otherRequest.isRequest()) {
3452 if (DBG) log(" still have other legacy request - leaving");
3453 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003454 }
3455 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003456 }
3457
Erik Klineacdd6392016-07-07 16:50:58 +09003458 if (doRemove) {
3459 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003460 }
3461 }
Erik Klineacdd6392016-07-07 16:50:58 +09003462
3463 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3464 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3465 nri.request);
3466 }
3467 } else {
3468 // listens don't have a singular affectedNetwork. Check all networks to see
3469 // if this listen request applies and remove it.
3470 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3471 nai.removeRequest(nri.request.requestId);
3472 if (nri.request.networkCapabilities.hasSignalStrength() &&
3473 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3474 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3475 }
3476 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003477 }
3478 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003479
Lorenzo Colitti18660282016-07-04 12:55:44 +09003480 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003481 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003482 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003483 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003484 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003485 }
3486
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003487 @Override
lucasline252a742019-03-12 13:08:03 +08003488 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3489 enforceNetworkStackSettingsOrSetup();
3490 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3491 encodeBool(accept), encodeBool(always), network));
3492 }
3493
3494 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003495 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003496 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003497 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3498 }
3499
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003500 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3501 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3502 " accept=" + accept + " always=" + always);
3503
3504 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3505 if (nai == null) {
3506 // Nothing to do.
3507 return;
3508 }
3509
3510 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003511 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003512 return;
3513 }
3514
3515 if (!nai.networkMisc.explicitlySelected) {
3516 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3517 }
3518
3519 if (accept != nai.networkMisc.acceptUnvalidated) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003520 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003521 // If network becomes partial connectivity and user already accepted to use this
3522 // network, we should respect the user's option and don't need to popup the
3523 // PARTIAL_CONNECTIVITY notification to user again.
3524 nai.networkMisc.acceptPartialConnectivity = accept;
Chalard Jean1a4548c2019-11-07 18:54:49 +09003525 rematchAllNetworksAndRequests();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003526 sendUpdatedScoreToFactories(nai);
3527 }
3528
3529 if (always) {
3530 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003531 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003532 }
3533
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003534 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003535 // Tell the NetworkAgent to not automatically reconnect to the network.
3536 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003537 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003538 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003539 }
3540
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003541 }
3542
lucasline252a742019-03-12 13:08:03 +08003543 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3544 boolean always) {
3545 if (DBG) {
3546 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3547 + " always=" + always);
3548 }
3549
3550 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3551 if (nai == null) {
3552 // Nothing to do.
3553 return;
3554 }
3555
3556 if (nai.lastValidated) {
3557 // The network validated while the dialog box was up. Take no action.
3558 return;
3559 }
3560
3561 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3562 nai.networkMisc.acceptPartialConnectivity = accept;
3563 }
3564
3565 // TODO: Use the current design or save the user choice into IpMemoryStore.
3566 if (always) {
3567 nai.asyncChannel.sendMessage(
3568 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3569 }
3570
3571 if (!accept) {
3572 // Tell the NetworkAgent to not automatically reconnect to the network.
3573 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3574 // Tear down the network.
3575 teardownUnneededNetwork(nai);
3576 } else {
lucaslin43338992019-03-20 18:21:59 +08003577 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3578 // result in a partial connectivity result which will be processed by
3579 // maybeHandleNetworkMonitorMessage.
Chiachang Wang8ea15c962019-05-23 16:29:30 +08003580 //
3581 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
3582 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colittiac955b32019-05-31 15:41:29 +09003583 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003584 }
3585 }
3586
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003587 private void handleSetAvoidUnvalidated(Network network) {
3588 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3589 if (nai == null || nai.lastValidated) {
3590 // Nothing to do. The network either disconnected or revalidated.
3591 return;
3592 }
3593 if (!nai.avoidUnvalidated) {
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003594 nai.avoidUnvalidated = true;
Chalard Jean1a4548c2019-11-07 18:54:49 +09003595 rematchAllNetworksAndRequests();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003596 sendUpdatedScoreToFactories(nai);
3597 }
3598 }
3599
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003600 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003601 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003602 mHandler.sendMessageDelayed(
3603 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3604 PROMPT_UNVALIDATED_DELAY_MS);
3605 }
3606
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003607 @Override
3608 public void startCaptivePortalApp(Network network) {
3609 enforceConnectivityInternalPermission();
3610 mHandler.post(() -> {
3611 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3612 if (nai == null) return;
3613 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colittiac955b32019-05-31 15:41:29 +09003614 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003615 });
3616 }
3617
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003618 /**
3619 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3620 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003621 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003622 * @param appExtras Bundle to use as intent extras for the captive portal application.
3623 * Must be treated as opaque to avoid preventing the captive portal app to
3624 * update its arguments.
3625 */
3626 @Override
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003627 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhu98525602019-05-14 14:17:44 +08003628 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3629 "ConnectivityService");
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003630
3631 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3632 appIntent.putExtras(appExtras);
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003633 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3634 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003635 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3636
Remi NGUYEN VAN0839a192019-06-17 11:28:27 +09003637 // This runs on a random binder thread, but getNetworkAgentInfoForNetwork is thread-safe,
3638 // and captivePortalValidationPending is volatile.
3639 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3640 if (nai != null) {
3641 nai.captivePortalValidationPending = true;
3642 }
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003643 Binder.withCleanCallingIdentity(() ->
3644 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3645 }
3646
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003647 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3648 private final Network mNetwork;
3649
3650 private CaptivePortalImpl(Network network) {
3651 mNetwork = network;
3652 }
3653
3654 @Override
Lorenzo Colittiac955b32019-05-31 15:41:29 +09003655 public void appResponse(final int response) {
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003656 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3657 enforceSettingsPermission();
3658 }
3659
3660 // getNetworkAgentInfoForNetwork is thread-safe
3661 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3662 if (nai == null) return;
3663
3664 // nai.networkMonitor() is thread-safe
Lorenzo Colittiac955b32019-05-31 15:41:29 +09003665 final NetworkMonitorManager nm = nai.networkMonitor();
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003666 if (nm == null) return;
Lorenzo Colittiac955b32019-05-31 15:41:29 +09003667 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003668 }
3669
3670 @Override
3671 public void logEvent(int eventId, String packageName) {
3672 enforceSettingsPermission();
3673
3674 new MetricsLogger().action(eventId, packageName);
3675 }
3676 }
3677
Hugo Benichic8e9e122016-09-14 23:23:08 +00003678 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003679 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003680 }
3681
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09003682 /**
3683 * Return whether the device should maintain continuous, working connectivity by switching away
3684 * from WiFi networks having no connectivity.
3685 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3686 */
3687 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003688 if (!checkNetworkStackPermission()) {
3689 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3690 }
3691 return avoidBadWifi();
3692 }
3693
3694
Erik Kline065ab6e2016-10-02 18:02:14 +09003695 private void rematchForAvoidBadWifiUpdate() {
Chalard Jean1a4548c2019-11-07 18:54:49 +09003696 rematchAllNetworksAndRequests();
Erik Kline065ab6e2016-10-02 18:02:14 +09003697 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3698 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3699 sendUpdatedScoreToFactories(nai);
3700 }
3701 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003702 }
3703
Erik Kline065ab6e2016-10-02 18:02:14 +09003704 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003705 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003706 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003707 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003708 if (!configRestrict) {
3709 pw.println("Bad Wi-Fi avoidance: unrestricted");
3710 return;
3711 }
3712
3713 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3714 pw.increaseIndent();
3715 pw.println("Config restrict: " + configRestrict);
3716
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003717 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003718 String description;
3719 // Can't use a switch statement because strings are legal case labels, but null is not.
3720 if ("0".equals(value)) {
3721 description = "get stuck";
3722 } else if (value == null) {
3723 description = "prompt";
3724 } else if ("1".equals(value)) {
3725 description = "avoid";
3726 } else {
3727 description = value + " (?)";
3728 }
3729 pw.println("User setting: " + description);
3730 pw.println("Network overrides:");
3731 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003732 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003733 if (nai.avoidUnvalidated) {
3734 pw.println(nai.name());
3735 }
3736 }
3737 pw.decreaseIndent();
3738 pw.decreaseIndent();
3739 }
3740
lucaslind2e045e02019-01-24 15:55:30 +08003741 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003742 final String action;
Lorenzo Colitti938457e2019-06-05 16:08:37 +09003743 final boolean highPriority;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003744 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003745 case LOGGED_IN:
3746 action = Settings.ACTION_WIFI_SETTINGS;
3747 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3748 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3749 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
Lorenzo Colitti938457e2019-06-05 16:08:37 +09003750 // High priority because it is a direct result of the user logging in to a portal.
3751 highPriority = true;
lucaslind2e045e02019-01-24 15:55:30 +08003752 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003753 case NO_INTERNET:
3754 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti938457e2019-06-05 16:08:37 +09003755 // High priority because it is only displayed for explicitly selected networks.
3756 highPriority = true;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003757 break;
lucaslin783f2212019-10-22 18:27:33 +08003758 case PRIVATE_DNS_BROKEN:
3759 action = Settings.ACTION_WIRELESS_SETTINGS;
3760 // High priority because we should let user know why there is no internet.
3761 highPriority = true;
3762 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003763 case LOST_INTERNET:
3764 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti938457e2019-06-05 16:08:37 +09003765 // High priority because it could help the user avoid unexpected data usage.
3766 highPriority = true;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003767 break;
lucasline252a742019-03-12 13:08:03 +08003768 case PARTIAL_CONNECTIVITY:
3769 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti938457e2019-06-05 16:08:37 +09003770 // Don't bother the user with a high-priority notification if the network was not
3771 // explicitly selected by the user.
3772 highPriority = nai.networkMisc.explicitlySelected;
lucasline252a742019-03-12 13:08:03 +08003773 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003774 default:
3775 Slog.wtf(TAG, "Unknown notification type " + type);
3776 return;
3777 }
3778
3779 Intent intent = new Intent(action);
lucaslin783f2212019-10-22 18:27:33 +08003780 if (type != NotificationType.LOGGED_IN && type != NotificationType.PRIVATE_DNS_BROKEN) {
lucaslind2e045e02019-01-24 15:55:30 +08003781 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3782 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3783 intent.setClassName("com.android.settings",
3784 "com.android.settings.wifi.WifiNoInternetDialog");
3785 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003786
3787 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3788 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
Lorenzo Colitti938457e2019-06-05 16:08:37 +09003789
3790 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003791 }
3792
Lorenzo Colittiec2c7ec2019-06-04 19:29:50 +09003793 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
3794 // Don't prompt if the network is validated, and don't prompt on captive portals
3795 // because we're already prompting the user to sign in.
3796 if (nai.everValidated || nai.everCaptivePortalDetected) {
3797 return false;
3798 }
3799
3800 // If a network has partial connectivity, always prompt unless the user has already accepted
3801 // partial connectivity and selected don't ask again. This ensures that if the device
3802 // automatically connects to a network that has partial Internet access, the user will
3803 // always be able to use it, either because they've already chosen "don't ask again" or
3804 // because we have prompt them.
3805 if (nai.partialConnectivity && !nai.networkMisc.acceptPartialConnectivity) {
3806 return true;
3807 }
3808
3809 // If a network has no Internet access, only prompt if the network was explicitly selected
3810 // and if the user has not already told us to use the network regardless of whether it
3811 // validated or not.
3812 if (nai.networkMisc.explicitlySelected && !nai.networkMisc.acceptUnvalidated) {
3813 return true;
3814 }
3815
3816 return false;
3817 }
3818
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003819 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003820 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003821 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3822
Lorenzo Colittiec2c7ec2019-06-04 19:29:50 +09003823 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003824 return;
3825 }
Lorenzo Colitti22991332019-05-30 16:24:31 +09003826
3827 // Stop automatically reconnecting to this network in the future. Automatically connecting
3828 // to a network that provides no or limited connectivity is not useful, because the user
3829 // cannot use that network except through the notification shown by this method, and the
3830 // notification is only shown if the network is explicitly selected by the user.
3831 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3832
lucasline252a742019-03-12 13:08:03 +08003833 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3834 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3835 // popup the notification immediately when the network is partial connectivity.
3836 if (nai.partialConnectivity) {
lucaslin975b7d32019-03-21 11:59:22 +08003837 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucasline252a742019-03-12 13:08:03 +08003838 } else {
3839 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3840 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003841 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003842
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003843 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3844 NetworkCapabilities nc = nai.networkCapabilities;
3845 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003846
lucasline252a742019-03-12 13:08:03 +08003847 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3848 return;
3849 }
3850
3851 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003852 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003853 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003854 }
3855
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003856 @Override
3857 public int getMultipathPreference(Network network) {
3858 enforceAccessPermission();
3859
3860 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003861 if (nai != null && nai.networkCapabilities
3862 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003863 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3864 }
3865
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003866 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3867 if (networkPreference != null) {
3868 return networkPreference;
3869 }
3870
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003871 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3872 }
3873
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003874 @Override
3875 public NetworkRequest getDefaultRequest() {
3876 return mDefaultRequest;
3877 }
3878
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003879 private class InternalHandler extends Handler {
3880 public InternalHandler(Looper looper) {
3881 super(looper);
3882 }
3883
3884 @Override
3885 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003886 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003887 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003888 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003889 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003890 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003891 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003892 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003893 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003894 break;
3895 }
Jason Monkdecd2952013-10-10 14:02:51 -04003896 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003897 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003898 break;
3899 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003900 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003901 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3902 break;
3903 }
3904 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3905 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003906 break;
3907 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003908 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003909 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3910 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3911 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003912 break;
3913 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003914 case EVENT_REGISTER_NETWORK_REQUEST:
3915 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003916 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003917 break;
3918 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003919 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3920 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003921 handleRegisterNetworkRequestWithIntent(msg);
3922 break;
3923 }
Erik Kline57faba92015-11-25 12:49:38 +09003924 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3925 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3926 handleTimedOutNetworkRequest(nri);
3927 break;
3928 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003929 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3930 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3931 break;
3932 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003933 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenddb720a2019-01-08 12:09:18 -08003934 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3935 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003936 break;
3937 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003938 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003939 Network network = (Network) msg.obj;
3940 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003941 break;
3942 }
lucasline252a742019-03-12 13:08:03 +08003943 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3944 Network network = (Network) msg.obj;
3945 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3946 toBool(msg.arg2));
3947 break;
3948 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003949 case EVENT_SET_AVOID_UNVALIDATED: {
3950 handleSetAvoidUnvalidated((Network) msg.obj);
3951 break;
3952 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003953 case EVENT_PROMPT_UNVALIDATED: {
3954 handlePromptUnvalidated((Network) msg.obj);
3955 break;
3956 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003957 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3958 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003959 break;
3960 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003961 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003962 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003963 mKeepaliveTracker.handleStartKeepalive(msg);
3964 break;
3965 }
3966 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003967 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003968 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3969 int slot = msg.arg1;
3970 int reason = msg.arg2;
3971 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3972 break;
3973 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003974 case EVENT_SYSTEM_READY: {
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003975 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003976 break;
3977 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003978 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003979 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003980 break;
3981 }
Erik Klinea24d4592018-01-11 21:07:29 +09003982 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3983 handlePrivateDnsSettingsChanged();
3984 break;
dalyk7301aa42018-03-05 12:42:22 -05003985 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3986 handlePrivateDnsValidationUpdate(
3987 (PrivateDnsValidationUpdate) msg.obj);
3988 break;
junyulai05986c62018-08-07 19:50:45 +08003989 case EVENT_UID_RULES_CHANGED:
3990 handleUidRulesChanged(msg.arg1, msg.arg2);
3991 break;
3992 case EVENT_DATA_SAVER_CHANGED:
3993 handleRestrictBackgroundChanged(toBool(msg.arg1));
3994 break;
lucaslind2e045e02019-01-24 15:55:30 +08003995 case EVENT_TIMEOUT_NOTIFICATION:
3996 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3997 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
3999 }
4000 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004001
4002 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09004003 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09004004 public int tether(String iface, String callerPkg) {
4005 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08004006 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09004007 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08004008 } else {
4009 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
4010 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004011 }
4012
4013 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09004014 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09004015 public int untether(String iface, String callerPkg) {
4016 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08004017
4018 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09004019 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08004020 } else {
4021 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
4022 }
4023 }
4024
4025 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09004026 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08004027 public int getLastTetherError(String iface) {
4028 enforceTetherAccessPermission();
4029
4030 if (isTetheringSupported()) {
4031 return mTethering.getLastTetherError(iface);
4032 } else {
4033 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
4034 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004035 }
4036
4037 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09004038 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004039 public String[] getTetherableUsbRegexs() {
4040 enforceTetherAccessPermission();
4041 if (isTetheringSupported()) {
4042 return mTethering.getTetherableUsbRegexs();
4043 } else {
4044 return new String[0];
4045 }
4046 }
4047
Lorenzo Colitti18660282016-07-04 12:55:44 +09004048 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004049 public String[] getTetherableWifiRegexs() {
4050 enforceTetherAccessPermission();
4051 if (isTetheringSupported()) {
4052 return mTethering.getTetherableWifiRegexs();
4053 } else {
4054 return new String[0];
4055 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004056 }
4057
Lorenzo Colitti18660282016-07-04 12:55:44 +09004058 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07004059 public String[] getTetherableBluetoothRegexs() {
4060 enforceTetherAccessPermission();
4061 if (isTetheringSupported()) {
4062 return mTethering.getTetherableBluetoothRegexs();
4063 } else {
4064 return new String[0];
4065 }
4066 }
4067
Lorenzo Colitti18660282016-07-04 12:55:44 +09004068 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09004069 public int setUsbTethering(boolean enable, String callerPkg) {
4070 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07004071 if (isTetheringSupported()) {
4072 return mTethering.setUsbTethering(enable);
4073 } else {
4074 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
4075 }
4076 }
4077
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004078 // TODO - move iface listing, queries, etc to new module
4079 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09004080 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004081 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004082 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004083 return mTethering.getTetherableIfaces();
4084 }
4085
Lorenzo Colitti18660282016-07-04 12:55:44 +09004086 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004087 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004088 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08004089 return mTethering.getTetheredIfaces();
4090 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004091
Lorenzo Colitti18660282016-07-04 12:55:44 +09004092 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08004093 public String[] getTetheringErroredIfaces() {
4094 enforceTetherAccessPermission();
4095 return mTethering.getErroredIfaces();
4096 }
4097
Lorenzo Colitti18660282016-07-04 12:55:44 +09004098 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07004099 public String[] getTetheredDhcpRanges() {
4100 enforceConnectivityInternalPermission();
4101 return mTethering.getTetheredDhcpRanges();
4102 }
4103
Udam Saini0e94c362017-06-07 12:06:28 -07004104 @Override
4105 public boolean isTetheringSupported(String callerPkg) {
4106 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
4107 return isTetheringSupported();
4108 }
4109
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004110 // if ro.tether.denied = true we default to no tethering
4111 // gservices could set the secure setting to 1 though to enable it on a build where it
4112 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07004113 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004114 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
4115 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
4116 Settings.Global.TETHER_SUPPORTED, defaultVal));
4117 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04004118 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07004119
4120 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
4121 boolean adminUser = false;
4122 final long token = Binder.clearCallingIdentity();
4123 try {
4124 adminUser = mUserManager.isAdminUser();
4125 } finally {
4126 Binder.restoreCallingIdentity(token);
4127 }
4128
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004129 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08004130 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07004131
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08004132 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09004133 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
4134 String callerPkg) {
4135 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08004136 if (!isTetheringSupported()) {
4137 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
4138 return;
4139 }
4140 mTethering.startTethering(type, receiver, showProvisioningUi);
4141 }
4142
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08004143 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09004144 public void stopTethering(int type, String callerPkg) {
4145 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08004146 mTethering.stopTethering(type);
4147 }
4148
markchienf2731272019-01-16 17:44:13 +08004149 /**
4150 * Get the latest value of the tethering entitlement check.
4151 *
4152 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
4153 * out some such apps are observed to abuse this API, change to per-UID limits on this API
4154 * if it's really needed.
4155 */
4156 @Override
markchien9554abf2019-03-06 16:25:00 +08004157 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08004158 boolean showEntitlementUi, String callerPkg) {
4159 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08004160 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08004161 }
4162
markchien26299ed2019-02-27 14:56:11 +08004163 /** Register tethering event callback. */
4164 @Override
4165 public void registerTetheringEventCallback(ITetheringEventCallback callback,
4166 String callerPkg) {
4167 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
4168 mTethering.registerTetheringEventCallback(callback);
4169 }
4170
4171 /** Unregister tethering event callback. */
4172 @Override
4173 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
4174 String callerPkg) {
4175 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
4176 mTethering.unregisterTetheringEventCallback(callback);
4177 }
4178
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07004179 // Called when we lose the default network and have no replacement yet.
4180 // This will automatically be cleared after X seconds or a new default network
4181 // becomes CONNECTED, whichever happens first. The timer is started by the
4182 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09004183 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07004184 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09004185 if (mNetTransitionWakeLock.isHeld()) {
4186 return;
4187 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07004188 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09004189 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4190 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07004191 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004192 mWakelockLogs.log("ACQUIRE for " + forWhom);
4193 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4194 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07004195 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07004196
Hugo Benichi4c31b342017-03-30 23:18:10 +09004197 // Called when we gain a new default network to release the network transition wakelock in a
4198 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4199 // message is cancelled.
4200 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004201 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09004202 if (!mNetTransitionWakeLock.isHeld()) {
4203 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004204 }
4205 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004206 // Cancel self timeout on wakelock hold.
4207 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4208 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4209 mHandler.sendMessageDelayed(msg, 1000);
4210 }
4211
4212 // Called when either message of ensureNetworkTransitionWakelock or
4213 // scheduleReleaseNetworkTransitionWakelock is processed.
4214 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4215 String event = eventName(eventId);
4216 synchronized (this) {
4217 if (!mNetTransitionWakeLock.isHeld()) {
4218 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4219 Slog.w(TAG, "expected Net Transition WakeLock to be held");
4220 return;
4221 }
4222 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09004223 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4224 mTotalWakelockDurationMs += lockDuration;
4225 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4226 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004227 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004228 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004229 }
4230
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004231 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09004232 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004233 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004234 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004235 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004236 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004237 }
4238
Lorenzo Colitti18660282016-07-04 12:55:44 +09004239 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004240 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004241 enforceAccessPermission();
4242 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004243 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004244 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004245 mHandler.sendMessage(
4246 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4247 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004248
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004249 private void handleReportNetworkConnectivity(
4250 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004251 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004252 if (network == null) {
4253 nai = getDefaultNetwork();
4254 } else {
4255 nai = getNetworkAgentInfoForNetwork(network);
4256 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004257 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4258 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4259 return;
4260 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004261 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004262 if (hasConnectivity == nai.lastValidated) {
4263 return;
4264 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004265 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004266 int netid = nai.network.netId;
4267 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004268 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004269 // Validating a network that has not yet connected could result in a call to
4270 // rematchNetworkAndRequests() which is not meant to work on such networks.
4271 if (!nai.everConnected) {
4272 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004273 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004274 LinkProperties lp = getLinkProperties(nai);
4275 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4276 return;
4277 }
Lorenzo Colittiac955b32019-05-31 15:41:29 +09004278 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004279 }
4280
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004281 /**
4282 * Returns information about the proxy a certain network is using. If given a null network, it
4283 * it will return the proxy for the bound network for the caller app or the default proxy if
4284 * none.
4285 *
4286 * @param network the network we want to get the proxy information for.
4287 * @return Proxy information if a network has a proxy configured, or otherwise null.
4288 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004289 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004290 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004291 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004292 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004293 if (network == null) {
4294 // Get the network associated with the calling UID.
4295 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4296 true);
4297 if (activeNetwork == null) {
4298 return null;
4299 }
4300 return getLinkPropertiesProxyInfo(activeNetwork);
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09004301 } else if (mDeps.queryUserAccess(Binder.getCallingUid(), network.netId)) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004302 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4303 // caller may not have.
4304 return getLinkPropertiesProxyInfo(network);
4305 }
4306 // No proxy info available if the calling UID does not have network access.
4307 return null;
4308 }
4309
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004310
4311 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004312 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4313 if (nai == null) return null;
4314 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004315 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4316 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004317 }
4318 }
4319
Chalard Jean3c443fc2018-06-07 18:37:59 +09004320 @Override
4321 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004322 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004323 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004324 }
4325
Chalard Jean5afbc832018-06-07 18:02:37 +09004326 @Override
4327 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004328 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004329 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004330 }
4331
Jason Monk207900c2014-04-25 15:00:09 -04004332 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004333 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004334 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004335 proxy = null;
4336 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004337 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004338 }
4339
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004340 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4341 // when any network changes proxy.
4342 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4343 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004344 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004345 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4346 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4347
Chalard Jean4949dd72018-06-07 17:41:29 +09004348 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004349 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004350 }
4351 }
4352
Robert Greenwalt434203a2010-10-11 16:00:27 -07004353 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004354 final private HashMap<Uri, Integer> mUriEventMap;
4355 final private Context mContext;
4356 final private Handler mHandler;
4357
4358 SettingsObserver(Context context, Handler handler) {
4359 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004360 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004361 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004362 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004363 }
4364
Erik Klineda4bfa82015-04-30 12:58:40 +09004365 void observe(Uri uri, int what) {
4366 mUriEventMap.put(uri, what);
4367 final ContentResolver resolver = mContext.getContentResolver();
4368 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004369 }
4370
4371 @Override
4372 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004373 Slog.wtf(TAG, "Should never be reached.");
4374 }
4375
4376 @Override
4377 public void onChange(boolean selfChange, Uri uri) {
4378 final Integer what = mUriEventMap.get(uri);
4379 if (what != null) {
Chalard Jeanafdecd52019-09-26 18:03:47 +09004380 mHandler.obtainMessage(what).sendToTarget();
Erik Klineda4bfa82015-04-30 12:58:40 +09004381 } else {
4382 loge("No matching event to send for URI=" + uri);
4383 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004384 }
4385 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004386
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004387 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004388 Slog.d(TAG, s);
4389 }
4390
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004391 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004392 Slog.e(TAG, s);
4393 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004394
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004395 private static void loge(String s, Throwable t) {
4396 Slog.e(TAG, s, t);
4397 }
4398
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004399 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004400 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004401 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4402 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4403 *
4404 * @param oldPackage Package name of the application which currently controls VPN, which will
4405 * be replaced. If there is no such application, this should should either be
4406 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4407 * @param newPackage Package name of the application which should gain control of VPN, or
4408 * {@code null} to disable.
4409 * @param userId User for whom to prepare the new VPN.
4410 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004411 * @hide
4412 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004413 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004414 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4415 int userId) {
4416 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004417
Hugo Benichi20035e02017-04-26 14:53:28 +09004418 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004419 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004420 Vpn vpn = mVpns.get(userId);
4421 if (vpn != null) {
4422 return vpn.prepare(oldPackage, newPackage);
4423 } else {
4424 return false;
4425 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004426 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004427 }
4428
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004429 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004430 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4431 * This method is used by system-privileged apps.
4432 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4433 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4434 *
4435 * @param packageName The package for which authorization state should change.
4436 * @param userId User for whom {@code packageName} is installed.
4437 * @param authorized {@code true} if this app should be able to start a VPN connection without
4438 * explicit user approval, {@code false} if not.
4439 *
Jeff Davidson05542602014-08-11 14:07:27 -07004440 * @hide
4441 */
4442 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004443 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4444 enforceCrossUserPermission(userId);
4445
Hugo Benichi20035e02017-04-26 14:53:28 +09004446 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004447 Vpn vpn = mVpns.get(userId);
4448 if (vpn != null) {
4449 vpn.setPackageAuthorization(packageName, authorized);
4450 }
Jeff Davidson05542602014-08-11 14:07:27 -07004451 }
4452 }
4453
4454 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004455 * Configure a TUN interface and return its file descriptor. Parameters
4456 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004457 * and not available in ConnectivityManager. Permissions are checked in
4458 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004459 * @hide
4460 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004461 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004462 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004463 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004464 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004465 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004466 return mVpns.get(user).establish(config);
4467 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004468 }
4469
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004470 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004471 * Start legacy VPN, controlling native daemons as needed. Creates a
4472 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004473 */
4474 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004475 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004476 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004477 final LinkProperties egress = getActiveLinkProperties();
4478 if (egress == null) {
4479 throw new IllegalStateException("Missing active network connection");
4480 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004481 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004482 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004483 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4484 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004485 }
4486
4487 /**
4488 * Return the information of the ongoing legacy VPN. This method is used
4489 * by VpnSettings and not available in ConnectivityManager. Permissions
4490 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004491 */
4492 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004493 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4494 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004495
Hugo Benichi20035e02017-04-26 14:53:28 +09004496 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004497 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004498 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004499 }
4500
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004501 /**
Varun Anandd33cbc62019-02-07 14:13:13 -08004502 * Return the information of all ongoing VPNs.
4503 *
4504 * <p>This method is used to update NetworkStatsService.
4505 *
4506 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004507 */
Varun Anandd33cbc62019-02-07 14:13:13 -08004508 private VpnInfo[] getAllVpnInfo() {
4509 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004510 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004511 if (mLockdownEnabled) {
4512 return new VpnInfo[0];
4513 }
4514
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004515 List<VpnInfo> infoList = new ArrayList<>();
4516 for (int i = 0; i < mVpns.size(); i++) {
4517 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4518 if (info != null) {
4519 infoList.add(info);
4520 }
4521 }
4522 return infoList.toArray(new VpnInfo[infoList.size()]);
4523 }
4524 }
4525
4526 /**
4527 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wonga84d9fa2019-06-12 17:46:15 +00004528 * information, e.g underlying ifaces.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004529 */
4530 @Nullable
4531 private VpnInfo createVpnInfo(Vpn vpn) {
4532 VpnInfo info = vpn.getVpnInfo();
4533 if (info == null) {
4534 return null;
4535 }
4536 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4537 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4538 // the underlyingNetworks list.
4539 if (underlyingNetworks == null) {
Benedict Wonga84d9fa2019-06-12 17:46:15 +00004540 NetworkAgentInfo defaultNai = getDefaultNetwork();
Benedict Wong9fbbdeb2019-06-12 17:46:31 +00004541 if (defaultNai != null) {
Benedict Wonga84d9fa2019-06-12 17:46:15 +00004542 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004543 }
4544 }
Benedict Wonga84d9fa2019-06-12 17:46:15 +00004545 if (underlyingNetworks != null && underlyingNetworks.length > 0) {
4546 List<String> interfaces = new ArrayList<>();
4547 for (Network network : underlyingNetworks) {
4548 LinkProperties lp = getLinkProperties(network);
4549 if (lp != null) {
Benedict Wong9fbbdeb2019-06-12 17:46:31 +00004550 for (String iface : lp.getAllInterfaceNames()) {
4551 if (!TextUtils.isEmpty(iface)) {
4552 interfaces.add(iface);
4553 }
4554 }
Benedict Wonga84d9fa2019-06-12 17:46:15 +00004555 }
4556 }
4557 if (!interfaces.isEmpty()) {
4558 info.underlyingIfaces = interfaces.toArray(new String[interfaces.size()]);
4559 }
4560 }
4561 return info.underlyingIfaces == null ? null : info;
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004562 }
4563
4564 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004565 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4566 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004567 * Permissions are checked in Vpn class.
4568 * @hide
4569 */
4570 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004571 public VpnConfig getVpnConfig(int userId) {
4572 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004573 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004574 Vpn vpn = mVpns.get(userId);
4575 if (vpn != null) {
4576 return vpn.getVpnConfig();
4577 } else {
4578 return null;
4579 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004580 }
4581 }
4582
Chalard Jean6b65ec72018-05-18 22:02:56 +09004583 /**
4584 * Ask all VPN objects to recompute and update their capabilities.
4585 *
4586 * When underlying networks change, VPNs may have to update capabilities to reflect things
4587 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4588 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4589 * handler thread through their agent, this is asynchronous. When the capabilities objects
4590 * are computed they will be up-to-date as they are computed synchronously from here and
4591 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004592 */
4593 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004594 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004595 synchronized (mVpns) {
4596 for (int i = 0; i < mVpns.size(); i++) {
4597 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004598 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4599 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004600 }
4601 }
4602 }
4603
Varun Anand4fa80e82019-02-06 10:13:38 -08004604 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4605 ensureRunningOnConnectivityServiceThread();
4606 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4607 if (vpnNai == null || nc == null) {
4608 return;
4609 }
4610 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4611 }
4612
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004613 @Override
4614 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004615 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4616 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4617 return false;
4618 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004619
Hugo Benichi69744342017-11-27 10:57:16 +09004620 synchronized (mVpns) {
4621 // Tear down existing lockdown if profile was removed
4622 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4623 if (mLockdownEnabled) {
4624 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4625 if (profileTag == null) {
4626 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4627 return false;
4628 }
4629 String profileName = new String(profileTag);
4630 final VpnProfile profile = VpnProfile.decode(
4631 profileName, mKeyStore.get(Credentials.VPN + profileName));
4632 if (profile == null) {
4633 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4634 setLockdownTracker(null);
4635 return true;
4636 }
4637 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004638 Vpn vpn = mVpns.get(user);
4639 if (vpn == null) {
4640 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4641 return false;
4642 }
junyulai465088e2019-08-30 16:44:45 +08004643 setLockdownTracker(new LockdownVpnTracker(mContext, this, mHandler, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004644 } else {
4645 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004646 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004647 }
4648
4649 return true;
4650 }
4651
4652 /**
4653 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4654 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4655 */
Hugo Benichi69744342017-11-27 10:57:16 +09004656 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004657 private void setLockdownTracker(LockdownVpnTracker tracker) {
4658 // Shutdown any existing tracker
4659 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004660 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4661 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004662 mLockdownTracker = null;
4663 if (existing != null) {
4664 existing.shutdown();
4665 }
4666
Robin Leec3736bc2017-03-10 16:19:54 +00004667 if (tracker != null) {
4668 mLockdownTracker = tracker;
4669 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004670 }
4671 }
4672
Hugo Benichi69744342017-11-27 10:57:16 +09004673 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004674 private void throwIfLockdownEnabled() {
4675 if (mLockdownEnabled) {
4676 throw new IllegalStateException("Unavailable in lockdown mode");
4677 }
4678 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004679
Robin Lee244ce8e2016-01-05 18:03:46 +00004680 /**
Robin Lee17e61832016-05-09 13:46:28 +01004681 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4682 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004683 *
Robin Lee17e61832016-05-09 13:46:28 +01004684 * @return {@code true} if the service was started, the service was already connected, or there
4685 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004686 */
Robin Lee17e61832016-05-09 13:46:28 +01004687 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004688 synchronized (mVpns) {
4689 Vpn vpn = mVpns.get(userId);
4690 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004691 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004692 // exists already.
4693 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4694 return false;
4695 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004696
Robin Lee812800c2016-05-13 15:38:08 +01004697 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004698 }
4699 }
4700
4701 @Override
Charles He36738632017-05-15 17:07:18 +01004702 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4703 enforceSettingsPermission();
4704 enforceCrossUserPermission(userId);
4705
4706 synchronized (mVpns) {
4707 Vpn vpn = mVpns.get(userId);
4708 if (vpn == null) {
4709 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4710 return false;
4711 }
4712 return vpn.isAlwaysOnPackageSupported(packageName);
4713 }
4714 }
4715
4716 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004717 public boolean setAlwaysOnVpnPackage(
4718 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4719 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004720 enforceCrossUserPermission(userId);
4721
Robin Lee244ce8e2016-01-05 18:03:46 +00004722 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004723 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4724 if (LockdownVpnTracker.isEnabled()) {
4725 return false;
4726 }
4727
Robin Lee244ce8e2016-01-05 18:03:46 +00004728 Vpn vpn = mVpns.get(userId);
4729 if (vpn == null) {
4730 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4731 return false;
4732 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004733 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004734 return false;
4735 }
Robin Lee17e61832016-05-09 13:46:28 +01004736 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004737 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004738 return false;
4739 }
4740 }
4741 return true;
4742 }
4743
4744 @Override
4745 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004746 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004747 enforceCrossUserPermission(userId);
4748
4749 synchronized (mVpns) {
4750 Vpn vpn = mVpns.get(userId);
4751 if (vpn == null) {
4752 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4753 return null;
4754 }
4755 return vpn.getAlwaysOnPackage();
4756 }
4757 }
4758
Wink Savilleab9321d2013-06-29 21:10:57 -07004759 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004760 public boolean isVpnLockdownEnabled(int userId) {
4761 enforceControlAlwaysOnVpnPermission();
4762 enforceCrossUserPermission(userId);
4763
4764 synchronized (mVpns) {
4765 Vpn vpn = mVpns.get(userId);
4766 if (vpn == null) {
4767 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4768 return false;
4769 }
4770 return vpn.getLockdown();
4771 }
4772 }
4773
4774 @Override
4775 public List<String> getVpnLockdownWhitelist(int userId) {
4776 enforceControlAlwaysOnVpnPermission();
4777 enforceCrossUserPermission(userId);
4778
4779 synchronized (mVpns) {
4780 Vpn vpn = mVpns.get(userId);
4781 if (vpn == null) {
4782 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4783 return null;
4784 }
4785 return vpn.getLockdownWhitelist();
4786 }
4787 }
4788
4789 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004790 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004791 // TODO: Remove? Any reason to trigger a provisioning check?
4792 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004793 }
4794
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004795 /** Location to an updatable file listing carrier provisioning urls.
4796 * An example:
4797 *
4798 * <?xml version="1.0" encoding="utf-8"?>
4799 * <provisioningUrls>
4800 * <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 -07004801 * </provisioningUrls>
4802 */
4803 private static final String PROVISIONING_URL_PATH =
4804 "/data/misc/radio/provisioning_urls.xml";
4805 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004806
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004807 /** XML tag for root element. */
4808 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4809 /** XML tag for individual url */
4810 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004811 /** XML attribute for mcc */
4812 private static final String ATTR_MCC = "mcc";
4813 /** XML attribute for mnc */
4814 private static final String ATTR_MNC = "mnc";
4815
Paul Jensen434dde82015-06-11 09:43:30 -04004816 private String getProvisioningUrlBaseFromFile() {
Chalard Jeanafdecd52019-09-26 18:03:47 +09004817 XmlPullParser parser;
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004818 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004819
Chalard Jeanafdecd52019-09-26 18:03:47 +09004820 try (FileReader fileReader = new FileReader(mProvisioningUrlFile)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004821 parser = Xml.newPullParser();
4822 parser.setInput(fileReader);
4823 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4824
4825 while (true) {
4826 XmlUtils.nextElement(parser);
4827
4828 String element = parser.getName();
4829 if (element == null) break;
4830
Paul Jensen434dde82015-06-11 09:43:30 -04004831 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004832 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4833 try {
4834 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4835 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4836 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4837 parser.next();
4838 if (parser.getEventType() == XmlPullParser.TEXT) {
4839 return parser.getText();
4840 }
4841 }
4842 }
4843 } catch (NumberFormatException e) {
4844 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4845 }
4846 }
4847 }
4848 return null;
4849 } catch (FileNotFoundException e) {
4850 loge("Carrier Provisioning Urls file not found");
4851 } catch (XmlPullParserException e) {
4852 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4853 } catch (IOException e) {
4854 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004855 }
4856 return null;
4857 }
4858
Wink Saville42d4f082013-07-20 20:31:59 -07004859 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004860 public String getMobileProvisioningUrl() {
4861 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004862 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004863 if (TextUtils.isEmpty(url)) {
4864 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004865 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004866 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004867 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004868 }
Wink Saville8cf35602013-07-10 23:00:07 -07004869 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004870 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004871 String phoneNumber = mTelephonyManager.getLine1Number();
4872 if (TextUtils.isEmpty(phoneNumber)) {
4873 phoneNumber = "0000000000";
4874 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004875 url = String.format(url,
4876 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4877 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004878 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004879 }
4880
Wink Savilleab9321d2013-06-29 21:10:57 -07004881 return url;
4882 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004883
Wink Saville948282b2013-08-29 08:55:16 -07004884 @Override
4885 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004886 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004887 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004888 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4889 return;
4890 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004891 final long ident = Binder.clearCallingIdentity();
4892 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004893 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09004894 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004895 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004896 } finally {
4897 Binder.restoreCallingIdentity(ident);
4898 }
Wink Saville948282b2013-08-29 08:55:16 -07004899 }
Wink Saville7788c612013-08-29 14:57:08 -07004900
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004901 @Override
4902 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004903 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004904 final long ident = Binder.clearCallingIdentity();
4905 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004906 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004907 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004908 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4909 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004910 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004911 } finally {
4912 Binder.restoreCallingIdentity(ident);
4913 }
4914 }
4915
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004916 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004917 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004918 Vpn userVpn = mVpns.get(userId);
4919 if (userVpn != null) {
4920 loge("Starting user already has a VPN");
4921 return;
4922 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004923 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004924 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004925 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4926 updateLockdownVpn();
4927 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004928 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004929 }
4930
4931 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004932 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004933 Vpn userVpn = mVpns.get(userId);
4934 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004935 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004936 return;
4937 }
Robin Lee17e61832016-05-09 13:46:28 +01004938 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004939 mVpns.delete(userId);
4940 }
4941 }
4942
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004943 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004944 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004945 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004946 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004947 final int vpnsSize = mVpns.size();
4948 for (int i = 0; i < vpnsSize; i++) {
4949 Vpn vpn = mVpns.valueAt(i);
4950 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004951 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4952 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004953 }
4954 }
4955 }
4956
4957 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004958 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004959 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004960 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004961 final int vpnsSize = mVpns.size();
4962 for (int i = 0; i < vpnsSize; i++) {
4963 Vpn vpn = mVpns.valueAt(i);
4964 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004965 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4966 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004967 }
4968 }
4969 }
4970
junyulai2454b692018-11-01 17:16:31 +08004971 private void onPackageAdded(String packageName, int uid) {
4972 if (TextUtils.isEmpty(packageName) || uid < 0) {
4973 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4974 return;
4975 }
4976 mPermissionMonitor.onPackageAdded(packageName, uid);
4977 }
4978
junyulaiefb04d32018-11-12 22:39:30 +08004979 private void onPackageReplaced(String packageName, int uid) {
4980 if (TextUtils.isEmpty(packageName) || uid < 0) {
4981 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4982 return;
4983 }
4984 final int userId = UserHandle.getUserId(uid);
4985 synchronized (mVpns) {
4986 final Vpn vpn = mVpns.get(userId);
4987 if (vpn == null) {
4988 return;
4989 }
4990 // Legacy always-on VPN won't be affected since the package name is not set.
4991 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4992 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4993 + userId);
4994 vpn.startAlwaysOnVpn();
4995 }
4996 }
4997 }
4998
4999 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08005000 if (TextUtils.isEmpty(packageName) || uid < 0) {
5001 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
5002 return;
5003 }
5004 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08005005
5006 final int userId = UserHandle.getUserId(uid);
5007 synchronized (mVpns) {
5008 final Vpn vpn = mVpns.get(userId);
5009 if (vpn == null) {
5010 return;
5011 }
5012 // Legacy always-on VPN won't be affected since the package name is not set.
5013 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
5014 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
5015 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00005016 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08005017 }
5018 }
junyulai2454b692018-11-01 17:16:31 +08005019 }
5020
Robin Lee89e7a692016-02-29 14:38:17 +00005021 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09005022 synchronized (mVpns) {
5023 // User present may be sent because of an unlock, which might mean an unlocked keystore.
5024 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
5025 updateLockdownVpn();
5026 } else {
5027 startAlwaysOnVpn(userId);
5028 }
Robin Lee9a5f4852015-12-17 11:42:22 +00005029 }
5030 }
5031
junyulai2454b692018-11-01 17:16:31 +08005032 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07005033 @Override
5034 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08005035 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07005036 final String action = intent.getAction();
5037 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08005038 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
5039 final Uri packageData = intent.getData();
5040 final String packageName =
5041 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07005042 if (userId == UserHandle.USER_NULL) return;
5043
Robin Lee323f29d2016-05-04 16:38:06 +01005044 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07005045 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07005046 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07005047 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07005048 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
5049 onUserAdded(userId);
5050 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5051 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00005052 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
5053 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08005054 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
5055 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08005056 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
5057 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08005058 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08005059 final boolean isReplacing = intent.getBooleanExtra(
5060 Intent.EXTRA_REPLACING, false);
5061 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07005062 }
5063 }
5064 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07005065
Robin Lee95204e02017-01-27 11:59:22 +00005066 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
5067 @Override
5068 public void onReceive(Context context, Intent intent) {
5069 // Try creating lockdown tracker, since user present usually means
5070 // unlocked keystore.
5071 updateLockdownVpn();
5072 mContext.unregisterReceiver(this);
5073 }
5074 };
5075
Chalard Jean4133a122018-06-04 13:33:12 +09005076 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
5077 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07005078
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04005079 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
5080 // Map from UID to number of NetworkRequests that UID has filed.
5081 @GuardedBy("mUidToNetworkRequestCount")
5082 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
5083
Robert Greenwalta67be032014-05-16 15:49:14 -07005084 private static class NetworkFactoryInfo {
5085 public final String name;
5086 public final Messenger messenger;
5087 public final AsyncChannel asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09005088 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07005089
Chalard Jean05ab6812018-05-02 21:14:54 +09005090 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
5091 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07005092 this.name = name;
5093 this.messenger = messenger;
5094 this.asyncChannel = asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09005095 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07005096 }
5097 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005098
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005099 private void ensureNetworkRequestHasType(NetworkRequest request) {
5100 if (request.type == NetworkRequest.Type.NONE) {
5101 throw new IllegalArgumentException(
5102 "All NetworkRequests in ConnectivityService must have a type");
5103 }
5104 }
5105
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005106 /**
5107 * Tracks info about the requester.
5108 * Also used to notice when the calling process dies so we can self-expire
5109 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07005110 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005111 final NetworkRequest request;
Chalard Jean68602592019-11-05 15:07:09 +09005112 // The network currently satisfying this request, or null if none. Must only be touched
5113 // on the handler thread. This only makes sense for network requests and not for listens,
5114 // as defined by NetworkRequest#isRequest(). For listens, this is always null.
5115 @Nullable
5116 NetworkAgentInfo mSatisfier;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005117 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08005118 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005119 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005120 final int mPid;
5121 final int mUid;
5122 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005123
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005124 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005125 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005126 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005127 mPendingIntent = pi;
5128 messenger = null;
5129 mBinder = null;
5130 mPid = getCallingPid();
5131 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04005132 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005133 }
5134
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005135 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005136 super();
5137 messenger = m;
5138 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005139 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005140 mBinder = binder;
5141 mPid = getCallingPid();
5142 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005143 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04005144 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005145
5146 try {
5147 mBinder.linkToDeath(this, 0);
5148 } catch (RemoteException e) {
5149 binderDied();
5150 }
5151 }
5152
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04005153 private void enforceRequestCountLimit() {
5154 synchronized (mUidToNetworkRequestCount) {
5155 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
5156 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09005157 throw new ServiceSpecificException(
5158 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04005159 }
5160 mUidToNetworkRequestCount.put(mUid, networkRequests);
5161 }
5162 }
5163
Robert Greenwalt9258c642014-03-26 16:47:06 -07005164 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005165 if (mBinder != null) {
5166 mBinder.unlinkToDeath(this, 0);
5167 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005168 }
5169
5170 public void binderDied() {
5171 log("ConnectivityService NetworkRequestInfo binderDied(" +
5172 request + ", " + mBinder + ")");
5173 releaseNetworkRequest(request);
5174 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005175
5176 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005177 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005178 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07005179 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005180 }
5181
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005182 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5183 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5184 if (badCapability != null) {
5185 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04005186 }
5187 }
5188
Chalard Jeanafdecd52019-09-26 18:03:47 +09005189 // This checks that the passed capabilities either do not request a
5190 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005191 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5192 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09005193 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09005194 throw new SecurityException("Insufficient permissions to request a specific SSID");
5195 }
paulhu3d67f532019-03-22 16:35:06 +08005196
5197 if (nc.hasSignalStrength()
5198 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5199 throw new SecurityException(
5200 "Insufficient permissions to request a specific signal strength");
5201 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09005202 }
5203
Erik Kline9d598e12015-07-13 16:37:51 +09005204 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09005205 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005206 synchronized (nai) {
5207 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5208 if (nri.request.networkCapabilities.hasSignalStrength() &&
5209 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
5210 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
5211 }
5212 }
5213 }
Chalard Jean4133a122018-06-04 13:33:12 +09005214 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005215 }
5216
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005217 private void updateSignalStrengthThresholds(
5218 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5219 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09005220 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005221 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
5222
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005223 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005224 String detail;
5225 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5226 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5227 } else {
5228 detail = reason;
5229 }
5230 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5231 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
5232 }
5233
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005234 nai.asyncChannel.sendMessage(
5235 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09005236 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005237 }
5238
Etan Cohen859748f2017-04-03 17:42:34 -07005239 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5240 if (nc == null) {
5241 return;
5242 }
5243 NetworkSpecifier ns = nc.getNetworkSpecifier();
5244 if (ns == null) {
5245 return;
5246 }
5247 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5248 ns.assertValidFromUid(Binder.getCallingUid());
5249 }
5250
lucaslin783f2212019-10-22 18:27:33 +08005251 private void ensureValid(NetworkCapabilities nc) {
5252 ensureValidNetworkSpecifier(nc);
5253 if (nc.isPrivateDnsBroken()) {
5254 throw new IllegalArgumentException("Can't request broken private DNS");
5255 }
5256 }
5257
Robert Greenwalt9258c642014-03-26 16:47:06 -07005258 @Override
5259 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005260 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005261 final NetworkRequest.Type type = (networkCapabilities == null)
5262 ? NetworkRequest.Type.TRACK_DEFAULT
5263 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005264 // If the requested networkCapabilities is null, take them instead from
5265 // the default network request. This allows callers to keep track of
5266 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005267 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005268 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005269 enforceAccessPermission();
5270 } else {
5271 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5272 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005273 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5274 // of the app when the request is filed, but we never change the request if the app
5275 // changes network state. http://b/29964605
5276 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005277 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005278 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005279 ensureSufficientPermissionsForRequest(networkCapabilities,
5280 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005281 // Set the UID range for this request to the single UID of the requester, or to an empty
5282 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005283 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5284 // are no visible methods to set the UIDs, an app could use reflection to try and get
5285 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005286 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005287
Etan Cohenba07c8c2017-02-05 10:42:27 -08005288 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005289 throw new IllegalArgumentException("Bad timeout specified");
5290 }
lucaslin783f2212019-10-22 18:27:33 +08005291 ensureValid(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005292
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005293 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005294 nextNetworkRequestId(), type);
5295 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005296 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005297
5298 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005299 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005300 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005301 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005302 }
5303 return networkRequest;
5304 }
5305
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005306 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005307 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005308 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005309 } else {
5310 enforceChangePermission();
5311 }
5312 }
5313
fenglub15e72b2015-03-20 11:29:56 -07005314 @Override
fengludb571472015-04-21 17:12:05 -07005315 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005316 enforceAccessPermission();
5317 NetworkAgentInfo nai = null;
5318 if (network == null) {
5319 return false;
5320 }
5321 synchronized (mNetworkForNetId) {
5322 nai = mNetworkForNetId.get(network.netId);
5323 }
5324 if (nai != null) {
5325 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005326 synchronized (mBandwidthRequests) {
5327 final int uid = Binder.getCallingUid();
5328 Integer uidReqs = mBandwidthRequests.get(uid);
5329 if (uidReqs == null) {
Chalard Jeanafdecd52019-09-26 18:03:47 +09005330 uidReqs = 0;
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005331 }
5332 mBandwidthRequests.put(uid, ++uidReqs);
5333 }
fenglub15e72b2015-03-20 11:29:56 -07005334 return true;
5335 }
5336 return false;
5337 }
5338
Felipe Lemeee27cab2016-06-20 16:36:29 -07005339 private boolean isSystem(int uid) {
5340 return uid < Process.FIRST_APPLICATION_UID;
5341 }
fenglub15e72b2015-03-20 11:29:56 -07005342
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005343 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005344 final int uid = Binder.getCallingUid();
5345 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005346 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005347 return;
5348 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005349 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5350 // Policy already enforced.
5351 return;
5352 }
5353 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5354 // If UID is restricted, don't allow them to bring up metered APNs.
5355 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005356 }
5357 }
5358
Robert Greenwalt9258c642014-03-26 16:47:06 -07005359 @Override
5360 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5361 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005362 checkNotNull(operation, "PendingIntent cannot be null.");
5363 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5364 enforceNetworkRequestPermissions(networkCapabilities);
5365 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005366 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005367 ensureSufficientPermissionsForRequest(networkCapabilities,
5368 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005369 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005370 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005371
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005372 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005373 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5374 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005375 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005376 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5377 nri));
5378 return networkRequest;
5379 }
5380
Jeremy Joslin79294842014-12-03 17:15:28 -08005381 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5382 mHandler.sendMessageDelayed(
5383 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5384 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5385 }
5386
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005387 @Override
5388 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005389 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005390 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5391 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005392 }
5393
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005394 // In order to implement the compatibility measure for pre-M apps that call
5395 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5396 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5397 // This ensures it has permission to do so.
5398 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5399 if (nc == null) {
5400 return false;
5401 }
5402 int[] transportTypes = nc.getTransportTypes();
5403 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5404 return false;
5405 }
5406 try {
5407 mContext.enforceCallingOrSelfPermission(
5408 android.Manifest.permission.ACCESS_WIFI_STATE,
5409 "ConnectivityService");
5410 } catch (SecurityException e) {
5411 return false;
5412 }
5413 return true;
5414 }
5415
Robert Greenwalt9258c642014-03-26 16:47:06 -07005416 @Override
5417 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5418 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005419 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5420 enforceAccessPermission();
5421 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005422
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005423 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005424 ensureSufficientPermissionsForRequest(networkCapabilities,
5425 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005426 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005427 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5428 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5429 // onLost and onAvailable callbacks when networks move in and out of the background.
5430 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5431 // can't request networks.
5432 restrictBackgroundRequestForCaller(nc);
lucaslin783f2212019-10-22 18:27:33 +08005433 ensureValid(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005434
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005435 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005436 NetworkRequest.Type.LISTEN);
5437 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005438 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005439
5440 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5441 return networkRequest;
5442 }
5443
5444 @Override
5445 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5446 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005447 checkNotNull(operation, "PendingIntent cannot be null.");
5448 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5449 enforceAccessPermission();
5450 }
lucaslin783f2212019-10-22 18:27:33 +08005451 ensureValid(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005452 ensureSufficientPermissionsForRequest(networkCapabilities,
5453 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005454
Chalard Jeandda156a2018-01-10 21:19:32 +09005455 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005456 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005457
5458 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005459 NetworkRequest.Type.LISTEN);
5460 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005461 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005462
5463 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005464 }
5465
Erik Klineacdd6392016-07-07 16:50:58 +09005466 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005467 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005468 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005469 mHandler.sendMessage(mHandler.obtainMessage(
5470 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005471 }
5472
5473 @Override
Chalard Jean05ab6812018-05-02 21:14:54 +09005474 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005475 enforceConnectivityInternalPermission();
Chalard Jean05ab6812018-05-02 21:14:54 +09005476 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5477 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005478 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean05ab6812018-05-02 21:14:54 +09005479 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005480 }
5481
Robert Greenwalta67be032014-05-16 15:49:14 -07005482 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005483 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005484 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5485 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5486 }
5487
5488 @Override
5489 public void unregisterNetworkFactory(Messenger messenger) {
5490 enforceConnectivityInternalPermission();
5491 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5492 }
5493
5494 private void handleUnregisterNetworkFactory(Messenger messenger) {
5495 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5496 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005497 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005498 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005499 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005500 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005501 }
5502
Paul Jensen31a94f42015-02-13 14:18:39 -05005503 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5504 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005505 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005506 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09005507 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen31a94f42015-02-13 14:18:39 -05005508 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09005509 private final NetIdManager mNetIdManager;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005510
Robert Greenwalt7b816022014-04-18 15:25:25 -07005511 // NetworkAgentInfo keyed off its connecting messenger
5512 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005513 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005514 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005515
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005516 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005517 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005518
Paul Jensen2c311d62014-11-17 12:34:51 -05005519 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Chalard Jean11293a92019-11-05 14:40:23 +09005520 @NonNull
Robert Greenwalt7b816022014-04-18 15:25:25 -07005521 private final NetworkRequest mDefaultRequest;
Chalard Jean11293a92019-11-05 14:40:23 +09005522 // The NetworkAgentInfo currently satisfying the default request, if any.
5523 @Nullable
5524 private volatile NetworkAgentInfo mDefaultNetworkNai = null;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005525
Erik Klineda4bfa82015-04-30 12:58:40 +09005526 // Request used to optionally keep mobile data active even when higher
5527 // priority networks like Wi-Fi are active.
5528 private final NetworkRequest mDefaultMobileDataRequest;
5529
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005530 // Request used to optionally keep wifi data active even when higher
5531 // priority networks like ethernet are active.
5532 private final NetworkRequest mDefaultWifiRequest;
5533
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005534 private NetworkAgentInfo getDefaultNetwork() {
Chalard Jean11293a92019-11-05 14:40:23 +09005535 return mDefaultNetworkNai;
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005536 }
5537
Varun Anand4fa80e82019-02-06 10:13:38 -08005538 @Nullable
5539 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5540 return nai != null ? nai.network : null;
5541 }
5542
5543 private void ensureRunningOnConnectivityServiceThread() {
5544 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5545 throw new IllegalStateException(
5546 "Not running on ConnectivityService thread: "
5547 + Thread.currentThread().getName());
5548 }
5549 }
5550
Chalard Jean612522b2019-04-10 23:07:55 +09005551 @VisibleForTesting
5552 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005553 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005554 }
5555
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005556 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5557 return nri.request.requestId == mDefaultRequest.requestId;
5558 }
5559
Chalard Jean05ab6812018-05-02 21:14:54 +09005560 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5561 // changes that would conflict throughout the automerger graph. Having this method temporarily
5562 // helps with the process of going through with all these dependent changes across the entire
5563 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005564 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005565 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005566 int currentScore, NetworkMisc networkMisc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005567 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5568 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5569 }
5570
5571 /**
5572 * Register a new agent with ConnectivityService to handle a network.
5573 *
5574 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5575 * @param networkInfo the initial info associated with this network. It can be updated later :
5576 * see {@link #updateNetworkInfo}.
5577 * @param linkProperties the initial link properties of this network. They can be updated
5578 * later : see {@link #updateLinkProperties}.
5579 * @param networkCapabilities the initial capabilites of this network. They can be updated
5580 * later : see {@link #updateNetworkCapabilities}.
5581 * @param currentScore the initial score of the network. See
5582 * {@link NetworkAgentInfo#getCurrentScore}.
5583 * @param networkMisc metadata about the network. This is never updated.
5584 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5585 */
5586 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5587 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5588 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005589 enforceConnectivityInternalPermission();
5590
Rubin Xu1bb5c082017-09-05 18:40:49 +01005591 LinkProperties lp = new LinkProperties(linkProperties);
5592 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005593 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5594 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005595 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
lucaslinc2bac512019-11-07 16:47:56 +08005596 final NetworkScore ns = new NetworkScore();
5597 ns.putIntExtension(NetworkScore.LEGACY_SCORE, currentScore);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005598 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09005599 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
lucaslinc2bac512019-11-07 16:47:56 +08005600 ns, mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd,
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09005601 mDnsResolver, mNMS, factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005602 // Make sure the network capabilities reflect what the agent info says.
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005603 nai.setNetworkCapabilities(mixInCapabilities(nai, nc));
Chalard Jeand771aa02018-04-26 16:16:10 +09005604 final String extraInfo = networkInfo.getExtraInfo();
5605 final String name = TextUtils.isEmpty(extraInfo)
5606 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005607 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005608 final long token = Binder.clearCallingIdentity();
5609 try {
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09005610 mDeps.getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005611 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005612 } finally {
5613 Binder.restoreCallingIdentity(token);
5614 }
5615 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5616 // If the network disconnects or sends any other event before that, messages are deferred by
5617 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5618 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005619 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005620 }
5621
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005622 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5623 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005624 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005625 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005626 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005627 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005628 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005629
5630 try {
5631 networkMonitor.start();
5632 } catch (RemoteException e) {
Chiachang Wang79bc7e22019-04-24 21:44:05 +08005633 e.rethrowAsRuntimeException();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005634 }
Erik Klinee5dac902018-03-04 21:01:01 +09005635 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5636 NetworkInfo networkInfo = nai.networkInfo;
Erik Klinee5dac902018-03-04 21:01:01 +09005637 updateNetworkInfo(nai, networkInfo);
5638 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005639 }
5640
lucaslin25a4ec32018-11-28 12:51:55 +08005641 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
Chalard Jeanafdecd52019-09-26 18:03:47 +09005642 @NonNull LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005643 int netId = networkAgent.network.netId;
5644
Lorenzo Colittidf595632019-01-08 14:43:37 +09005645 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5646 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5647 // are accurate.
5648 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005649
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005650 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00005651
5652 // update filtering rules, need to happen after the interface update so netd knows about the
5653 // new interface (the interface name -> index map becomes initialized)
5654 updateVpnFiltering(newLp, oldLp, networkAgent);
5655
Robert Greenwalt7b816022014-04-18 15:25:25 -07005656 updateMtu(newLp, oldLp);
5657 // TODO - figure out what to do for clat
5658// for (LinkProperties lp : newLp.getStackedLinks()) {
5659// updateMtu(lp, null);
5660// }
lucaslin041a1af2018-11-28 19:27:52 +08005661 if (isDefaultNetwork(networkAgent)) {
5662 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5663 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005664
Erik Kline94887872016-04-05 13:30:49 +09005665 updateRoutes(newLp, oldLp, netId);
5666 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005667 // Make sure LinkProperties represents the latest private DNS status.
5668 // This does not need to be done before updateDnses because the
5669 // LinkProperties are not the source of the private DNS configuration.
5670 // updateDnses will fetch the private DNS configuration from DnsManager.
5671 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005672
Paul Jensene0bef712014-12-10 15:12:18 -05005673 if (isDefaultNetwork(networkAgent)) {
5674 handleApplyDefaultProxy(newLp.getHttpProxy());
5675 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005676 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005677 }
Valentin Iftimec86ebba2019-09-24 13:32:13 +02005678
5679 updateWakeOnLan(newLp);
5680
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005681 // TODO - move this check to cover the whole function
5682 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005683 synchronized (networkAgent) {
5684 networkAgent.linkProperties = newLp;
5685 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005686 // Start or stop DNS64 detection and 464xlat according to network state.
5687 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005688 notifyIfacesChangedForNetworkStats();
Lorenzo Colittiac955b32019-05-31 15:41:29 +09005689 networkAgent.networkMonitor().notifyLinkPropertiesChanged(newLp);
lucaslin25a4ec32018-11-28 12:51:55 +08005690 if (networkAgent.everConnected) {
5691 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5692 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005693 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005694
5695 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005696 }
5697
Joel Scherpelz668370b2017-06-08 15:35:21 +09005698 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005699 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005700 // marks on unsupported interfaces is harmless.
5701 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5702 return;
5703 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005704
Joel Scherpelz668370b2017-06-08 15:35:21 +09005705 int mark = mContext.getResources().getInteger(
5706 com.android.internal.R.integer.config_networkWakeupPacketMark);
5707 int mask = mContext.getResources().getInteger(
5708 com.android.internal.R.integer.config_networkWakeupPacketMask);
5709
5710 // Mask/mark of zero will not detect anything interesting.
5711 // Don't install rules unless both values are nonzero.
5712 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005713 return;
5714 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005715
5716 final String prefix = "iface:" + iface;
5717 try {
5718 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005719 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005720 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005721 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005722 }
5723 } catch (Exception e) {
5724 loge("Exception modifying wakeup packet monitoring: " + e);
5725 }
5726
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005727 }
5728
5729 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5730 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005731 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005732 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5733 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005734 for (String iface : interfaceDiff.added) {
5735 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005736 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005737 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005738 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005739 } catch (Exception e) {
5740 loge("Exception adding interface: " + e);
5741 }
5742 }
5743 for (String iface : interfaceDiff.removed) {
5744 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005745 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005746 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005747 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005748 } catch (Exception e) {
5749 loge("Exception removing interface: " + e);
5750 }
5751 }
5752 }
5753
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005754 /**
5755 * Have netd update routes from oldLp to newLp.
5756 * @return true if routes changed between oldLp and newLp
5757 */
5758 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005759 // Compare the route diff to determine which routes should be added and removed.
Chalard Jeanafdecd52019-09-26 18:03:47 +09005760 CompareResult<RouteInfo> routeDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005761 oldLp != null ? oldLp.getAllRoutes() : null,
5762 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005763
5764 // add routes before removing old in case it helps with continuous connectivity
5765
Chalard Jean4d660112018-06-04 16:52:49 +09005766 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005767 for (RouteInfo route : routeDiff.added) {
5768 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005769 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005770 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005771 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005772 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005773 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5774 loge("Exception in addRoute for non-gateway: " + e);
5775 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005776 }
5777 }
5778 for (RouteInfo route : routeDiff.added) {
Chalard Jeanafdecd52019-09-26 18:03:47 +09005779 if (!route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005780 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005781 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005782 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005783 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005784 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5785 loge("Exception in addRoute for gateway: " + e);
5786 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005787 }
5788 }
5789
5790 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005791 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005792 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005793 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005794 } catch (Exception e) {
5795 loge("Exception in removeRoute: " + e);
5796 }
5797 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005798 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005799 }
Erik Kline41368502015-06-17 13:19:54 +09005800
Erik Kline94887872016-04-05 13:30:49 +09005801 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5802 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5803 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005804 }
Erik Kline94887872016-04-05 13:30:49 +09005805
Erik Kline1742fe12017-12-13 19:40:49 +09005806 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5807 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5808
Erik Klinea24d4592018-01-11 21:07:29 +09005809 if (DBG) {
5810 final Collection<InetAddress> dnses = newLp.getDnsServers();
5811 log("Setting DNS servers for network " + netId + " to " + dnses);
5812 }
Erik Kline94887872016-04-05 13:30:49 +09005813 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005814 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005815 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005816 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005817 }
Erik Kline4edba012017-04-07 15:29:29 +09005818 }
5819
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00005820 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
5821 NetworkAgentInfo nai) {
5822 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
5823 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
5824 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
5825 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
5826
5827 if (!wasFiltering && !needsFiltering) {
5828 // Nothing to do.
5829 return;
5830 }
5831
5832 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
5833 // Nothing changed.
5834 return;
5835 }
5836
5837 final Set<UidRange> ranges = nai.networkCapabilities.getUids();
5838 final int vpnAppUid = nai.networkCapabilities.getEstablishingVpnAppUid();
5839 // TODO: this create a window of opportunity for apps to receive traffic between the time
5840 // when the old rules are removed and the time when new rules are added. To fix this,
5841 // make eBPF support two whitelisted interfaces so here new rules can be added before the
5842 // old rules are being removed.
5843 if (wasFiltering) {
5844 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
5845 }
5846 if (needsFiltering) {
5847 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
5848 }
5849 }
5850
Valentin Iftimec86ebba2019-09-24 13:32:13 +02005851 private void updateWakeOnLan(@NonNull LinkProperties lp) {
5852 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
5853 }
5854
Luke Huang8a462ec2018-08-24 20:33:16 +08005855 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005856 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005857 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005858 }
5859 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005860 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005861 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005862 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005863 }
5864
Paul Jensen3d194ea2015-06-16 14:27:36 -04005865 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005866 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5867 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5868 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005869 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005870 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005871 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005872 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5873 // causing a connect/teardown loop.
5874 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5875 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005876 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005877 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005878 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5879 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005880 // does not cause any request (that is not a listen) currently matching that agent to
5881 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005882 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005883 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005884 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005885 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005886 }
5887
Paul Jensen3d194ea2015-06-16 14:27:36 -04005888 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005889 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005890 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005891 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005892 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005893 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005894 }
Paul Jensene0988542015-06-25 15:30:08 -04005895 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005896 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005897 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005898 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005899 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005900 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005901 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005902 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005903 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005904 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005905 if (nai.isSuspended()) {
5906 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5907 } else {
5908 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5909 }
lucasline252a742019-03-12 13:08:03 +08005910 if (nai.partialConnectivity) {
5911 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5912 } else {
5913 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5914 }
lucaslin783f2212019-10-22 18:27:33 +08005915 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005916
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005917 return newNc;
5918 }
5919
5920 /**
5921 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5922 *
5923 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5924 * capabilities we manage and store in {@code nai}, such as validated status and captive
5925 * portal status)
5926 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5927 * potentially triggers rematches.
5928 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5929 * change.)
5930 *
5931 * @param oldScore score of the network before any of the changes that prompted us
5932 * to call this function.
5933 * @param nai the network having its capabilities updated.
5934 * @param nc the new network capabilities.
5935 */
5936 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5937 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5938
5939 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005940
Luke Huang8a462ec2018-08-24 20:33:16 +08005941 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5942 final int newPermission = getNetworkPermission(newNc);
5943 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005944 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005945 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005946 } catch (RemoteException e) {
5947 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005948 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005949 }
5950
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005951 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005952 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005953 prevNc = nai.networkCapabilities;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +09005954 nai.setNetworkCapabilities(newNc);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005955 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005956
Chalard Jeanf213ca12018-01-16 18:43:05 +09005957 updateUids(nai, prevNc, newNc);
5958
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005959 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005960 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5961 // the change we're processing can't affect any requests, it can only affect the listens
5962 // on this network. We might have been called by rematchNetworkAndRequests when a
5963 // network changed foreground state.
5964 processListenRequests(nai, true);
5965 } else {
5966 // If the requestable capabilities have changed or the score changed, we can't have been
5967 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jean1a4548c2019-11-07 18:54:49 +09005968 rematchAllNetworksAndRequests();
Paul Jensene0988542015-06-25 15:30:08 -04005969 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005970 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005971
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005972 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005973 final boolean oldMetered = prevNc.isMetered();
5974 final boolean newMetered = newNc.isMetered();
5975 final boolean meteredChanged = oldMetered != newMetered;
5976
5977 if (meteredChanged) {
5978 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5979 mRestrictBackground);
5980 }
5981
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005982 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005983 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005984
5985 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005986 if (meteredChanged || roamingChanged) {
5987 notifyIfacesChangedForNetworkStats();
5988 }
5989 }
5990
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005991 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005992 // Tell VPNs about updated capabilities, since they may need to
5993 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005994 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005995 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005996 }
5997
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00005998 /**
5999 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
6000 * network.
6001 *
6002 * Ingress interface filtering enforces that all apps under the given network can only receive
6003 * packets from the network's interface (and loopback). This is important for VPNs because
6004 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
6005 * non-VPN interfaces.
6006 *
6007 * As a result, this method should return true iff
6008 * 1. the network is an app VPN (not legacy VPN)
6009 * 2. the VPN does not allow bypass
6010 * 3. the VPN is fully-routed
6011 * 4. the VPN interface is non-null
6012 *
Chalard Jeanafdecd52019-09-26 18:03:47 +09006013 * @see INetd#firewallAddUidInterfaceRules
6014 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00006015 */
6016 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
6017 LinkProperties lp) {
6018 if (nc == null || lp == null) return false;
6019 return nai.isVPN()
6020 && !nai.networkMisc.allowBypass
6021 && nc.getEstablishingVpnAppUid() != Process.SYSTEM_UID
6022 && lp.getInterfaceName() != null
6023 && (lp.hasIPv4DefaultRoute() || lp.hasIPv6DefaultRoute());
6024 }
6025
Chalard Jeanf213ca12018-01-16 18:43:05 +09006026 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
6027 NetworkCapabilities newNc) {
6028 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
6029 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
6030 if (null == prevRanges) prevRanges = new ArraySet<>();
6031 if (null == newRanges) newRanges = new ArraySet<>();
6032 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
6033
6034 prevRanges.removeAll(newRanges);
6035 newRanges.removeAll(prevRangesCopy);
6036
6037 try {
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00006038 // When updating the VPN uid routing rules, add the new range first then remove the old
6039 // range. If old range were removed first, there would be a window between the old
6040 // range being removed and the new range being added, during which UIDs contained
6041 // in both ranges are not subject to any VPN routing rules. Adding new range before
6042 // removing old range works because, unlike the filtering rules below, it's possible to
6043 // add duplicate UID routing rules.
Chalard Jeanf213ca12018-01-16 18:43:05 +09006044 if (!newRanges.isEmpty()) {
6045 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
6046 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08006047 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09006048 }
6049 if (!prevRanges.isEmpty()) {
6050 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
6051 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08006052 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09006053 }
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00006054 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
6055 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
6056 final String iface = nai.linkProperties.getInterfaceName();
6057 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
6058 // be added, due to the range being expanded and stored as invidiual UIDs. For example
6059 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
6060 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
6061 // were added first and then newRanges got removed later, there would be only one uid
6062 // 10013 left. A consequence of removing old ranges before adding new ranges is that
6063 // there is now a window of opportunity when the UIDs are not subject to any filtering.
6064 // Note that this is in contrast with the (more robust) update of VPN routing rules
6065 // above, where the addition of new ranges happens before the removal of old ranges.
6066 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
6067 // to be removed will never overlap with the new range to be added.
6068 if (wasFiltering && !prevRanges.isEmpty()) {
6069 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges,
6070 prevNc.getEstablishingVpnAppUid());
6071 }
6072 if (shouldFilter && !newRanges.isEmpty()) {
6073 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges,
6074 newNc.getEstablishingVpnAppUid());
6075 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09006076 } catch (Exception e) {
6077 // Never crash!
Lorenzo Colitti4c9f9542019-04-12 10:48:06 +00006078 loge("Exception in updateUids: ", e);
Chalard Jeanf213ca12018-01-16 18:43:05 +09006079 }
6080 }
6081
Hugo Benichief502882017-09-01 01:23:32 +00006082 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09006083 ensureRunningOnConnectivityServiceThread();
6084
Erik Kline736353a2018-03-21 07:18:33 -07006085 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00006086 // Ignore updates for disconnected networks
6087 return;
6088 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01006089 // newLp is already a defensive copy.
6090 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006091 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00006092 log("Update of LinkProperties for " + nai.name() +
6093 "; created=" + nai.created +
6094 "; everConnected=" + nai.everConnected);
6095 }
lucaslin25a4ec32018-11-28 12:51:55 +08006096 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00006097 }
6098
Paul Jensenc8b9a742014-09-30 15:37:41 -04006099 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006100 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6101 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04006102 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09006103 if (nr.isListen()) continue;
Chalard Jean05ab6812018-05-02 21:14:54 +09006104 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04006105 }
6106 }
6107
Chalard Jean05ab6812018-05-02 21:14:54 +09006108 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
6109 int score = 0;
6110 int serial = 0;
6111 if (nai != null) {
6112 score = nai.getCurrentScore();
6113 serial = nai.factorySerialNumber;
6114 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006115 if (VDBG || DDBG){
6116 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
6117 }
Robert Greenwalta67be032014-05-16 15:49:14 -07006118 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean05ab6812018-05-02 21:14:54 +09006119 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
6120 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006121 }
6122 }
6123
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006124 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
6125 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08006126 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006127 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08006128 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
6129 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08006130 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006131 sendIntent(nri.mPendingIntent, intent);
6132 }
6133 // else not handled
6134 }
6135
6136 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
6137 mPendingIntentWakeLock.acquire();
6138 try {
6139 if (DBG) log("Sending " + pendingIntent);
6140 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
6141 } catch (PendingIntent.CanceledException e) {
6142 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
6143 mPendingIntentWakeLock.release();
6144 releasePendingNetworkRequest(pendingIntent);
6145 }
6146 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
6147 }
6148
6149 @Override
6150 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
6151 String resultData, Bundle resultExtras) {
6152 if (DBG) log("Finished sending " + pendingIntent);
6153 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08006154 // Release with a delay so the receiving client has an opportunity to put in its
6155 // own request.
6156 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006157 }
6158
Chalard Jeanf19db372018-01-26 19:24:40 +09006159 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006160 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09006161 if (nri.messenger == null) {
6162 return; // Default request has no msgr
6163 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006164 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09006165 // TODO: check if defensive copies of data is needed.
6166 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006167 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09006168 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
6169 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006170 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006171 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09006172 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08006173 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
6174 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09006175 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08006176 // For this notification, arg1 contains the blocked status.
6177 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09006178 break;
6179 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006180 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006181 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006182 break;
6183 }
6184 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09006185 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09006186 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09006187 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09006188 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006189 break;
6190 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006191 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09006192 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07006193 break;
6194 }
junyulai05986c62018-08-07 19:50:45 +08006195 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08006196 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08006197 msg.arg1 = arg1;
6198 break;
6199 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006200 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006201 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07006202 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006203 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07006204 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006205 String notification = ConnectivityManager.getCallbackName(notificationType);
6206 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07006207 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006208 nri.messenger.send(msg);
6209 } catch (RemoteException e) {
6210 // may occur naturally in the race of binder death.
6211 loge("RemoteException caught trying to send a callback msg for " + nri.request);
6212 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006213 }
6214
Hugo Benichidba33db2017-03-23 22:40:44 +09006215 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
6216 bundle.putParcelable(t.getClass().getSimpleName(), t);
6217 }
6218
Paul Jensenc8b9a742014-09-30 15:37:41 -04006219 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006220 if (nai.numRequestNetworkRequests() != 0) {
6221 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6222 NetworkRequest nr = nai.requestAt(i);
6223 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09006224 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006225 loge("Dead network still had at least " + nr);
6226 break;
6227 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04006228 }
6229 nai.asyncChannel.disconnect();
6230 }
6231
Robert Greenwalt7b816022014-04-18 15:25:25 -07006232 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
6233 if (oldNetwork == null) {
6234 loge("Unknown NetworkAgentInfo in handleLingerComplete");
6235 return;
6236 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04006237 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006238
6239 // If we get here it means that the last linger timeout for this network expired. So there
6240 // must be no other active linger timers, and we must stop lingering.
6241 oldNetwork.clearLingerState();
6242
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006243 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006244 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006245 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006246 } else {
6247 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006248 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
6249 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006250 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006251 }
6252
Chalard Jeancf904232019-11-05 15:10:49 +09006253 private void makeDefault(@NonNull final NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07006254 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08006255
Paul Jensen27b02b72014-07-14 12:03:33 -04006256 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08006257 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04006258 } catch (Exception e) {
6259 loge("Exception setting default network :" + e);
6260 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09006261
Chalard Jeancf904232019-11-05 15:10:49 +09006262 mDefaultNetworkNai = newNetwork;
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006263 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04006264 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08006265 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09006266 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09006267 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08006268 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
6269 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04006270 }
6271
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006272 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006273 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
6274 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6275 NetworkRequest nr = nri.request;
6276 if (!nr.isListen()) continue;
6277 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
6278 nai.removeRequest(nri.request.requestId);
6279 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
6280 }
6281 }
6282
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006283 if (capabilitiesChanged) {
6284 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
6285 }
6286
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006287 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6288 NetworkRequest nr = nri.request;
6289 if (!nr.isListen()) continue;
6290 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
6291 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006292 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006293 }
6294 }
6295 }
6296
Chalard Jean1a4548c2019-11-07 18:54:49 +09006297 private ArrayMap<NetworkRequestInfo, NetworkAgentInfo> computeRequestReassignmentForNetwork(
6298 @NonNull final NetworkAgentInfo newNetwork) {
6299 final int score = newNetwork.getCurrentScore();
6300 final ArrayMap<NetworkRequestInfo, NetworkAgentInfo> reassignedRequests = new ArrayMap<>();
6301 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6302 // Process requests in the first pass and listens in the second pass. This allows us to
6303 // change a network's capabilities depending on which requests it has. This is only
6304 // correct if the change in capabilities doesn't affect whether the network satisfies
6305 // requests or not, and doesn't affect the network's score.
6306 if (nri.request.isListen()) continue;
6307
6308 final NetworkAgentInfo currentNetwork = nri.mSatisfier;
6309 final boolean satisfies = newNetwork.satisfies(nri.request);
6310 if (newNetwork == currentNetwork && satisfies) continue;
6311
6312 // check if it satisfies the NetworkCapabilities
6313 if (VDBG) log(" checking if request is satisfied: " + nri.request);
6314 if (satisfies) {
6315 // next check if it's better than any current network we're using for
6316 // this request
6317 if (VDBG || DDBG) {
6318 log("currentScore = "
6319 + (currentNetwork != null ? currentNetwork.getCurrentScore() : 0)
6320 + ", newScore = " + score);
6321 }
6322 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
6323 reassignedRequests.put(nri, newNetwork);
6324 }
6325 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
6326 reassignedRequests.put(nri, null);
6327 }
6328 }
6329 return reassignedRequests;
6330 }
6331
Paul Jensen2161a8e2014-09-11 11:00:39 -04006332 // Handles a network appearing or improving its score.
6333 //
6334 // - Evaluates all current NetworkRequests that can be
6335 // satisfied by newNetwork, and reassigns to newNetwork
6336 // any such requests for which newNetwork is the best.
6337 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006338 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006339 // needed. A network is needed if it is the best network for
6340 // one or more NetworkRequests, or if it is a VPN.
6341 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006342 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006343 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006344 //
Paul Jensen2161a8e2014-09-11 11:00:39 -04006345 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6346 // it does not remove NetworkRequests that other Networks could better satisfy.
6347 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6348 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6349 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006350 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006351 // @param newNetwork is the network to be matched against NetworkRequests.
Chalard Jeanc89c4892019-11-07 19:05:18 +09006352 // @param now the time the rematch starts, as returned by SystemClock.elapsedRealtime();
6353 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, long now) {
Chalard Jean11293a92019-11-05 14:40:23 +09006354 ensureRunningOnConnectivityServiceThread();
Robin Lee585e2482016-05-01 23:00:00 +01006355 if (!newNetwork.everConnected) return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006356 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006357 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006358
6359 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6360 final int score = newNetwork.getCurrentScore();
6361
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006362 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006363
Chalard Jean1a4548c2019-11-07 18:54:49 +09006364 final ArrayMap<NetworkRequestInfo, NetworkAgentInfo> reassignedRequests =
6365 computeRequestReassignmentForNetwork(newNetwork);
Chalard Jean8dcbaa52019-11-07 17:39:53 +09006366
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006367 NetworkCapabilities nc = newNetwork.networkCapabilities;
6368 if (VDBG) log(" network has: " + nc);
Chalard Jean7f014e52019-11-07 17:46:33 +09006369
Chalard Jean578c4202019-11-07 18:32:38 +09006370 // Find and migrate to this Network any NetworkRequests for
6371 // which this network is now the best.
6372 final ArrayList<NetworkAgentInfo> removedRequests = new ArrayList<>();
6373 final ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Chalard Jean7f014e52019-11-07 17:46:33 +09006374 for (final Map.Entry<NetworkRequestInfo, NetworkAgentInfo> entry :
6375 reassignedRequests.entrySet()) {
6376 final NetworkRequestInfo nri = entry.getKey();
6377 final NetworkAgentInfo previousSatisfier = nri.mSatisfier;
Chalard Jeanc6784cc2019-11-07 18:22:23 +09006378 final NetworkAgentInfo newSatisfier = entry.getValue();
Chalard Jeanc9ffb4e2019-11-07 18:24:01 +09006379 if (newSatisfier != null) {
6380 if (VDBG) log("rematch for " + newSatisfier.name());
6381 if (previousSatisfier != null) {
6382 if (VDBG || DDBG) {
6383 log(" accepting network in place of " + previousSatisfier.name());
6384 }
6385 previousSatisfier.removeRequest(nri.request.requestId);
6386 previousSatisfier.lingerRequest(nri.request, now, mLingerDelayMs);
6387 removedRequests.add(previousSatisfier);
6388 } else {
6389 if (VDBG || DDBG) log(" accepting network in place of null");
6390 }
6391 newSatisfier.unlingerRequest(nri.request);
6392 nri.mSatisfier = newSatisfier;
6393 if (!newSatisfier.addRequest(nri.request)) {
6394 Slog.wtf(TAG, "BUG: " + newSatisfier.name() + " already has " + nri.request);
6395 }
6396 addedRequests.add(nri);
Chalard Jeanc9ffb4e2019-11-07 18:24:01 +09006397 // Tell NetworkFactories about the new score, so they can stop
6398 // trying to connect if they know they cannot match it.
6399 // TODO - this could get expensive if we have a lot of requests for this
6400 // network. Think about if there is a way to reduce this. Push
6401 // netid->request mapping to each factory?
6402 sendUpdatedScoreToFactories(nri.request, newSatisfier);
6403 if (isDefaultRequest(nri)) {
6404 isNewDefault = true;
6405 oldDefaultNetwork = previousSatisfier;
6406 if (previousSatisfier != null) {
6407 mLingerMonitor.noteLingerDefaultNetwork(previousSatisfier, newSatisfier);
6408 }
6409 }
6410 } else {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006411 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6412 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006413 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006414 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6415 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6416 // This means this code doesn't have to handle the case where "currentNetwork" no
6417 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6418 if (DBG) {
6419 log("Network " + newNetwork.name() + " stopped satisfying" +
6420 " request " + nri.request.requestId);
6421 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006422 newNetwork.removeRequest(nri.request.requestId);
Chalard Jean7f014e52019-11-07 17:46:33 +09006423 if (previousSatisfier == newNetwork) {
Chalard Jeancf904232019-11-05 15:10:49 +09006424 nri.mSatisfier = null;
6425 if (isDefaultRequest(nri)) mDefaultNetworkNai = null;
Chalard Jean05ab6812018-05-02 21:14:54 +09006426 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006427 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006428 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6429 newNetwork.name() +
Chalard Jeancf904232019-11-05 15:10:49 +09006430 " without updating mSatisfier or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006431 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006432 // TODO: Technically, sending CALLBACK_LOST here is
6433 // incorrect if there is a replacement network currently
6434 // connected that can satisfy nri, which is a request
6435 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006436 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6437 // so this code is only incorrect for a network that loses
6438 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006439 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006440 }
6441 }
Chalard Jean7f014e52019-11-07 17:46:33 +09006442
Paul Jensencf4c2c62015-07-01 14:16:32 -04006443 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006444 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006445 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006446 makeDefault(newNetwork);
6447 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +09006448 mDeps.getMetricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006449 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006450 // Have a new default network, release the transition wakelock in
6451 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006452 }
6453
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006454 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6455 Slog.wtf(TAG, String.format(
6456 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006457 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006458 }
6459 if (newNetwork.getCurrentScore() != score) {
6460 Slog.wtf(TAG, String.format(
6461 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006462 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006463 }
6464
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006465 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006466 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6467 // If the network went from background to foreground or vice versa, we need to update
6468 // its foreground state. It is safe to do this after rematching the requests because
6469 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6470 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006471 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006472 } else {
6473 processListenRequests(newNetwork, false);
6474 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006475
Paul Jensencf4c2c62015-07-01 14:16:32 -04006476 // do this after the default net is switched, but
6477 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006478 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006479
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006480 // Linger any networks that are no longer needed. This should be done after sending the
6481 // available callback for newNetwork.
Chalard Jean8dcbaa52019-11-07 17:39:53 +09006482 for (NetworkAgentInfo nai : removedRequests) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006483 updateLingerState(nai, now);
6484 }
6485 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6486 // does not need to be done in any particular order.
6487 updateLingerState(newNetwork, now);
6488
Paul Jensencf4c2c62015-07-01 14:16:32 -04006489 if (isNewDefault) {
6490 // Maintain the illusion: since the legacy API only
6491 // understands one network at a time, we must pretend
6492 // that the current default network disconnected before
6493 // the new one connected.
6494 if (oldDefaultNetwork != null) {
6495 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6496 oldDefaultNetwork, true);
6497 }
6498 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6499 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6500 notifyLockdownVpn(newNetwork);
6501 }
6502
Chalard Jeand39db872019-11-07 19:16:09 +09006503 if (reassignedRequests.containsValue(newNetwork) || newNetwork.isVPN()) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006504 // Notify battery stats service about this network, both the normal
6505 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006506 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006507 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006508 final IBatteryStats bs = BatteryStatsService.getService();
6509 final int type = newNetwork.networkInfo.getType();
6510
6511 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6512 bs.noteNetworkInterfaceType(baseIface, type);
6513 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6514 final String stackedIface = stacked.getInterfaceName();
6515 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006516 }
6517 } catch (RemoteException ignored) {
6518 }
6519
Robert Greenwalt152ed372014-12-17 17:19:53 -08006520 // This has to happen after the notifyNetworkCallbacks as that tickles each
6521 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006522 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006523 // and will generally do a dns request so they can ensureRouteToHost and if
6524 // they do that before the callbacks happen they'll use the default network.
6525 //
6526 // TODO: Is there still a race here? We send the broadcast
6527 // after sending the callback, but if the app can receive the
6528 // broadcast before the callback, it might still break.
6529 //
6530 // This *does* introduce a race where if the user uses the new api
6531 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6532 // they may get old info. Reverse this after the old startUsing api is removed.
6533 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006534 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6535 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006536 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006537 // legacy type tracker filters out repeat adds
6538 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6539 }
6540 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006541
6542 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6543 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6544 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6545 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6546 if (newNetwork.isVPN()) {
6547 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6548 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006549 }
6550 }
6551
Paul Jensen1c7ba022015-06-16 14:27:36 -04006552 /**
6553 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6554 * being disconnected.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006555 */
Chalard Jean1a4548c2019-11-07 18:54:49 +09006556 private void rematchAllNetworksAndRequests() {
6557 // TODO: This may be slow, and should be optimized. Unfortunately at this moment the
6558 // processing is network-major instead of request-major (the code iterates through all
6559 // networks, then for each it iterates for all requests), which is a problem for re-scoring
6560 // requests. Once the code has switched to a request-major iteration style, this can
6561 // be optimized to only do the processing needed.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006562 final long now = SystemClock.elapsedRealtime();
Chalard Jean1a4548c2019-11-07 18:54:49 +09006563 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6564 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6565 // Rematch higher scoring networks first to prevent requests first matching a lower
6566 // scoring network and then a higher scoring network, which could produce multiple
6567 // callbacks and inadvertently unlinger networks.
6568 Arrays.sort(nais);
6569 for (NetworkAgentInfo nai : nais) {
Chalard Jeanc89c4892019-11-07 19:05:18 +09006570 rematchNetworkAndRequests(nai, now);
6571 }
6572 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6573 if (unneeded(nai, UnneededFor.TEARDOWN)) {
6574 if (nai.getLingerExpiry() > 0) {
6575 // This network has active linger timers and no requests, but is not
6576 // lingering. Linger it.
6577 //
6578 // One way (the only way?) this can happen if this network is unvalidated
6579 // and became unneeded due to another network improving its score to the
6580 // point where this network will no longer be able to satisfy any requests
6581 // even if it validates.
6582 updateLingerState(nai, now);
6583 } else {
6584 if (DBG) log("Reaping " + nai.name());
6585 teardownUnneededNetwork(nai);
6586 }
6587 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04006588 }
6589 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006590
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006591 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006592 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006593 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006594 // For now only update icons for default connection.
6595 // TODO: Update WiFi and cellular icons separately. b/17237507
6596 if (!isDefaultNetwork(nai)) return;
6597
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006598 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006599 // Don't repeat publish.
6600 if (newInetCondition == mDefaultInetConditionPublished) return;
6601
6602 mDefaultInetConditionPublished = newInetCondition;
6603 sendInetConditionBroadcast(nai.networkInfo);
6604 }
6605
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006606 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006607 synchronized (mVpns) {
6608 if (mLockdownTracker != null) {
6609 if (nai != null && nai.isVPN()) {
6610 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6611 } else {
6612 mLockdownTracker.onNetworkInfoChanged();
6613 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006614 }
6615 }
6616 }
6617
Robert Greenwalt7b816022014-04-18 15:25:25 -07006618 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006619 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006620 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006621 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006622 synchronized (networkAgent) {
6623 oldInfo = networkAgent.networkInfo;
6624 networkAgent.networkInfo = newInfo;
6625 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006626 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006627
Robert Greenwalt7b816022014-04-18 15:25:25 -07006628 if (DBG) {
6629 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
Yintang Gu1505d0a2019-06-18 14:24:32 +08006630 oldInfo.getState() + " to " + state);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006631 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006632
Robin Lee585e2482016-05-01 23:00:00 +01006633 if (!networkAgent.created
6634 && (state == NetworkInfo.State.CONNECTED
6635 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006636
6637 // A network that has just connected has zero requests and is thus a foreground network.
6638 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6639
Luke Huanga24d5d82019-04-09 18:41:49 +08006640 if (!createNativeNetwork(networkAgent)) return;
Paul Jenseneec75412014-08-04 12:21:19 -04006641 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006642 }
6643
6644 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6645 networkAgent.everConnected = true;
6646
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006647 if (networkAgent.linkProperties == null) {
6648 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6649 }
6650
lucaslin8175ac992019-04-03 17:09:28 +08006651 // NetworkCapabilities need to be set before sending the private DNS config to
6652 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
6653 synchronized (networkAgent) {
6654 networkAgent.setNetworkCapabilities(networkAgent.networkCapabilities);
6655 }
Erik Kline736353a2018-03-21 07:18:33 -07006656 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006657 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6658 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006659
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006660 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6661 // command must be sent after updating LinkProperties to maximize chances of
6662 // NetworkMonitor seeing the correct LinkProperties when starting.
6663 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiac955b32019-05-31 15:41:29 +09006664 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6665 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006666 }
Lorenzo Colittiac955b32019-05-31 15:41:29 +09006667 networkAgent.networkMonitor().notifyNetworkConnected(
6668 networkAgent.linkProperties, networkAgent.networkCapabilities);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006669 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006670
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006671 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6672 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6673 // capabilities, so it only needs to be done once on initial connect, not every time the
6674 // network's capabilities change. Note that we do this before rematching the network,
6675 // so we could decide to tear it down immediately afterwards. That's fine though - on
6676 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6677 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006678 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006679
Varun Anand4fa80e82019-02-06 10:13:38 -08006680 if (networkAgent.isVPN()) {
6681 updateAllVpnsCapabilities();
6682 }
6683
Paul Jensen2161a8e2014-09-11 11:00:39 -04006684 // Consider network even though it is not yet validated.
Chalard Jean1a4548c2019-11-07 18:54:49 +09006685 rematchAllNetworksAndRequests();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006686
6687 // This has to happen after matching the requests, because callbacks are just requests.
6688 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006689 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006690 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006691 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006692 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006693 }
Chalard Jean392971c2018-05-11 20:19:20 +09006694 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006695 if (networkAgent.isVPN()) {
6696 // As the active or bound network changes for apps, broadcast the default proxy, as
6697 // apps may need to update their proxy data. This is called after disconnecting from
6698 // VPN to make sure we do not broadcast the old proxy data.
6699 // TODO(b/122649188): send the broadcast only to VPN users.
6700 mProxyTracker.sendProxyBroadcast();
6701 }
Yintang Gu1505d0a2019-06-18 14:24:32 +08006702 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
6703 state == NetworkInfo.State.SUSPENDED)) {
Chalard Jean4d660112018-06-04 16:52:49 +09006704 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006705 if (networkAgent.getCurrentScore() != oldScore) {
Chalard Jean1a4548c2019-11-07 18:54:49 +09006706 rematchAllNetworksAndRequests();
Robert Greenwalt8d482522015-06-24 13:23:42 -07006707 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006708 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6709 networkAgent.networkCapabilities);
6710 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6711 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006712 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6713 ConnectivityManager.CALLBACK_SUSPENDED :
6714 ConnectivityManager.CALLBACK_RESUMED));
6715 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006716 }
6717 }
6718
lucaslinc2bac512019-11-07 16:47:56 +08006719 private void updateNetworkScore(NetworkAgentInfo nai, NetworkScore ns) {
Chalard Jean1a4548c2019-11-07 18:54:49 +09006720 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + ns);
lucaslinc2bac512019-11-07 16:47:56 +08006721 nai.setNetworkScore(ns);
Chalard Jean1a4548c2019-11-07 18:54:49 +09006722 rematchAllNetworksAndRequests();
Paul Jensenc8b9a742014-09-30 15:37:41 -04006723 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006724 }
6725
Erik Klinec75d4fa2017-02-15 19:59:17 +09006726 // Notify only this one new request of the current state. Transfer all the
6727 // current state by calling NetworkCapabilities and LinkProperties callbacks
6728 // so that callers can be guaranteed to have as close to atomicity in state
6729 // transfer as can be supported by this current API.
6730 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006731 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006732 if (nri.mPendingIntent != null) {
6733 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6734 // Attempt no subsequent state pushes where intents are involved.
6735 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006736 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006737
junyulai05986c62018-08-07 19:50:45 +08006738 final boolean metered = nai.networkCapabilities.isMetered();
6739 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6740 metered, mRestrictBackground);
6741 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6742 }
6743
6744 /**
6745 * Notify of the blocked state apps with a registered callback matching a given NAI.
6746 *
6747 * Unlike other callbacks, blocked status is different between each individual uid. So for
6748 * any given nai, all requests need to be considered according to the uid who filed it.
6749 *
6750 * @param nai The target NetworkAgentInfo.
6751 * @param oldMetered True if the previous network capabilities is metered.
6752 * @param newRestrictBackground True if data saver is enabled.
6753 */
6754 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6755 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6756
6757 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6758 NetworkRequest nr = nai.requestAt(i);
6759 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6760 final int uidRules = mUidRules.get(nri.mUid);
6761 final boolean oldBlocked, newBlocked;
6762 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6763 // between these two calls.
6764 synchronized (mVpns) {
6765 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6766 oldRestrictBackground);
6767 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6768 newRestrictBackground);
6769 }
6770 if (oldBlocked != newBlocked) {
6771 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6772 encodeBool(newBlocked));
6773 }
6774 }
6775 }
6776
6777 /**
6778 * Notify apps with a given UID of the new blocked state according to new uid rules.
6779 * @param uid The uid for which the rules changed.
6780 * @param newRules The new rules to apply.
6781 */
6782 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6783 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6784 final boolean metered = nai.networkCapabilities.isMetered();
6785 final boolean oldBlocked, newBlocked;
6786 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6787 // rules changed event. And this function actually loop through all connected nai and
6788 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6789 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6790 synchronized (mVpns) {
6791 oldBlocked = isUidNetworkingWithVpnBlocked(
6792 uid, mUidRules.get(uid), metered, mRestrictBackground);
6793 newBlocked = isUidNetworkingWithVpnBlocked(
6794 uid, newRules, metered, mRestrictBackground);
6795 }
6796 if (oldBlocked == newBlocked) {
junyulai26b76642019-04-08 16:58:22 +08006797 continue;
junyulai05986c62018-08-07 19:50:45 +08006798 }
6799 final int arg = encodeBool(newBlocked);
6800 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6801 NetworkRequest nr = nai.requestAt(i);
6802 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6803 if (nri != null && nri.mUid == uid) {
6804 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6805 }
6806 }
6807 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006808 }
6809
Chalard Jean612522b2019-04-10 23:07:55 +09006810 @VisibleForTesting
6811 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006812 // The NetworkInfo we actually send out has no bearing on the real
6813 // state of affairs. For example, if the default connection is mobile,
6814 // and a request for HIPRI has just gone away, we need to pretend that
6815 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6816 // the state to DISCONNECTED, even though the network is of type MOBILE
6817 // and is still connected.
6818 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6819 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006820 if (state != DetailedState.DISCONNECTED) {
6821 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006822 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006823 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006824 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006825 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6826 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6827 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6828 if (info.isFailover()) {
6829 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6830 nai.networkInfo.setFailover(false);
6831 }
6832 if (info.getReason() != null) {
6833 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6834 }
6835 if (info.getExtraInfo() != null) {
6836 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6837 }
6838 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006839 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006840 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006841 if (newDefaultAgent != null) {
6842 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6843 newDefaultAgent.networkInfo);
6844 } else {
6845 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6846 }
6847 }
6848 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6849 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006850 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006851 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006852 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006853 }
6854 }
6855 }
6856
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006857 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006858 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006859 String notification = ConnectivityManager.getCallbackName(notifyType);
6860 log("notifyType " + notification + " for " + networkAgent.name());
6861 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006862 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6863 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006864 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6865 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006866 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6867 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006868 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006869 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006870 } else {
6871 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6872 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006873 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006874 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006875
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006876 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6877 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6878 }
6879
Jeff Sharkey69736342014-12-08 14:50:12 -08006880 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006881 * Returns the list of all interfaces that could be used by network traffic that does not
6882 * explicitly specify a network. This includes the default network, but also all VPNs that are
6883 * currently connected.
6884 *
6885 * Must be called on the handler thread.
6886 */
6887 private Network[] getDefaultNetworks() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006888 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006889 ArrayList<Network> defaultNetworks = new ArrayList<>();
6890 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6891 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6892 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6893 defaultNetworks.add(nai.network);
6894 }
6895 }
6896 return defaultNetworks.toArray(new Network[0]);
6897 }
6898
6899 /**
Lorenzo Colitti4aa87602019-06-24 13:50:45 +09006900 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6901 * active iface's tracked properties has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006902 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006903 private void notifyIfacesChangedForNetworkStats() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006904 ensureRunningOnConnectivityServiceThread();
6905 String activeIface = null;
6906 LinkProperties activeLinkProperties = getActiveLinkProperties();
6907 if (activeLinkProperties != null) {
6908 activeIface = activeLinkProperties.getInterfaceName();
6909 }
Benedict Wong9fbbdeb2019-06-12 17:46:31 +00006910
Lorenzo Colitti4aa87602019-06-24 13:50:45 +09006911 final VpnInfo[] vpnInfos = getAllVpnInfo();
Jeff Sharkey69736342014-12-08 14:50:12 -08006912 try {
Varun Anandd33cbc62019-02-07 14:13:13 -08006913 mStatsService.forceUpdateIfaces(
Lorenzo Colitti4aa87602019-06-24 13:50:45 +09006914 getDefaultNetworks(), getAllNetworkState(), activeIface, vpnInfos);
Jeff Sharkey69736342014-12-08 14:50:12 -08006915 } catch (Exception ignored) {
6916 }
6917 }
6918
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006919 @Override
6920 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006921 int user = UserHandle.getUserId(Binder.getCallingUid());
6922 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006923 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006924 return mVpns.get(user).addAddress(address, prefixLength);
6925 }
6926 }
6927
6928 @Override
6929 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006930 int user = UserHandle.getUserId(Binder.getCallingUid());
6931 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006932 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006933 return mVpns.get(user).removeAddress(address, prefixLength);
6934 }
6935 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006936
6937 @Override
6938 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006939 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006940 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006941 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006942 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006943 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006944 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006945 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006946 mHandler.post(() -> {
6947 // Update VPN's capabilities based on updated underlying network set.
6948 updateAllVpnsCapabilities();
6949 notifyIfacesChangedForNetworkStats();
6950 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006951 }
6952 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006953 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006954
6955 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006956 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006957 enforceConnectivityInternalPermission();
Niklas Lindgrenafc5f9b2018-12-07 11:08:04 +01006958 String settingUrl = mContext.getResources().getString(
6959 R.string.config_networkCaptivePortalServerUrl);
6960
6961 if (!TextUtils.isEmpty(settingUrl)) {
6962 return settingUrl;
6963 }
6964
6965 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
6966 Settings.Global.CAPTIVE_PORTAL_HTTP_URL);
6967 if (!TextUtils.isEmpty(settingUrl)) {
6968 return settingUrl;
6969 }
6970
6971 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainib7c24872016-01-04 12:16:14 -08006972 }
6973
6974 @Override
junyulai7c469172019-01-16 20:23:34 +08006975 public void startNattKeepalive(Network network, int intervalSeconds,
6976 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006977 enforceKeepalivePermission();
6978 mKeepaliveTracker.startNattKeepalive(
junyulai0c666972019-03-04 22:45:36 +08006979 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai7c469172019-01-16 20:23:34 +08006980 intervalSeconds, cb,
junyulai06835112019-01-03 18:50:15 +08006981 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006982 }
6983
6984 @Override
junyulai215b8772019-01-15 11:32:44 +08006985 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006986 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006987 String dstAddr) {
junyulai215b8772019-01-15 11:32:44 +08006988 mKeepaliveTracker.startNattKeepalive(
6989 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006990 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006991 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6992 }
6993
6994 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006995 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006996 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006997 enforceKeepalivePermission();
6998 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006999 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08007000 }
7001
7002 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09007003 public void stopKeepalive(Network network, int slot) {
7004 mHandler.sendMessage(mHandler.obtainMessage(
junyulai06835112019-01-03 18:50:15 +08007005 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09007006 }
7007
7008 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07007009 public void factoryReset() {
7010 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07007011
7012 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
7013 return;
7014 }
7015
Robin Lee3b3dd942015-05-12 18:14:58 +01007016 final int userId = UserHandle.getCallingUserId();
7017
Heemin Seog29ddbd52019-06-12 09:21:44 -07007018 Binder.withCleanCallingIdentity(() -> {
7019 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
7020 ipMemoryStore.factoryReset();
7021 });
Xiao Mad91ec092019-04-10 19:01:52 +09007022
Stuart Scottf1fb3972015-04-02 18:00:02 -07007023 // Turn airplane mode off
7024 setAirplaneMode(false);
7025
Stuart Scotte3e314d2015-04-20 14:07:45 -07007026 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
7027 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09007028 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07007029 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09007030 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07007031 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07007032 }
7033
Stuart Scotte3e314d2015-04-20 14:07:45 -07007034 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01007035 // Remove always-on package
7036 synchronized (mVpns) {
7037 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
7038 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00007039 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01007040 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
7041 }
Victor Changb04a5ea2016-05-30 20:36:30 +01007042
Hugo Benichi69744342017-11-27 10:57:16 +09007043 // Turn Always-on VPN off
7044 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
7045 final long ident = Binder.clearCallingIdentity();
7046 try {
7047 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
7048 mLockdownEnabled = false;
7049 setLockdownTracker(null);
7050 } finally {
7051 Binder.restoreCallingIdentity(ident);
7052 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09007053 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09007054
Hugo Benichi69744342017-11-27 10:57:16 +09007055 // Turn VPN off
7056 VpnConfig vpnConfig = getVpnConfig(userId);
7057 if (vpnConfig != null) {
7058 if (vpnConfig.legacy) {
7059 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
7060 } else {
7061 // Prevent this app (packagename = vpnConfig.user) from initiating
7062 // VPN connections in the future without user intervention.
7063 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07007064
Hugo Benichi69744342017-11-27 10:57:16 +09007065 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
7066 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07007067 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07007068 }
7069 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09007070
Xiao Maed25f9c2019-06-12 16:31:14 +09007071 // restore private DNS settings to default mode (opportunistic)
7072 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_PRIVATE_DNS)) {
7073 Settings.Global.putString(mContext.getContentResolver(),
7074 Settings.Global.PRIVATE_DNS_MODE, PRIVATE_DNS_MODE_OPPORTUNISTIC);
7075 }
7076
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09007077 Settings.Global.putString(mContext.getContentResolver(),
7078 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07007079 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04007080
Ricky Wai44dcbde2018-01-23 04:09:45 +00007081 @Override
7082 public byte[] getNetworkWatchlistConfigHash() {
7083 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
7084 if (nwm == null) {
7085 loge("Unable to get NetworkWatchlistManager");
7086 return null;
7087 }
7088 // Redirect it to network watchlist service to access watchlist file and calculate hash.
7089 return nwm.getWatchlistConfigHash();
7090 }
7091
Hugo Benichicfddd682016-05-31 16:28:06 +09007092 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09007093 int[] transports = nai.networkCapabilities.getTransportTypes();
7094 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09007095 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09007096
7097 private static boolean toBool(int encodedBoolean) {
7098 return encodedBoolean != 0; // Only 0 means false.
7099 }
7100
7101 private static int encodeBool(boolean b) {
7102 return b ? 1 : 0;
7103 }
mswest46386886f2018-03-12 10:34:34 -07007104
7105 @Override
Chalard Jeanafdecd52019-09-26 18:03:47 +09007106 public void onShellCommand(@NonNull FileDescriptor in, @NonNull FileDescriptor out,
7107 FileDescriptor err, @NonNull String[] args, ShellCallback callback,
7108 @NonNull ResultReceiver resultReceiver) {
mswest46386886f2018-03-12 10:34:34 -07007109 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
7110 }
7111
7112 private class ShellCmd extends ShellCommand {
7113
7114 @Override
7115 public int onCommand(String cmd) {
7116 if (cmd == null) {
7117 return handleDefaultCommands(cmd);
7118 }
7119 final PrintWriter pw = getOutPrintWriter();
7120 try {
7121 switch (cmd) {
7122 case "airplane-mode":
7123 final String action = getNextArg();
7124 if ("enable".equals(action)) {
7125 setAirplaneMode(true);
7126 return 0;
7127 } else if ("disable".equals(action)) {
7128 setAirplaneMode(false);
7129 return 0;
7130 } else if (action == null) {
7131 final ContentResolver cr = mContext.getContentResolver();
7132 final int enabled = Settings.Global.getInt(cr,
7133 Settings.Global.AIRPLANE_MODE_ON);
7134 pw.println(enabled == 0 ? "disabled" : "enabled");
7135 return 0;
7136 } else {
7137 onHelp();
7138 return -1;
7139 }
7140 default:
7141 return handleDefaultCommands(cmd);
7142 }
7143 } catch (Exception e) {
7144 pw.println(e);
7145 }
7146 return -1;
7147 }
7148
7149 @Override
7150 public void onHelp() {
7151 PrintWriter pw = getOutPrintWriter();
7152 pw.println("Connectivity service commands:");
7153 pw.println(" help");
7154 pw.println(" Print this help text.");
7155 pw.println(" airplane-mode [enable|disable]");
7156 pw.println(" Turn airplane mode on or off.");
7157 pw.println(" airplane-mode");
7158 pw.println(" Get airplane mode.");
7159 }
7160 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007161
Pavel Grafovcb3b8952018-12-14 13:51:07 +00007162 @GuardedBy("mVpns")
7163 private Vpn getVpnIfOwner() {
7164 final int uid = Binder.getCallingUid();
7165 final int user = UserHandle.getUserId(uid);
7166
7167 final Vpn vpn = mVpns.get(user);
7168 if (vpn == null) {
7169 return null;
7170 } else {
7171 final VpnInfo info = vpn.getVpnInfo();
7172 return (info == null || info.ownerUid != uid) ? null : vpn;
7173 }
7174 }
7175
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007176 /**
7177 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
7178 * for testing.
7179 */
7180 private Vpn enforceActiveVpnOrNetworkStackPermission() {
7181 if (checkNetworkStackPermission()) {
7182 return null;
7183 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007184 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00007185 Vpn vpn = getVpnIfOwner();
7186 if (vpn != null) {
7187 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07007188 }
7189 }
7190 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
7191 + "permission");
7192 }
7193
7194 /**
7195 * @param connectionInfo the connection to resolve.
7196 * @return {@code uid} if the connection is found and the app has permission to observe it
7197 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
7198 * connection is not found.
7199 */
7200 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
7201 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
7202 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
7203 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
7204 }
7205
7206 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
7207 connectionInfo.local, connectionInfo.remote);
7208
7209 /* Filter out Uids not associated with the VPN. */
7210 if (vpn != null && !vpn.appliesToUid(uid)) {
7211 return INVALID_UID;
7212 }
7213
7214 return uid;
7215 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00007216
7217 @Override
7218 public boolean isCallerCurrentAlwaysOnVpnApp() {
7219 synchronized (mVpns) {
7220 Vpn vpn = getVpnIfOwner();
7221 return vpn != null && vpn.getAlwaysOn();
7222 }
7223 }
7224
7225 @Override
7226 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
7227 synchronized (mVpns) {
7228 Vpn vpn = getVpnIfOwner();
7229 return vpn != null && vpn.getLockdown();
7230 }
7231 }
Benedict Wonga341fbc2018-11-09 14:45:34 -08007232
7233 /**
7234 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
7235 *
7236 * <p>The TestNetworkService must be run in the system server due to TUN creation.
7237 */
7238 @Override
7239 public IBinder startOrGetTestNetworkService() {
7240 synchronized (mTNSLock) {
7241 TestNetworkService.enforceTestNetworkPermissions(mContext);
7242
7243 if (mTNS == null) {
7244 mTNS = new TestNetworkService(mContext, mNMS);
7245 }
7246
7247 return mTNS;
7248 }
7249 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07007250}