blob: 3ed294845d9763a16bdc1705b47f7a057ee736e7 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
lucasline252a742019-03-12 13:08:03 +080028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090029import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040030import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090032import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
34import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
lucasline252a742019-03-12 13:08:03 +080038import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090039import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060040import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080041import static android.net.NetworkPolicyManager.RULE_NONE;
42import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090043import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090044import static android.net.shared.NetworkParcelableUtil.toStableParcelable;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070045import static android.os.Process.INVALID_UID;
46import static android.system.OsConstants.IPPROTO_TCP;
47import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060048
Hugo Benichia0385682017-03-22 17:07:57 +090049import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060050
Wenchao Tongf5ea3402015-03-04 13:26:38 -080051import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080052import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090053import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070054import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070055import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ContentResolver;
57import android.content.Context;
58import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070059import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070060import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070061import android.database.ContentObserver;
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +090062import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070063import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.ConnectivityManager;
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +090065import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050067import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080068import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050069import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070070import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090071import android.net.INetworkMonitor;
72import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070073import android.net.INetworkPolicyListener;
74import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070075import android.net.INetworkStatsService;
markchien6ea34542019-02-27 14:56:11 +080076import android.net.ITetheringEventCallback;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090077import android.net.InetAddresses;
78import android.net.IpPrefix;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080079import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070080import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010081import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080082import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070083import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070084import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070085import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070086import android.net.NetworkConfig;
Chalard Jean08577fc2018-05-02 21:14:54 +090087import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070089import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070090import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090091import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070092import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070093import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070094import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090095import android.net.NetworkStack;
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +090096import android.net.NetworkStackClient;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070097import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070098import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000099import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900100import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -0400101import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -0700102import android.net.RouteInfo;
junyulaie4135282019-01-03 18:50:15 +0800103import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -0400105import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600106import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900107import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900108import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700109import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900110import android.net.shared.NetworkMonitorUtils;
111import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900112import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900113import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800115import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700116import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700118import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700120import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.os.Looper;
122import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700123import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700124import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900125import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700126import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700127import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700128import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800129import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900130import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900131import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700132import android.os.ShellCallback;
133import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900134import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700135import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400136import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700138import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700139import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700140import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900142import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700143import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600144import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900145import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800146import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700147import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500148import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700149import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Wink Savilleab9321d2013-06-29 21:10:57 -0700152import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400153import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400154import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700155import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANd4a9de202019-01-30 22:01:20 +0900156import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700157import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700158import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800159import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700160import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900161import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700162import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600163import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700164import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900165import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900166import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700167import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700168import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400169import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900170import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500171import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900172import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900173import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100174import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700175import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900176import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700177import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600178import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900179import com.android.server.connectivity.NetworkNotificationManager;
180import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700181import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900182import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800183import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700184import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100185import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500186import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700187import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700188import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900189import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700190import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600191
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700192import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700193
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700194import org.xmlpull.v1.XmlPullParser;
195import org.xmlpull.v1.XmlPullParserException;
196
197import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700199import java.io.FileNotFoundException;
200import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700201import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700203import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700204import java.net.InetAddress;
205import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700206import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700207import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700208import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900209import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800210import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700211import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700212import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700214import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700215import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900216import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600217import java.util.SortedSet;
218import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
220/**
221 * @hide
222 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800223public class ConnectivityService extends IConnectivityManager.Stub
224 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900225 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Chalard Jean4133a122018-06-04 13:33:12 +0900227 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900228 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900229 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900230 private static final String NETWORK_ARG = "networks";
231 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900232
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900233 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900234 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
235 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900237 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700238
Jeff Sharkey899223b2012-08-04 15:24:58 -0700239 // TODO: create better separation between radio types and network types
240
Robert Greenwalt42acef32009-08-12 16:08:25 -0700241 // how long to wait before switching back to a radio's default network
242 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
243 // system property that can override the above value
244 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
245 "android.telephony.apn-restore";
246
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900247 // How long to wait before putting up a "This network doesn't have an Internet connection,
248 // connect anyway?" dialog after the user selects a network that doesn't validate.
249 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
250
lucaslind2e045e02019-01-24 15:55:30 +0800251 // How long to dismiss network notification.
252 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
253
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900254 // Default to 30s linger time-out. Modifiable only for testing.
255 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
256 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
257 @VisibleForTesting
258 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
259
Jeremy Joslin79294842014-12-03 17:15:28 -0800260 // How long to delay to removal of a pending intent based request.
261 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
262 private final int mReleasePendingIntentDelayMs;
263
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900264 private MockableSystemProperties mSystemProperties;
265
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800266 private Tethering mTethering;
267
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700268 private final PermissionMonitor mPermissionMonitor;
269
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700270 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700271
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900272 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700273 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900274 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700275
Hugo Benichi69744342017-11-27 10:57:16 +0900276 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
277 // a direct call to LockdownVpnTracker.isEnabled().
278 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700279 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900280 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700281 private LockdownVpnTracker mLockdownTracker;
282
junyulai05986c62018-08-07 19:50:45 +0800283 /**
284 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
285 * handler thread, they don't need a lock.
286 */
287 private SparseIntArray mUidRules = new SparseIntArray();
288 /** Flag indicating if background data is restricted. */
289 private boolean mRestrictBackground;
290
Erik Klineda4bfa82015-04-30 12:58:40 +0900291 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700292 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700293 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Luke Huang4e25ec62018-09-27 16:58:23 +0800295 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800296 @VisibleForTesting
297 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800298 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700299 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900300 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700301
Benedict Wong99a48412018-11-09 14:45:34 -0800302 /**
303 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
304 * instances.
305 */
306 @GuardedBy("mTNSLock")
307 private TestNetworkService mTNS;
308
309 private final Object mTNSLock = new Object();
310
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700311 private String mCurrentTcpBufferSizes;
312
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900313 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900314 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
315 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900316
Paul Jensenb10e37f2014-11-25 12:33:08 -0500317 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400318 // Tear down networks that have no chance (e.g. even if validated) of becoming
319 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500320 // all networks have been rematched against all NetworkRequests.
321 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400322 // Don't reap networks. This should be passed when some networks have not yet been
323 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500324 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900325 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500326
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900327 private enum UnneededFor {
328 LINGER, // Determine whether this network is unneeded and should be lingered.
329 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
330 }
331
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700332 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700333 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700334 * from one net to another. Clear happens when we get a new
335 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
336 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700337 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700338 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700339
Robert Greenwalt434203a2010-10-11 16:00:27 -0700340 /**
341 * used internally to reload global proxy settings
342 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700343 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700344
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700345 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400346 * PAC manager has received new port.
347 */
348 private static final int EVENT_PROXY_HAS_CHANGED = 16;
349
Robert Greenwalte049c232014-04-11 15:53:27 -0700350 /**
351 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700352 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700353 */
354 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
355
Robert Greenwalt7b816022014-04-18 15:25:25 -0700356 /**
357 * used internally when registering NetworkAgents
358 * obj = Messenger
359 */
360 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
361
Robert Greenwalt9258c642014-03-26 16:47:06 -0700362 /**
363 * used to add a network request
364 * includes a NetworkRequestInfo
365 */
366 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
367
368 /**
369 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900370 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700371 * cancel it.
372 * includes a NetworkRequestInfo
373 */
374 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
375
376 /**
377 * used to add a network listener - no request
378 * includes a NetworkRequestInfo
379 */
380 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
381
382 /**
383 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400384 * arg1 = UID of caller
385 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700386 */
387 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
388
Robert Greenwalta67be032014-05-16 15:49:14 -0700389 /**
390 * used internally when registering NetworkFactories
391 * obj = Messenger
392 */
393 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
394
Robert Greenwalt27711812014-06-25 16:45:57 -0700395 /**
396 * used internally to expire a wakelock when transitioning
397 * from one net to another. Expire happens when we fail to find
398 * a new network (typically after 1 minute) -
399 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
400 * a replacement network.
401 */
402 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
403
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700404 /**
405 * Used internally to indicate the system is ready.
406 */
407 private static final int EVENT_SYSTEM_READY = 25;
408
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800409 /**
410 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400411 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800412 */
413 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
414
415 /**
416 * used to remove a pending intent and its associated network request.
417 * arg1 = UID of caller
418 * obj = PendingIntent
419 */
420 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
421
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900422 /**
423 * used to specify whether a network should be used even if unvalidated.
424 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
425 * arg2 = whether to remember this choice in the future (1 or 0)
426 * obj = network
427 */
428 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
429
430 /**
431 * used to ask the user to confirm a connection to an unvalidated network.
432 * obj = network
433 */
434 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700435
Erik Klineda4bfa82015-04-30 12:58:40 +0900436 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700437 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900438 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700439 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900440
Paul Jensen694f2b82015-06-17 14:15:39 -0400441 /**
442 * used to add a network listener with a pending intent
443 * obj = NetworkRequestInfo
444 */
445 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
446
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900447 /**
448 * used to specify whether a network should not be penalized when it becomes unvalidated.
449 */
450 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
451
452 /**
453 * used to trigger revalidation of a network.
454 */
455 private static final int EVENT_REVALIDATE_NETWORK = 36;
456
Erik Klinea24d4592018-01-11 21:07:29 +0900457 // Handle changes in Private DNS settings.
458 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
459
dalyk7301aa42018-03-05 12:42:22 -0500460 // Handle private DNS validation status updates.
461 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
462
junyulai05986c62018-08-07 19:50:45 +0800463 /**
464 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
465 */
466 private static final int EVENT_UID_RULES_CHANGED = 39;
467
468 /**
469 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
470 */
471 private static final int EVENT_DATA_SAVER_CHANGED = 40;
472
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900473 /**
474 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
475 * been tested.
476 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
477 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
478 * arg2 = NetID.
479 */
480 public static final int EVENT_NETWORK_TESTED = 41;
481
482 /**
483 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
484 * config was resolved.
485 * obj = PrivateDnsConfig
486 * arg2 = netid
487 */
488 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
489
490 /**
491 * Request ConnectivityService display provisioning notification.
492 * arg1 = Whether to make the notification visible.
493 * arg2 = NetID.
494 * obj = Intent to be launched when notification selected by user, null if !arg1.
495 */
496 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
497
498 /**
lucaslind2e045e02019-01-24 15:55:30 +0800499 * This event can handle dismissing notification by given network id.
500 */
501 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
502
503 /**
lucasline252a742019-03-12 13:08:03 +0800504 * Used to specify whether a network should be used even if connectivity is partial.
505 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
506 * false)
507 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
508 * obj = network
509 */
510 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
511
512 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900513 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
514 * should be shown.
515 */
516 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
517
518 /**
519 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
520 * should be hidden.
521 */
522 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
523
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900524 private static String eventName(int what) {
525 return sMagicDecoderRing.get(what, Integer.toString(what));
526 }
527
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900528 /** Handler thread used for both of the handlers below. */
529 @VisibleForTesting
530 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700531 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700532 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700533 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700534 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900535 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700536
Mike Lockwood0f79b542009-08-14 14:18:49 -0400537 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800538 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400539
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700540 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700541 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800542 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700543
Chalard Jean52c2aa72018-06-07 16:44:04 +0900544 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
545 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000546 @VisibleForTesting
547 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400548
Erik Klineda4bfa82015-04-30 12:58:40 +0900549 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700550
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400551 private UserManager mUserManager;
552
Chalard Jean4133a122018-06-04 13:33:12 +0900553 private NetworkConfig[] mNetConfigs;
554 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700555
Robert Greenwalt50393202011-06-21 17:26:14 -0700556 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900557 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700558
Chalard Jean4133a122018-06-04 13:33:12 +0900559 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400560
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900561 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900562 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900563 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900564
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700565 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800566 private static final int MIN_NET_ID = 100; // some reserved marks
567 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700568 private int mNextNetId = MIN_NET_ID;
569
Robert Greenwalt34524f02014-05-18 16:22:10 -0700570 // sequence number of NetworkRequests
571 private int mNextNetworkRequestId = 1;
572
Erik Kline7523eb32015-07-09 18:24:03 +0900573 // NetworkRequest activity String log entries.
574 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
575 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
576
Hugo Benichic2ae2872016-07-11 11:05:12 +0900577 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900578 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900579 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
580
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900581 private static final int MAX_WAKELOCK_LOGS = 20;
582 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900583 private int mTotalWakelockAcquisitions = 0;
584 private int mTotalWakelockReleases = 0;
585 private long mTotalWakelockDurationMs = 0;
586 private long mMaxWakelockDurationMs = 0;
587 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900588
Hugo Benichif9fdf872016-07-28 17:53:06 +0900589 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900590
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700591 @GuardedBy("mBandwidthRequests")
592 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
593
Erik Kline065ab6e2016-10-02 18:02:14 +0900594 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900595 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900596
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900597 @VisibleForTesting
598 final MultipathPolicyTracker mMultipathPolicyTracker;
599
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700600 /**
601 * Implements support for the legacy "one network per network type" model.
602 *
603 * We used to have a static array of NetworkStateTrackers, one for each
604 * network type, but that doesn't work any more now that we can have,
605 * for example, more that one wifi network. This class stores all the
606 * NetworkAgentInfo objects that support a given type, but the legacy
607 * API will only see the first one.
608 *
609 * It serves two main purposes:
610 *
611 * 1. Provide information about "the network for a given type" (since this
612 * API only supports one).
613 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
614 * the first network for a given type changes, or if the default network
615 * changes.
616 */
617 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900619 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900620 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900621
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700622 /**
623 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
624 * Each list holds references to all NetworkAgentInfos that are used to
625 * satisfy requests for that network type.
626 *
627 * This array is built out at startup such that an unsupported network
628 * doesn't get an ArrayList instance, making this a tristate:
629 * unsupported, supported but not active and active.
630 *
631 * The actual lists are populated when we scan the network types that
632 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900633 *
634 * Threading model:
635 * - addSupportedType() is only called in the constructor
636 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
637 * They are therefore not thread-safe with respect to each other.
638 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
639 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
640 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900642 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700643
644 public LegacyTypeTracker() {
645 mTypeLists = (ArrayList<NetworkAgentInfo>[])
646 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
647 }
648
649 public void addSupportedType(int type) {
650 if (mTypeLists[type] != null) {
651 throw new IllegalStateException(
652 "legacy list for type " + type + "already initialized");
653 }
Chalard Jean4133a122018-06-04 13:33:12 +0900654 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 }
656
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700657 public boolean isTypeSupported(int type) {
658 return isNetworkTypeValid(type) && mTypeLists[type] != null;
659 }
660
661 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900662 synchronized (mTypeLists) {
663 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
664 return mTypeLists[type].get(0);
665 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700666 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900667 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700668 }
669
Robert Greenwalt8d482522015-06-24 13:23:42 -0700670 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900671 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900672 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700673 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900674 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900675 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 }
677 }
678
679 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700680 public void add(int type, NetworkAgentInfo nai) {
681 if (!isTypeSupported(type)) {
682 return; // Invalid network type.
683 }
684 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
685
686 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
687 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700688 return;
689 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900690 synchronized (mTypeLists) {
691 list.add(nai);
692 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900693
694 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900695 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900696 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700697 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
698 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700699 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700700 }
701
Lorenzo Colittia793a672014-07-31 23:20:17 +0900702 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900703 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900704 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
705 if (list == null || list.isEmpty()) {
706 return;
707 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900708 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900709
Hugo Benichi78caa2582016-06-21 09:48:07 +0900710 synchronized (mTypeLists) {
711 if (!list.remove(nai)) {
712 return;
713 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900714 }
715
Robert Greenwalt8d482522015-06-24 13:23:42 -0700716 final DetailedState state = DetailedState.DISCONNECTED;
717
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900718 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700719 maybeLogBroadcast(nai, state, type, wasDefault);
720 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900721 }
722
723 if (!list.isEmpty() && wasFirstNetwork) {
724 if (DBG) log("Other network available for type " + type +
725 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900726 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700727 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
728 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900729 }
730 }
731
732 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900733 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
734 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700735 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900736 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700737 }
738 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700739
Robert Greenwalt8d482522015-06-24 13:23:42 -0700740 // send out another legacy broadcast - currently only used for suspend/unsuspend
741 // toggle
742 public void update(NetworkAgentInfo nai) {
743 final boolean isDefault = isDefaultNetwork(nai);
744 final DetailedState state = nai.networkInfo.getDetailedState();
745 for (int type = 0; type < mTypeLists.length; type++) {
746 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700747 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900748 final boolean isFirst = contains && (nai == list.get(0));
749 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700750 maybeLogBroadcast(nai, state, type, isDefault);
751 sendLegacyNetworkBroadcast(nai, state, type);
752 }
753 }
754 }
755
Lorenzo Colittia793a672014-07-31 23:20:17 +0900756 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900757 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900758 String state = (nai.networkInfo != null) ?
759 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
760 "???/???";
761 return name + " " + state;
762 }
763
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700764 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900765 pw.println("mLegacyTypeTracker:");
766 pw.increaseIndent();
767 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700768 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900769 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700770 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900771 pw.println();
772 pw.println("Current state:");
773 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900774 synchronized (mTypeLists) {
775 for (int type = 0; type < mTypeLists.length; type++) {
776 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
777 for (NetworkAgentInfo nai : mTypeLists[type]) {
778 pw.println(type + " " + naiToString(nai));
779 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900780 }
781 }
782 pw.decreaseIndent();
783 pw.decreaseIndent();
784 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700785 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700786 }
787 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
788
Vishnu Nair5c010902017-10-26 10:08:50 -0700789 /**
790 * Helper class which parses out priority arguments and dumps sections according to their
791 * priority. If priority arguments are omitted, function calls the legacy dump command.
792 */
793 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
794 @Override
795 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
796 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
797 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
798 }
799
800 @Override
801 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
802 doDump(fd, pw, args, asProto);
803 }
804
805 @Override
806 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
807 doDump(fd, pw, args, asProto);
808 }
809 };
810
Jeff Sharkey899223b2012-08-04 15:24:58 -0700811 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700812 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900813 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
814 }
815
816 @VisibleForTesting
817 protected ConnectivityService(Context context, INetworkManagementService netManager,
818 INetworkStatsService statsService, INetworkPolicyManager policyManager,
819 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800820 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800821
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900822 mSystemProperties = getSystemProperties();
823
Hugo Benichif9fdf872016-07-28 17:53:06 +0900824 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900825 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900826 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900827 mNetworkRequests.put(mDefaultRequest, defaultNRI);
828 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900829
Chalard Jeandda156a2018-01-10 21:19:32 +0900830 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900831 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700832
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700833 // The default WiFi request is a background request so that apps using WiFi are
834 // migrated to a better network (typically ethernet) when one comes up, instead
835 // of staying on WiFi forever.
836 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
837 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
838
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900839 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900840 mHandlerThread.start();
841 mHandler = new InternalHandler(mHandlerThread.getLooper());
842 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700843
Jeremy Joslin79294842014-12-03 17:15:28 -0800844 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
845 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
846
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900847 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900848
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700849 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800850 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800851 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700852 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900853 mPolicyManagerInternal = checkNotNull(
854 LocalServices.getService(NetworkPolicyManagerInternal.class),
855 "missing NetworkPolicyManagerInternal");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000856 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900857
Luke Huang674660f2018-09-27 19:33:11 +0800858 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700859 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700860 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700861
junyulai05986c62018-08-07 19:50:45 +0800862 // To ensure uid rules are synchronized with Network Policy, register for
863 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
864 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700865 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900866 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700867 } catch (RemoteException e) {
868 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700869 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700870 }
871
872 final PowerManager powerManager = (PowerManager) context.getSystemService(
873 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700874 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
875 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
876 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800877 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700878
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700879 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700880
Wink Saville51f456f2013-04-23 14:26:51 -0700881 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900882 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700883 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700884 String[] naStrings = context.getResources().getStringArray(
885 com.android.internal.R.array.networkAttributes);
886 for (String naString : naStrings) {
887 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700888 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700889 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700890 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800891 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700892 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700893 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700894 }
Wink Saville51f456f2013-04-23 14:26:51 -0700895 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
896 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
897 n.type);
898 continue;
899 }
Wink Saville975c8482011-04-07 14:23:45 -0700900 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800901 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700902 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700903 continue;
904 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700905 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700906
Wink Saville975c8482011-04-07 14:23:45 -0700907 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700908 mNetworksDefined++;
909 } catch(Exception e) {
910 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700911 }
912 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700913
914 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
915 if (mNetConfigs[TYPE_VPN] == null) {
916 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
917 // don't need to add TYPE_VPN to mNetConfigs.
918 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
919 mNetworksDefined++; // used only in the log() statement below.
920 }
921
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900922 // Do the same for Ethernet, since it's often not specified in the configs, although many
923 // devices can use it via USB host adapters.
924 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
925 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
926 mNetworksDefined++;
927 }
928
Wink Saville5e56bc52013-07-29 15:00:57 -0700929 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700930
Robert Greenwalt50393202011-06-21 17:26:14 -0700931 mProtectedNetworks = new ArrayList<Integer>();
932 int[] protectedNetworks = context.getResources().getIntArray(
933 com.android.internal.R.array.config_protectedNetworks);
934 for (int p : protectedNetworks) {
935 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
936 mProtectedNetworks.add(p);
937 } else {
938 if (DBG) loge("Ignoring protectedNetwork " + p);
939 }
940 }
941
Erik Kline47222fc2017-04-30 19:36:15 +0900942 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800943
Luke Huang4e25ec62018-09-27 16:58:23 +0800944 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700945
Varun Anand4fa80e82019-02-06 10:13:38 -0800946 // Set up the listener for user state for creating user VPNs.
947 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700948 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100949 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700950 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700951 intentFilter.addAction(Intent.ACTION_USER_ADDED);
952 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000953 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700954 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800955 mIntentReceiver,
956 UserHandle.ALL,
957 intentFilter,
958 null /* broadcastPermission */,
959 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000960 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
961 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900962
junyulai2454b692018-11-01 17:16:31 +0800963 // Listen to package add and removal events for all users.
964 intentFilter = new IntentFilter();
965 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800966 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800967 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
968 intentFilter.addDataScheme("package");
969 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800970 mIntentReceiver,
971 UserHandle.ALL,
972 intentFilter,
973 null /* broadcastPermission */,
974 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800975
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700976 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800977 mNMS.registerObserver(mTethering);
978 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700979 } catch (RemoteException e) {
980 loge("Error registering observer :" + e);
981 }
982
Erik Klineda4bfa82015-04-30 12:58:40 +0900983 mSettingsObserver = new SettingsObserver(mContext, mHandler);
984 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800985
Chalard Jean4133a122018-06-04 13:33:12 +0900986 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
987 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400988
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400989 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900990
991 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900992 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
993 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900994
995 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
996 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
997 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
998 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
999 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1000 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1001 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09001002
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001003 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +09001004 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001005 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +09001006
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001007 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1008
Luke Huang4e25ec62018-09-27 16:58:23 +08001009 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001010 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001012
Mike Yuf9729752018-08-17 15:22:05 +08001013 @VisibleForTesting
1014 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001015 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001016 final TetheringDependencies deps = new TetheringDependencies() {
1017 @Override
1018 public boolean isTetheringSupported() {
1019 return ConnectivityService.this.isTetheringSupported();
1020 }
Erik Kline72302902018-06-14 17:36:40 +09001021 @Override
1022 public NetworkRequest getDefaultNetworkRequest() {
1023 return mDefaultRequest;
1024 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001025 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001026 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001027 IoThread.get().getLooper(), new MockableSystemProperties(),
1028 deps);
1029 }
1030
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001031 @VisibleForTesting
1032 protected ProxyTracker makeProxyTracker() {
1033 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1034 }
1035
Chalard Jean26400492018-04-18 20:18:38 +09001036 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1037 final NetworkCapabilities netCap = new NetworkCapabilities();
1038 netCap.addCapability(NET_CAPABILITY_INTERNET);
1039 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1040 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1041 netCap.setSingleUid(uid);
1042 return netCap;
1043 }
1044
Chalard Jeandda156a2018-01-10 21:19:32 +09001045 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001046 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001047 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001048 netCap.addCapability(NET_CAPABILITY_INTERNET);
1049 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001050 if (transportType > -1) {
1051 netCap.addTransportType(transportType);
1052 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001053 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001054 }
1055
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001056 // Used only for testing.
1057 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001058 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001059 // changing ContentResolver to make registerContentObserver non-final).
1060 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1061 // by subclassing SettingsObserver.
1062 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001063 void updateAlwaysOnNetworks() {
1064 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001065 }
1066
Erik Kline736353a2018-03-21 07:18:33 -07001067 // See FakeSettingsProvider comment above.
1068 @VisibleForTesting
1069 void updatePrivateDnsSettings() {
1070 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1071 }
1072
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001073 private void handleAlwaysOnNetworkRequest(
1074 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001075 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001076 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1077 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001078 if (enable == isEnabled) {
1079 return; // Nothing to do.
1080 }
1081
1082 if (enable) {
1083 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001084 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001085 } else {
Etan Cohenae574a82019-01-08 12:09:18 -08001086 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1087 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001088 }
1089 }
1090
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001091 private void handleConfigureAlwaysOnNetworks() {
1092 handleAlwaysOnNetworkRequest(
1093 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1094 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1095 false);
1096 }
1097
Erik Klineda4bfa82015-04-30 12:58:40 +09001098 private void registerSettingsCallbacks() {
1099 // Watch for global HTTP proxy changes.
1100 mSettingsObserver.observe(
1101 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1102 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1103
1104 // Watch for whether or not to keep mobile data always on.
1105 mSettingsObserver.observe(
1106 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001107 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1108
1109 // Watch for whether or not to keep wifi always on.
1110 mSettingsObserver.observe(
1111 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1112 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001113 }
1114
Erik Klinea24d4592018-01-11 21:07:29 +09001115 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001116 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1117 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001118 }
1119 }
1120
Robert Greenwalt34524f02014-05-18 16:22:10 -07001121 private synchronized int nextNetworkRequestId() {
1122 return mNextNetworkRequestId++;
1123 }
1124
Paul Jensen67b0b072015-06-10 11:22:17 -04001125 @VisibleForTesting
1126 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001127 synchronized (mNetworkForNetId) {
1128 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1129 int netId = mNextNetId;
1130 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1131 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001132 if (!mNetIdInUse.get(netId)) {
1133 mNetIdInUse.put(netId, true);
1134 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001135 }
1136 }
1137 }
1138 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001139 }
1140
Chalard Jeanc0982912018-06-07 16:11:34 +09001141 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001142 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1144 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001145 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001146 state = nai.getNetworkState();
1147 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001148 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001149 final NetworkInfo info = new NetworkInfo(networkType, 0,
1150 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001151 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1152 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001153 final NetworkCapabilities capabilities = new NetworkCapabilities();
1154 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1155 !info.isRoaming());
1156 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001157 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001159 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 return state;
1161 } else {
1162 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001163 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001164 }
1165
junyulai4a192e22018-06-13 15:00:37 +08001166 @VisibleForTesting
1167 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 if (network == null) {
1169 return null;
1170 }
Erik Kline736353a2018-03-21 07:18:33 -07001171 return getNetworkAgentInfoForNetId(network.netId);
1172 }
1173
1174 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001176 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001180 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001181 synchronized (mVpns) {
1182 if (!mLockdownEnabled) {
1183 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001184 Vpn vpn = mVpns.get(user);
1185 if (vpn != null && vpn.appliesToUid(uid)) {
1186 return vpn.getUnderlyingNetworks();
1187 }
1188 }
1189 }
1190 return null;
1191 }
1192
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001194 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001195
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001196 final Network[] networks = getVpnUnderlyingNetworks(uid);
1197 if (networks != null) {
1198 // getUnderlyingNetworks() returns:
1199 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1200 // empty array => the VPN explicitly said "no default network".
1201 // non-empty array => the VPN specified one or more default networks; we use the
1202 // first one.
1203 if (networks.length > 0) {
1204 nai = getNetworkAgentInfoForNetwork(networks[0]);
1205 } else {
1206 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001207 }
1208 }
1209
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001211 return nai.getNetworkState();
1212 } else {
1213 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001215 }
1216
1217 /**
1218 * Check if UID should be blocked from using the network with the given LinkProperties.
1219 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001220 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1221 boolean ignoreBlocked) {
1222 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001223 if (ignoreBlocked) {
1224 return false;
1225 }
Robin Lee17e61832016-05-09 13:46:28 +01001226 synchronized (mVpns) {
1227 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001228 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001229 return true;
1230 }
1231 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001232 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001233 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001234 }
1235
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001236 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001237 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1238 return;
1239 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001240 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001241 synchronized (mBlockedAppUids) {
1242 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001243 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001244 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001245 blocked = false;
1246 } else {
1247 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001248 }
1249 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001250 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1251 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1252 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001253 }
1254
junyulai05986c62018-08-07 19:50:45 +08001255 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1256 boolean blocked) {
1257 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1258 return;
1259 }
1260 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1261 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1262 nri.mUid, nri.request.requestId, net.netId));
1263 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1264 }
1265
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001266 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001267 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1268 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001269 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001270 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001271 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001272 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1273
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001274 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001275 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001276 }
Hugo Benichi69744342017-11-27 10:57:16 +09001277 synchronized (mVpns) {
1278 if (mLockdownTracker != null) {
1279 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1280 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001281 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001282 }
1283
1284 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 * Return NetworkInfo for the active (i.e., connected) network interface.
1286 * It is assumed that at most one network is active at a time. If more
1287 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001288 * @return the info for the active network, or {@code null} if none is
1289 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001291 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001293 enforceAccessPermission();
1294 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001295 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001296 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001297 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1298 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300
Paul Jensen31a94f42015-02-13 14:18:39 -05001301 @Override
1302 public Network getActiveNetwork() {
1303 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001304 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001305 }
1306
1307 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001308 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001309 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001310 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001311 }
1312
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001313 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001314 final int user = UserHandle.getUserId(uid);
1315 int vpnNetId = NETID_UNSET;
1316 synchronized (mVpns) {
1317 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001318 // TODO : now that capabilities contain the UID, the appliesToUid test should
1319 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001320 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1321 }
1322 NetworkAgentInfo nai;
1323 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001324 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001325 if (nai != null) {
1326 final NetworkCapabilities requiredCaps =
1327 createDefaultNetworkCapabilitiesForUid(uid);
1328 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1329 return nai.network;
1330 }
1331 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001332 }
1333 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001334 if (nai != null
1335 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1336 nai = null;
1337 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001338 return nai != null ? nai.network : null;
1339 }
1340
Lorenzo Colitti18660282016-07-04 12:55:44 +09001341 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001342 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1343 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001344 final int uid = Binder.getCallingUid();
1345 NetworkState state = getUnfilteredActiveNetworkState(uid);
1346 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001347 }
1348
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001349 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001350 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001351 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001352 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001353 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001354 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 }
1356
1357 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 public NetworkInfo getNetworkInfo(int networkType) {
1359 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001361 if (getVpnUnderlyingNetworks(uid) != null) {
1362 // A VPN is active, so we may need to return one of its underlying networks. This
1363 // information is not available in LegacyTypeTracker, so we have to get it from
1364 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001365 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001366 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001367 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001368 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001369 }
1370 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001371 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001372 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001375 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001376 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001377 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001378 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001379 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001380 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001381 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001382 return state.networkInfo;
1383 } else {
1384 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001385 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001386 }
1387
1388 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 public NetworkInfo[] getAllNetworkInfo() {
1390 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001391 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001392 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1393 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001394 NetworkInfo info = getNetworkInfo(networkType);
1395 if (info != null) {
1396 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001399 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001402 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001403 public Network getNetworkForType(int networkType) {
1404 enforceAccessPermission();
1405 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001406 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001407 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001408 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001409 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001410 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001411 }
1412
1413 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001414 public Network[] getAllNetworks() {
1415 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001416 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001417 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001418 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001419 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001420 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001421 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001422 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001423 }
1424
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001425 @Override
1426 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1427 // The basic principle is: if an app's traffic could possibly go over a
1428 // network, without the app doing anything multinetwork-specific,
1429 // (hence, by "default"), then include that network's capabilities in
1430 // the array.
1431 //
1432 // In the normal case, app traffic only goes over the system's default
1433 // network connection, so that's the only network returned.
1434 //
1435 // With a VPN in force, some app traffic may go into the VPN, and thus
1436 // over whatever underlying networks the VPN specifies, while other app
1437 // traffic may go over the system default network (e.g.: a split-tunnel
1438 // VPN, or an app disallowed by the VPN), so the set of networks
1439 // returned includes the VPN's underlying networks and the system
1440 // default.
1441 enforceAccessPermission();
1442
Chalard Jean4133a122018-06-04 13:33:12 +09001443 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001444
1445 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001446 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001447 if (nc != null) {
1448 result.put(nai.network, nc);
1449 }
1450
Hugo Benichi69744342017-11-27 10:57:16 +09001451 synchronized (mVpns) {
1452 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001453 Vpn vpn = mVpns.get(userId);
1454 if (vpn != null) {
1455 Network[] networks = vpn.getUnderlyingNetworks();
1456 if (networks != null) {
1457 for (Network network : networks) {
1458 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001459 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001460 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001461 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001462 }
1463 }
1464 }
1465 }
1466 }
1467 }
1468
1469 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1470 out = result.values().toArray(out);
1471 return out;
1472 }
1473
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001474 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001475 public boolean isNetworkSupported(int networkType) {
1476 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001477 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001478 }
1479
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001480 /**
1481 * Return LinkProperties for the active (i.e., connected) default
1482 * network interface. It is assumed that at most one default network
1483 * is active at a time. If more than one is active, it is indeterminate
1484 * which will be returned.
1485 * @return the ip properties for the active network, or {@code null} if
1486 * none is active
1487 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001488 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001489 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001490 enforceAccessPermission();
1491 final int uid = Binder.getCallingUid();
1492 NetworkState state = getUnfilteredActiveNetworkState(uid);
1493 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001494 }
1495
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001497 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001498 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001499 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1500 if (nai != null) {
1501 synchronized (nai) {
1502 return new LinkProperties(nai.linkProperties);
1503 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001504 }
1505 return null;
1506 }
1507
Robert Greenwalt12e67352014-05-13 21:41:06 -07001508 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001509 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001510 public LinkProperties getLinkProperties(Network network) {
1511 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001512 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1513 }
1514
1515 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1516 if (nai == null) {
1517 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001518 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001519 synchronized (nai) {
1520 return new LinkProperties(nai.linkProperties);
1521 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001522 }
1523
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001524 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001525 if (nai != null) {
1526 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001527 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001528 return networkCapabilitiesRestrictedForCallerPermissions(
1529 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001530 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001531 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001532 }
1533 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001534 return null;
1535 }
1536
1537 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001538 public NetworkCapabilities getNetworkCapabilities(Network network) {
1539 enforceAccessPermission();
1540 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1541 }
1542
Chalard Jeanb03a6222018-04-11 21:09:10 +09001543 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001544 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001545 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001546 if (!checkSettingsPermission(callerPid, callerUid)) {
1547 newNc.setUids(null);
1548 newNc.setSSID(null);
1549 }
Etan Cohen836ad572018-12-30 17:59:59 -08001550 if (newNc.getNetworkSpecifier() != null) {
1551 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1552 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001553 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001554 }
1555
Chalard Jeanb552c462018-02-21 18:43:54 +09001556 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1557 if (!checkSettingsPermission()) {
1558 nc.setSingleUid(Binder.getCallingUid());
1559 }
1560 }
1561
Chalard Jean26aa91a2018-03-20 19:13:57 +09001562 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1563 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1564 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1565 }
1566 }
1567
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001568 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001569 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001570 // Require internal since we're handing out IMSI details
1571 enforceConnectivityInternalPermission();
1572
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001573 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001574 for (Network network : getAllNetworks()) {
1575 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1576 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001577 // TODO (b/73321673) : NetworkState contains a copy of the
1578 // NetworkCapabilities, which may contain UIDs of apps to which the
1579 // network applies. Should the UIDs be cleared so as not to leak or
1580 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001581 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001582 }
1583 }
1584 return result.toArray(new NetworkState[result.size()]);
1585 }
1586
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001587 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001588 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001589 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001590 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1591 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1592 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001593 }
1594
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001595 @Override
1596 public boolean isActiveNetworkMetered() {
1597 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001598
Varun Anandc51b06d2019-02-25 17:22:02 -08001599 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001600 if (caps != null) {
1601 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1602 } else {
1603 // Always return the most conservative value
1604 return true;
1605 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001606 }
1607
Jeff Sharkey216c1812012-08-05 14:29:23 -07001608 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1609 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001610 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001611 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001612 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001613 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001614 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001615
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001616 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001617 * Ensures that the system cannot call a particular method.
1618 */
1619 private boolean disallowedBecauseSystemCaller() {
1620 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1621 // requestRouteToHost.
1622 if (isSystem(Binder.getCallingUid())) {
1623 log("This method exists only for app backwards compatibility"
1624 + " and must not be called by system services.");
1625 return true;
1626 }
1627 return false;
1628 }
1629
1630 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 * Ensure that a network route exists to deliver traffic to the specified
1632 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001633 * @param networkType the type of the network over which traffic to the
1634 * specified host is to be routed
1635 * @param hostAddress the IP address of the host to which the route is
1636 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 * @return {@code true} on success, {@code false} on failure
1638 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001639 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001640 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001641 if (disallowedBecauseSystemCaller()) {
1642 return false;
1643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001645 if (mProtectedNetworks.contains(networkType)) {
1646 enforceConnectivityInternalPermission();
1647 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001648
Chad Brubakerc0234532014-02-14 13:24:29 -08001649 InetAddress addr;
1650 try {
1651 addr = InetAddress.getByAddress(hostAddress);
1652 } catch (UnknownHostException e) {
1653 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1654 return false;
1655 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001658 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 return false;
1660 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001661
1662 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1663 if (nai == null) {
1664 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1665 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1666 } else {
1667 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1668 }
1669 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001670 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001671
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001672 DetailedState netState;
1673 synchronized (nai) {
1674 netState = nai.networkInfo.getDetailedState();
1675 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001676
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001677 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001678 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001679 log("requestRouteToHostAddress on down network "
1680 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001681 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001682 }
1683 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001685
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001686 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001687 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001688 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001689 LinkProperties lp;
1690 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001691 synchronized (nai) {
1692 lp = nai.linkProperties;
1693 netId = nai.network.netId;
1694 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001695 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001696 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1697 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001698 } finally {
1699 Binder.restoreCallingIdentity(token);
1700 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001701 }
1702
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001703 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001704 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001705 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001706 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001707 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001708 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001709 if (bestRoute.getGateway().equals(addr)) {
1710 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001711 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001712 } else {
1713 // if we will connect to this through another route, add a direct route
1714 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001715 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001716 }
1717 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001718 if (DBG) log("Adding legacy route " + bestRoute +
1719 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001720 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001721 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001722 } catch (Exception e) {
1723 // never crash - catch them all
1724 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001725 return false;
1726 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001727 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729
dalyk7301aa42018-03-05 12:42:22 -05001730 @VisibleForTesting
1731 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1732 @Override
1733 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1734 String hostname, boolean validated) {
1735 try {
1736 mHandler.sendMessage(mHandler.obtainMessage(
1737 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1738 new PrivateDnsValidationUpdate(netId,
1739 InetAddress.parseNumericAddress(ipAddress),
1740 hostname, validated)));
1741 } catch (IllegalArgumentException e) {
1742 loge("Error parsing ip address in validation event");
1743 }
1744 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001745
1746 @Override
1747 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1748 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1749 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1750 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1751 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1752 // event callback for certain nai. e.g. cellular. Register here to pass to
1753 // NetworkMonitor instead.
1754 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1755 // registerNetworkAgent to have NetworkMonitor created with system process as design
1756 // expectation. Also, NetdEventListenerService only allow one callback from each
1757 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1758 // NetworkMonitor registrants.
1759 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001760 try {
1761 nai.networkMonitor().notifyDnsResponse(returnCode);
1762 } catch (RemoteException e) {
1763 e.rethrowFromSystemServer();
1764 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001765 }
1766 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001767
1768 @Override
1769 public void onNat64PrefixEvent(int netId, boolean added,
1770 String prefixString, int prefixLength) {
1771 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1772 }
dalyk7301aa42018-03-05 12:42:22 -05001773 };
1774
1775 @VisibleForTesting
1776 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001777 final IIpConnectivityMetrics ipConnectivityMetrics =
1778 IIpConnectivityMetrics.Stub.asInterface(
1779 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1780 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001781 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001782 return;
dalyk7301aa42018-03-05 12:42:22 -05001783 }
1784
1785 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001786 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001787 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1788 mNetdEventCallback);
1789 } catch (Exception e) {
1790 loge("Error registering netd callback: " + e);
1791 }
1792 }
1793
Jeff Sharkey75d31892018-01-18 22:01:59 +09001794 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001795 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001796 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001797 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001798 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001799 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001800 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001801 // caller is NPMS, since we only register with them
1802 if (LOGD_BLOCKED_NETWORKINFO) {
1803 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1804 }
1805 mHandler.sendMessage(mHandler.obtainMessage(
1806 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1807
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001808 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001809 if (restrictBackground) {
1810 log("onRestrictBackgroundChanged(true): disabling tethering");
1811 mTethering.untetherAll();
1812 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001813 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001814 };
1815
junyulai05986c62018-08-07 19:50:45 +08001816 void handleUidRulesChanged(int uid, int newRules) {
1817 // skip update when we've already applied rules
1818 final int oldRules = mUidRules.get(uid, RULE_NONE);
1819 if (oldRules == newRules) return;
1820
1821 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1822
1823 if (newRules == RULE_NONE) {
1824 mUidRules.delete(uid);
1825 } else {
1826 mUidRules.put(uid, newRules);
1827 }
1828 }
1829
1830 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1831 if (mRestrictBackground == restrictBackground) return;
1832
1833 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1834 final boolean curMetered = nai.networkCapabilities.isMetered();
1835 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1836 restrictBackground);
1837 }
1838
1839 mRestrictBackground = restrictBackground;
1840 }
1841
1842 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1843 boolean isBackgroundRestricted) {
1844 synchronized (mVpns) {
1845 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1846 // Because the return value of this function depends on the list of UIDs the
1847 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1848 // list all state depending on the return value of this function has to be recomputed.
1849 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1850 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001851 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001852 return true;
1853 }
1854 }
1855
1856 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1857 isNetworkMetered, isBackgroundRestricted);
1858 }
1859
Robin Lee3b3dd942015-05-12 18:14:58 +01001860 /**
1861 * Require that the caller is either in the same user or has appropriate permission to interact
1862 * across users.
1863 *
1864 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1865 */
1866 private void enforceCrossUserPermission(int userId) {
1867 if (userId == UserHandle.getCallingUserId()) {
1868 // Not a cross-user call.
1869 return;
1870 }
1871 mContext.enforceCallingOrSelfPermission(
1872 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1873 "ConnectivityService");
1874 }
1875
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001876 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001877 for (String permission : permissions) {
1878 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001879 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001880 }
1881 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001882 return false;
1883 }
1884
1885 private void enforceAnyPermissionOf(String... permissions) {
1886 if (!checkAnyPermissionOf(permissions)) {
1887 throw new SecurityException("Requires one of the following permissions: "
1888 + String.join(", ", permissions) + ".");
1889 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001890 }
1891
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001892 private void enforceInternetPermission() {
1893 mContext.enforceCallingOrSelfPermission(
1894 android.Manifest.permission.INTERNET,
1895 "ConnectivityService");
1896 }
1897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001899 mContext.enforceCallingOrSelfPermission(
1900 android.Manifest.permission.ACCESS_NETWORK_STATE,
1901 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
1904 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001905 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907
Charles He36738632017-05-15 17:07:18 +01001908 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001909 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001910 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001911 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001912 }
1913
Chalard Jeanb552c462018-02-21 18:43:54 +09001914 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001915 return checkAnyPermissionOf(
1916 android.Manifest.permission.NETWORK_SETTINGS,
1917 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001918 }
1919
1920 private boolean checkSettingsPermission(int pid, int uid) {
1921 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001922 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1923 || PERMISSION_GRANTED == mContext.checkPermission(
1924 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001925 }
1926
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001927 private void enforceTetherAccessPermission() {
1928 mContext.enforceCallingOrSelfPermission(
1929 android.Manifest.permission.ACCESS_NETWORK_STATE,
1930 "ConnectivityService");
1931 }
1932
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001933 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001934 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001935 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001936 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001937 }
1938
Pavel Grafova462bcb2019-01-25 08:50:06 +00001939 private void enforceControlAlwaysOnVpnPermission() {
1940 mContext.enforceCallingOrSelfPermission(
1941 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1942 "ConnectivityService");
1943 }
1944
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001945 private void enforceNetworkStackSettingsOrSetup() {
1946 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001947 android.Manifest.permission.NETWORK_SETTINGS,
1948 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001949 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001950 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001951 }
1952
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001953 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001954 return checkAnyPermissionOf(
1955 android.Manifest.permission.NETWORK_STACK,
1956 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001957 }
1958
Hugo Benichi514da602016-07-19 15:59:27 +09001959 private void enforceConnectivityRestrictedNetworksPermission() {
1960 try {
1961 mContext.enforceCallingOrSelfPermission(
1962 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1963 "ConnectivityService");
1964 return;
1965 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1966 enforceConnectivityInternalPermission();
1967 }
1968
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001969 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001970 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001971 }
1972
Lorenzo Colitti18660282016-07-04 12:55:44 +09001973 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001974 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001975 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001976 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001977 }
1978
1979 private void sendInetConditionBroadcast(NetworkInfo info) {
1980 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1981 }
1982
Wink Saville628b0852011-08-04 15:01:58 -07001983 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001984 synchronized (mVpns) {
1985 if (mLockdownTracker != null) {
1986 info = new NetworkInfo(info);
1987 mLockdownTracker.augmentNetworkInfo(info);
1988 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001989 }
1990
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001991 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001992 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001993 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 if (info.isFailover()) {
1995 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1996 info.setFailover(false);
1997 }
1998 if (info.getReason() != null) {
1999 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2000 }
2001 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002002 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2003 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002005 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002006 return intent;
2007 }
2008
2009 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2010 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2011 }
2012
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002013 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002014 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2015 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2016 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002017 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002018 final long ident = Binder.clearCallingIdentity();
2019 try {
2020 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2021 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002025 }
2026
Mike Lockwood0f79b542009-08-14 14:18:49 -04002027 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002028 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002029 if (!mSystemReady
2030 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002031 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002032 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002033 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002034 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002035 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002036 }
2037
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002038 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002039 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002040 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002041 final NetworkInfo ni = intent.getParcelableExtra(
2042 ConnectivityManager.EXTRA_NETWORK_INFO);
2043 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2044 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2045 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002046 } else {
2047 BroadcastOptions opts = BroadcastOptions.makeBasic();
2048 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2049 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002050 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002051 final IBatteryStats bs = BatteryStatsService.getService();
2052 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002053 bs.noteConnectivityChanged(intent.getIntExtra(
2054 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002055 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002056 } catch (RemoteException e) {
2057 }
Chad Brubakerac925012018-03-08 10:37:09 -08002058 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002059 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002060 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002061 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002062 } finally {
2063 Binder.restoreCallingIdentity(ident);
2064 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002065 }
2066 }
2067
2068 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002069 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002070 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002071 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002072
Hugo Benichi20035e02017-04-26 14:53:28 +09002073 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002074 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002075 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002076 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002077 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002078 }
2079 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002080
Robin Lee244ce8e2016-01-05 18:03:46 +00002081 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2082 // for user to unlock device too.
2083 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002084
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002085 // Create network requests for always-on networks.
2086 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002087
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002088 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002089
2090 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002094 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002095 *
2096 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002097 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002098 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2100 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002101
2102 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002104
Robert Greenwalt7b816022014-04-18 15:25:25 -07002105 if (networkAgent.networkCapabilities.hasTransport(
2106 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002107 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2108 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002109 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002110 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 } else if (networkAgent.networkCapabilities.hasTransport(
2112 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002113 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2114 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002115 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002117 } else {
2118 // do not track any other networks
2119 timeout = 0;
2120 }
2121
Robert Greenwalt7b816022014-04-18 15:25:25 -07002122 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002123 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002124 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002125 } catch (Exception e) {
2126 // You shall not crash!
2127 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002128 }
2129 }
2130 }
2131
2132 /**
2133 * Remove data activity tracking when network disconnects.
2134 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2136 final String iface = networkAgent.linkProperties.getInterfaceName();
2137 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002138
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2140 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002141 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002142 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002143 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002144 } catch (Exception e) {
2145 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002146 }
2147 }
2148 }
2149
2150 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002151 * Update data activity tracking when network state is updated.
2152 */
2153 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2154 NetworkAgentInfo oldNetwork) {
2155 if (newNetwork != null) {
2156 setupDataActivityTracking(newNetwork);
2157 }
2158 if (oldNetwork != null) {
2159 removeDataActivityTracking(oldNetwork);
2160 }
2161 }
2162 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002163 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002164 * and set it on it's iface.
2165 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2167 final String iface = newLp.getInterfaceName();
2168 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002169 if (oldLp == null && mtu == 0) {
2170 // Silently ignore unset MTU value.
2171 return;
2172 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2174 if (VDBG) log("identical MTU - not setting");
2175 return;
2176 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002177 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002178 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 return;
2180 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002181
w1997615afd812014-08-05 15:18:11 -07002182 // Cannot set MTU without interface name
2183 if (TextUtils.isEmpty(iface)) {
2184 loge("Setting MTU size with null iface.");
2185 return;
2186 }
2187
Robert Greenwalt7b816022014-04-18 15:25:25 -07002188 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002189 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002190 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002191 } catch (Exception e) {
2192 Slog.e(TAG, "exception in setMtu()" + e);
2193 }
2194 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002195
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002196 @VisibleForTesting
2197 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002198 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2199
2200 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002201 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002202 protected MockableSystemProperties getSystemProperties() {
2203 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002204 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002205
lucaslin041a1af2018-11-28 19:27:52 +08002206 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002207 String[] values = null;
2208 if (tcpBufferSizes != null) {
2209 values = tcpBufferSizes.split(",");
2210 }
2211
2212 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002213 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002214 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2215 values = tcpBufferSizes.split(",");
2216 }
2217
2218 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2219
2220 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002221 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002222
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002223 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2224 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2225 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002226 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002227 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002228 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002229 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002230
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002231 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002232 Settings.Global.TCP_DEFAULT_INIT_RWND,
2233 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002234 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2235 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002236 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002237 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002238 }
2239
Robert Greenwalt562cc542014-05-15 18:07:26 -07002240 @Override
2241 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002242 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002243 NETWORK_RESTORE_DELAY_PROP_NAME);
2244 if(restoreDefaultNetworkDelayStr != null &&
2245 restoreDefaultNetworkDelayStr.length() != 0) {
2246 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002247 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002248 } catch (NumberFormatException e) {
2249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002251 // if the system property isn't set, use the value for the apn type
2252 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2253
2254 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2255 (mNetConfigs[networkType] != null)) {
2256 ret = mNetConfigs[networkType].restoreTime;
2257 }
2258 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 }
2260
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002261 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2262 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2263 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002264 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002265 // Start gathering diagnostic information.
2266 netDiags.add(new NetworkDiagnostics(
2267 nai.network,
2268 new LinkProperties(nai.linkProperties), // Must be a copy.
2269 DIAG_TIME_MS));
2270 }
2271
2272 for (NetworkDiagnostics netDiag : netDiags) {
2273 pw.println();
2274 netDiag.waitForMeasurements();
2275 netDiag.dump(pw);
2276 }
2277 }
2278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002280 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002281 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2282 }
2283
2284 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002285 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002286 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002287 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002288
Erik Kline3f8306b2018-05-01 16:51:44 +09002289 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002290 dumpNetworkDiagnostics(pw);
2291 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002292 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002293 mTethering.dump(fd, pw, args);
2294 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002295 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2296 dumpNetworks(pw);
2297 return;
2298 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2299 dumpNetworkRequests(pw);
2300 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002301 }
Erik Kline379747a2015-06-05 17:47:34 +09002302
Lorenzo Colittie3805462015-06-03 11:18:24 +09002303 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002304 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002305 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002306 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002307 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002308 pw.println();
2309
Paul Jensen85cf78e2015-06-25 13:25:07 -04002310 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002311 pw.print("Active default network: ");
2312 if (defaultNai == null) {
2313 pw.println("none");
2314 } else {
2315 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002317 pw.println();
2318
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002319 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002320 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002321 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002322 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002323 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002324
junyulai05986c62018-08-07 19:50:45 +08002325 pw.print("Restrict background: ");
2326 pw.println(mRestrictBackground);
2327 pw.println();
2328
2329 pw.println("Status for known UIDs:");
2330 pw.increaseIndent();
2331 final int size = mUidRules.size();
2332 for (int i = 0; i < size; i++) {
2333 // Don't crash if the array is modified while dumping in bugreports.
2334 try {
2335 final int uid = mUidRules.keyAt(i);
2336 final int uidRules = mUidRules.get(uid, RULE_NONE);
2337 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2338 } catch (ArrayIndexOutOfBoundsException e) {
2339 pw.println(" ArrayIndexOutOfBoundsException");
2340 } catch (ConcurrentModificationException e) {
2341 pw.println(" ConcurrentModificationException");
2342 }
2343 }
2344 pw.println();
2345 pw.decreaseIndent();
2346
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002347 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002348 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002349 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002350 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002351 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002352
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002353 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002354
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002355 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002356 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002357
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002358 pw.println();
2359 mKeepaliveTracker.dump(pw);
2360
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002361 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002362 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002363
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002364 pw.println();
2365 mMultipathPolicyTracker.dump(pw);
2366
Erik Kline3f8306b2018-05-01 16:51:44 +09002367 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002368 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002369 pw.println("mNetworkRequestInfoLogs (most recent first):");
2370 pw.increaseIndent();
2371 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2372 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002373
2374 pw.println();
2375 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2376 pw.increaseIndent();
2377 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2378 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002379
2380 pw.println();
2381 pw.println("NetTransition WakeLock activity (most recent first):");
2382 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002383 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2384 pw.println("total releases: " + mTotalWakelockReleases);
2385 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2386 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2387 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2388 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2389 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2390 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002391 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002392
2393 pw.println();
2394 pw.println("bandwidth update requests (by uid):");
2395 pw.increaseIndent();
2396 synchronized (mBandwidthRequests) {
2397 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2398 pw.println("[" + mBandwidthRequests.keyAt(i)
2399 + "]: " + mBandwidthRequests.valueAt(i));
2400 }
2401 }
2402 pw.decreaseIndent();
2403
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002404 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002405 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002406
2407 pw.println();
2408 pw.println("NetworkStackClient logs:");
2409 pw.increaseIndent();
2410 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 }
2412
Hugo Benichi14683812018-09-03 08:32:56 +09002413 private void dumpNetworks(IndentingPrintWriter pw) {
2414 for (NetworkAgentInfo nai : networksSortedById()) {
2415 pw.println(nai.toString());
2416 pw.increaseIndent();
2417 pw.println(String.format(
2418 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2419 nai.numForegroundNetworkRequests(),
2420 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2421 nai.numBackgroundNetworkRequests(),
2422 nai.numNetworkRequests()));
2423 pw.increaseIndent();
2424 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2425 pw.println(nai.requestAt(i).toString());
2426 }
2427 pw.decreaseIndent();
2428 pw.println("Lingered:");
2429 pw.increaseIndent();
2430 nai.dumpLingerTimers(pw);
2431 pw.decreaseIndent();
2432 pw.decreaseIndent();
2433 }
2434 }
2435
2436 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2437 for (NetworkRequestInfo nri : requestsSortedById()) {
2438 pw.println(nri.toString());
2439 }
2440 }
2441
Hugo Benichia2a917c2018-09-03 08:19:02 +09002442 /**
2443 * Return an array of all current NetworkAgentInfos sorted by network id.
2444 */
2445 private NetworkAgentInfo[] networksSortedById() {
2446 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2447 networks = mNetworkAgentInfos.values().toArray(networks);
2448 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2449 return networks;
2450 }
2451
2452 /**
2453 * Return an array of all current NetworkRequest sorted by request id.
2454 */
2455 private NetworkRequestInfo[] requestsSortedById() {
2456 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2457 requests = mNetworkRequests.values().toArray(requests);
2458 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2459 return requests;
2460 }
2461
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002462 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002463 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002464 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002465 if (officialNai != null && officialNai.equals(nai)) return true;
2466 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002467 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002468 " - " + nai);
2469 }
2470 return false;
2471 }
2472
Robert Greenwalt42acef32009-08-12 16:08:25 -07002473 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002474 private class NetworkStateTrackerHandler extends Handler {
2475 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002476 super(looper);
2477 }
2478
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002479 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002481 default:
2482 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002483 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002484 handleAsyncChannelHalfConnect(msg);
2485 break;
2486 }
2487 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2488 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2489 if (nai != null) nai.asyncChannel.disconnect();
2490 break;
2491 }
2492 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2493 handleAsyncChannelDisconnected(msg);
2494 break;
2495 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002496 }
2497 return true;
2498 }
2499
2500 private void maybeHandleNetworkAgentMessage(Message msg) {
2501 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2502 if (nai == null) {
2503 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002504 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002505 }
2506 return;
2507 }
2508
2509 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002510 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002511 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002512 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002513 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002514 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002515 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002516 break;
2517 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002518 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002519 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002520 break;
2521 }
2522 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002523 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002524 updateNetworkInfo(nai, info);
2525 break;
2526 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002527 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002528 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002529 break;
2530 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002531 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002532 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2533 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002534 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002535 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002536 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002537 // Mark the network as temporarily accepting partial connectivity so that it
2538 // will be validated (and possibly become default) even if it only provides
2539 // partial internet access. Note that if user connects to partial connectivity
2540 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2541 // out of wifi coverage) and if the same wifi is available again, the device
2542 // will auto connect to this wifi even though the wifi has "no internet".
2543 // TODO: Evaluate using a separate setting in IpMemoryStore.
2544 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002545 break;
2546 }
junyulaie4135282019-01-03 18:50:15 +08002547 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2548 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002549 break;
2550 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002551 }
2552 }
2553
2554 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2555 switch (msg.what) {
2556 default:
2557 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002558 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002559 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002560 if (nai == null) break;
2561
lucasline252a742019-03-12 13:08:03 +08002562 final boolean partialConnectivity =
2563 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
2564 // If user accepts partial connectivity network, NetworkMonitor
2565 // will skip https probing. It will make partial connectivity
2566 // network becomes valid. But user still need to know this
2567 // network is limited. So, it's needed to refer to
2568 // acceptPartialConnectivity to add
2569 // NET_CAPABILITY_PARTIAL_CONNECTIVITY into NetworkCapabilities
2570 // of this network. So that user can see "Limited connection"
2571 // in the settings.
2572 || (nai.networkMisc.acceptPartialConnectivity
2573 && nai.partialConnectivity);
2574 // Once a network is determined to have partial connectivity, it cannot
2575 // go back to full connectivity without a disconnect.
2576 final boolean partialConnectivityChange =
2577 (partialConnectivity && !nai.partialConnectivity);
2578
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002579 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002580 final boolean wasValidated = nai.lastValidated;
2581 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002582 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2583 && valid) {
2584 nai.captivePortalLoginNotified = true;
2585 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2586 }
lucasline252a742019-03-12 13:08:03 +08002587 // If this network has just connected and partial connectivity has just been
2588 // detected, tell NetworkMonitor if the user accepted partial connectivity on a
2589 // previous connect.
2590 if ((msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
2591 && nai.networkMisc.acceptPartialConnectivity) {
2592 try {
2593 nai.networkMonitor().notifyAcceptPartialConnectivity();
2594 } catch (RemoteException e) {
2595 e.rethrowFromSystemServer();
2596 }
2597 }
Erik Klinea24d4592018-01-11 21:07:29 +09002598
Erik Klinea24d4592018-01-11 21:07:29 +09002599 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2600
Erik Klinea24d4592018-01-11 21:07:29 +09002601 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002602 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2603 ? " with redirect to " + redirectUrl
2604 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002605 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2606 }
Erik Klinea24d4592018-01-11 21:07:29 +09002607 if (valid != nai.lastValidated) {
2608 if (wasDefault) {
2609 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2610 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002611 }
Erik Klinea24d4592018-01-11 21:07:29 +09002612 final int oldScore = nai.getCurrentScore();
2613 nai.lastValidated = valid;
2614 nai.everValidated |= valid;
2615 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2616 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2617 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002618 if (valid) {
2619 handleFreshlyValidatedNetwork(nai);
2620 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2621 // valid.
2622 mNotifier.clearNotification(nai.network.netId,
2623 NotificationType.NO_INTERNET);
2624 mNotifier.clearNotification(nai.network.netId,
2625 NotificationType.LOST_INTERNET);
2626 }
lucasline252a742019-03-12 13:08:03 +08002627 } else if (partialConnectivityChange) {
2628 nai.partialConnectivity = partialConnectivity;
2629 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002630 }
2631 updateInetCondition(nai);
2632 // Let the NetworkAgent know the state of its network
2633 Bundle redirectUrlBundle = new Bundle();
2634 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2635 nai.asyncChannel.sendMessage(
2636 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2637 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2638 0, redirectUrlBundle);
2639 if (wasValidated && !nai.lastValidated) {
2640 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002641 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002642 break;
2643 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002644 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002645 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002646 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002647 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002648 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002649 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002650 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002651 nai.lastCaptivePortalDetected = visible;
2652 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002653 if (visible) {
2654 nai.captivePortalLoginNotified = false;
2655 }
Calvin Onbe96da12016-10-11 15:10:46 -07002656 if (nai.lastCaptivePortalDetected &&
2657 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2658 if (DBG) log("Avoiding captive portal network: " + nai.name());
2659 nai.asyncChannel.sendMessage(
2660 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2661 teardownUnneededNetwork(nai);
2662 break;
2663 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002664 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002665 }
2666 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002667 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002668 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002669 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2670 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002671 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002672 if (nai == null) {
2673 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2674 break;
2675 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002676 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002677 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002678 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002679 }
Paul Jensen869868be2014-05-15 10:33:05 -04002680 }
Paul Jensen869868be2014-05-15 10:33:05 -04002681 break;
2682 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002683 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002684 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002685 if (nai == null) break;
2686
Erik Kline736353a2018-03-21 07:18:33 -07002687 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002688 break;
2689 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002690 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002691 return true;
2692 }
2693
Calvin Onbe96da12016-10-11 15:10:46 -07002694 private int getCaptivePortalMode() {
2695 return Settings.Global.getInt(mContext.getContentResolver(),
2696 Settings.Global.CAPTIVE_PORTAL_MODE,
2697 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2698 }
2699
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002700 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2701 switch (msg.what) {
2702 default:
2703 return false;
2704 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2705 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2706 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2707 handleLingerComplete(nai);
2708 }
2709 break;
2710 }
2711 }
2712 return true;
2713 }
2714
Etan Cohenae574a82019-01-08 12:09:18 -08002715 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2716 switch (msg.what) {
2717 default:
2718 return false;
2719 case NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2720 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2721 /* callOnUnavailable */ true);
2722 break;
2723 }
2724 }
2725 return true;
2726 }
2727
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002728 @Override
2729 public void handleMessage(Message msg) {
Etan Cohenae574a82019-01-08 12:09:18 -08002730 if (!maybeHandleAsyncChannelMessage(msg)
2731 && !maybeHandleNetworkMonitorMessage(msg)
2732 && !maybeHandleNetworkAgentInfoMessage(msg)
2733 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002734 maybeHandleNetworkAgentMessage(msg);
2735 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002736 }
2737 }
2738
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002739 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2740 private final NetworkAgentInfo mNai;
2741
2742 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2743 mNai = nai;
2744 }
2745
2746 @Override
2747 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2748 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2749 new Pair<>(mNai, networkMonitor)));
2750 }
2751
2752 @Override
2753 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2754 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2755 testResult, mNai.network.netId, redirectUrl));
2756 }
2757
2758 @Override
2759 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2760 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2761 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2762 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2763 }
2764
2765 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002766 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002767 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002768 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002769
2770 final PendingIntent pendingIntent;
2771 // Only the system server can register notifications with package "android"
2772 final long token = Binder.clearCallingIdentity();
2773 try {
2774 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2775 } finally {
2776 Binder.restoreCallingIdentity(token);
2777 }
2778 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2779 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2780 mNai.network.netId,
2781 pendingIntent));
2782 }
2783
2784 @Override
2785 public void hideProvisioningNotification() {
2786 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2787 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2788 mNai.network.netId));
2789 }
2790 }
2791
Erik Kline736353a2018-03-21 07:18:33 -07002792 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002793 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002794 }
2795
Erik Klinec6d00222018-06-26 18:53:43 +09002796 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2797 if (nai == null) return;
2798 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2799 // in order to restart a validation pass from within netd.
2800 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2801 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2802 updateDnses(nai.linkProperties, null, nai.network.netId);
2803 }
2804 }
2805
Erik Klinea24d4592018-01-11 21:07:29 +09002806 private void handlePrivateDnsSettingsChanged() {
2807 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2808
2809 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002810 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002811 if (networkRequiresValidation(nai)) {
2812 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2813 }
Erik Klinea24d4592018-01-11 21:07:29 +09002814 }
2815 }
2816
Erik Kline736353a2018-03-21 07:18:33 -07002817 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2818 // Private DNS only ever applies to networks that might provide
2819 // Internet access and therefore also require validation.
2820 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002821
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002822 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002823 // schedule DNS resolutions. If a DNS resolution is required the
2824 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002825 try {
2826 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2827 } catch (RemoteException e) {
2828 e.rethrowFromSystemServer();
2829 }
Erik Kline736353a2018-03-21 07:18:33 -07002830
2831 // With Private DNS bypass support, we can proceed to update the
2832 // Private DNS config immediately, even if we're in strict mode
2833 // and have not yet resolved the provider name into a set of IPs.
2834 updatePrivateDns(nai, cfg);
2835 }
2836
2837 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2838 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002839 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002840 }
2841
dalyk7301aa42018-03-05 12:42:22 -05002842 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2843 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2844 if (nai == null) {
2845 return;
2846 }
2847 mDnsManager.updatePrivateDnsValidation(update);
2848 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2849 }
2850
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002851 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2852 int prefixLength) {
2853 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2854 if (nai == null) return;
2855
2856 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2857 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2858
2859 IpPrefix prefix = null;
2860 if (added) {
2861 try {
2862 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2863 prefixLength);
2864 } catch (IllegalArgumentException e) {
2865 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2866 return;
2867 }
2868 }
2869
2870 nai.clatd.setNat64Prefix(prefix);
2871 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2872 }
2873
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002874 private void updateLingerState(NetworkAgentInfo nai, long now) {
2875 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2876 // 2. If the network was lingering and there are now requests, unlinger it.
2877 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2878 // one lingered request, start lingering.
2879 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002880 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002881 if (DBG) log("Unlingering " + nai.name());
2882 nai.unlinger();
2883 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002884 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002885 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002886 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002887 nai.linger();
2888 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2889 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2890 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002891 }
2892
Robert Greenwalt7b816022014-04-18 15:25:25 -07002893 private void handleAsyncChannelHalfConnect(Message msg) {
2894 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002895 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002896 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2897 if (VDBG) log("NetworkFactory connected");
Etan Cohenae574a82019-01-08 12:09:18 -08002898 // Finish setting up the full connection
2899 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2900 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002901 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002902 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002903 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002904 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002905 final int score;
2906 final int serial;
2907 if (nai != null) {
2908 score = nai.getCurrentScore();
2909 serial = nai.factorySerialNumber;
2910 } else {
2911 score = 0;
2912 serial = NetworkFactory.SerialNumber.NONE;
2913 }
2914 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2915 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002916 }
2917 } else {
2918 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002919 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002920 }
2921 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2922 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2923 if (VDBG) log("NetworkAgent connected");
2924 // A network agent has requested a connection. Establish the connection.
2925 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2926 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2927 } else {
2928 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002929 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002930 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002931 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002932 synchronized (mNetworkForNetId) {
2933 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002934 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002935 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002936 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002937 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002938 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002939 }
2940 }
2941 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002942
Chalard Jean392971c2018-05-11 20:19:20 +09002943 // This is a no-op if it's called with a message designating a network that has
2944 // already been destroyed, because its reference will not be found in the relevant
2945 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002946 private void handleAsyncChannelDisconnected(Message msg) {
2947 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2948 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002949 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002950 } else {
2951 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2952 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002953 }
2954 }
2955
Chalard Jean392971c2018-05-11 20:19:20 +09002956 // Destroys a network, remove references to it from the internal state managed by
2957 // ConnectivityService, free its interfaces and clean up.
2958 // Must be called on the Handler thread.
2959 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2960 if (DBG) {
2961 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2962 }
lucaslinf80b83b2019-02-12 15:30:13 +08002963 // Clear all notifications of this network.
2964 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002965 // A network agent has disconnected.
2966 // TODO - if we move the logic to the network agent (have them disconnect
2967 // because they lost all their requests or because their score isn't good)
2968 // then they would disconnect organically, report their new state and then
2969 // disconnect the channel.
2970 if (nai.networkInfo.isConnected()) {
2971 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2972 null, null);
2973 }
2974 final boolean wasDefault = isDefaultNetwork(nai);
2975 if (wasDefault) {
2976 mDefaultInetConditionPublished = 0;
2977 // Log default network disconnection before required book-keeping.
2978 // Let rematchAllNetworksAndRequests() below record a new default network event
2979 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2980 // whose timestamps tell how long it takes to recover a default network.
2981 long now = SystemClock.elapsedRealtime();
2982 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2983 }
2984 notifyIfacesChangedForNetworkStats();
2985 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2986 // by other networks that are already connected. Perhaps that can be done by
2987 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2988 // of rematchAllNetworksAndRequests
2989 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulaie4135282019-01-03 18:50:15 +08002990 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002991 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2992 // Disable wakeup packet monitoring for each interface.
2993 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2994 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002995 try {
2996 nai.networkMonitor().notifyNetworkDisconnected();
2997 } catch (RemoteException e) {
2998 e.rethrowFromSystemServer();
2999 }
Chalard Jean392971c2018-05-11 20:19:20 +09003000 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09003001 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09003002 synchronized (mNetworkForNetId) {
3003 // Remove the NetworkAgent, but don't mark the netId as
3004 // available until we've told netd to delete it below.
3005 mNetworkForNetId.remove(nai.network.netId);
3006 }
3007 // Remove all previously satisfied requests.
3008 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3009 NetworkRequest request = nai.requestAt(i);
3010 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
3011 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3012 clearNetworkForRequest(request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09003013 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003014 }
3015 }
3016 nai.clearLingerState();
3017 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003018 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003019 notifyLockdownVpn(nai);
3020 ensureNetworkTransitionWakelock(nai.name());
3021 }
3022 mLegacyTypeTracker.remove(nai, wasDefault);
3023 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3024 updateAllVpnsCapabilities();
3025 }
3026 rematchAllNetworksAndRequests(null, 0);
3027 mLingerMonitor.noteDisconnect(nai);
3028 if (nai.created) {
3029 // Tell netd to clean up the configuration for this network
3030 // (routing rules, DNS, etc).
3031 // This may be slow as it requires a lot of netd shelling out to ip and
3032 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3033 // after we've rematched networks with requests which should make a potential
3034 // fallback network the default or requested a new network from the
3035 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3036 // long time.
3037 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08003038 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003039 } catch (Exception e) {
3040 loge("Exception removing network: " + e);
3041 }
3042 mDnsManager.removeNetwork(nai.network);
3043 }
3044 synchronized (mNetworkForNetId) {
3045 mNetIdInUse.delete(nai.network.netId);
3046 }
3047 }
3048
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003049 // If this method proves to be too slow then we can maintain a separate
3050 // pendingIntent => NetworkRequestInfo map.
3051 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3052 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3053 Intent intent = pendingIntent.getIntent();
3054 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3055 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3056 if (existingPendingIntent != null &&
3057 existingPendingIntent.getIntent().filterEquals(intent)) {
3058 return entry.getValue();
3059 }
3060 }
3061 return null;
3062 }
3063
3064 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3065 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3066
3067 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3068 if (existingRequest != null) { // remove the existing request.
3069 if (DBG) log("Replacing " + existingRequest.request + " with "
3070 + nri.request + " because their intents matched.");
Etan Cohenae574a82019-01-08 12:09:18 -08003071 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3072 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003073 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003074 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003075 }
3076
Erik Klineda4bfa82015-04-30 12:58:40 +09003077 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003078 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003079 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003080 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003081 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003082 if (nri.request.networkCapabilities.hasSignalStrength() &&
3083 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3084 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003085 }
3086 }
3087 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003088 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003089 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean08577fc2018-05-02 21:14:54 +09003090 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003091 }
3092 }
3093
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003094 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3095 int callingUid) {
3096 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3097 if (nri != null) {
Etan Cohenae574a82019-01-08 12:09:18 -08003098 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003099 }
3100 }
3101
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003102 // Determines whether the network is the best (or could become the best, if it validated), for
3103 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3104 // on the value of reason:
3105 //
3106 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3107 // then it should be torn down.
3108 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3109 // then it should be lingered.
3110 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3111 final int numRequests;
3112 switch (reason) {
3113 case TEARDOWN:
3114 numRequests = nai.numRequestNetworkRequests();
3115 break;
3116 case LINGER:
3117 numRequests = nai.numForegroundNetworkRequests();
3118 break;
3119 default:
3120 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3121 return true;
3122 }
3123
3124 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003125 return false;
3126 }
Paul Jensene0988542015-06-25 15:30:08 -04003127 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003128 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3129 // Background requests don't affect lingering.
3130 continue;
3131 }
3132
Paul Jensene0988542015-06-25 15:30:08 -04003133 // If this Network is already the highest scoring Network for a request, or if
3134 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003135 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003136 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003137 // Note that this catches two important cases:
3138 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3139 // is currently satisfying the request. This is desirable when
3140 // cellular ends up validating but WiFi does not.
3141 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003142 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003143 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003144 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003145 nai.getCurrentScoreAsValidated())) {
3146 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003147 }
3148 }
Paul Jensene0988542015-06-25 15:30:08 -04003149 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003150 }
3151
Erik Klineacdd6392016-07-07 16:50:58 +09003152 private NetworkRequestInfo getNriForAppRequest(
3153 NetworkRequest request, int callingUid, String requestedOperation) {
3154 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3155
Robert Greenwalt9258c642014-03-26 16:47:06 -07003156 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003157 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003158 log(String.format("UID %d attempted to %s for unowned request %s",
3159 callingUid, requestedOperation, nri));
3160 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003161 }
Erik Klineacdd6392016-07-07 16:50:58 +09003162 }
3163
3164 return nri;
3165 }
3166
Erik Kline57faba92015-11-25 12:49:38 +09003167 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003168 if (mNetworkRequests.get(nri.request) == null) {
3169 return;
Erik Kline57faba92015-11-25 12:49:38 +09003170 }
Hugo Benichicd952782017-09-20 11:20:14 +09003171 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003172 return;
3173 }
3174 if (VDBG || (DBG && nri.request.isRequest())) {
3175 log("releasing " + nri.request + " (timeout)");
3176 }
3177 handleRemoveNetworkRequest(nri);
3178 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003179 }
3180
Etan Cohenae574a82019-01-08 12:09:18 -08003181 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3182 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003183 final NetworkRequestInfo nri =
3184 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3185 if (nri == null) {
3186 return;
Erik Kline57faba92015-11-25 12:49:38 +09003187 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003188 if (VDBG || (DBG && nri.request.isRequest())) {
3189 log("releasing " + nri.request + " (release request)");
3190 }
3191 handleRemoveNetworkRequest(nri);
Etan Cohenae574a82019-01-08 12:09:18 -08003192 if (callOnUnavailable) {
3193 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3194 }
Erik Kline57faba92015-11-25 12:49:38 +09003195 }
Erik Klineacdd6392016-07-07 16:50:58 +09003196
Hugo Benichidba33db2017-03-23 22:40:44 +09003197 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003198 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003199 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003200
Erik Klineacdd6392016-07-07 16:50:58 +09003201 synchronized (mUidToNetworkRequestCount) {
3202 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3203 if (requests < 1) {
3204 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3205 nri.mUid);
3206 } else if (requests == 1) {
3207 mUidToNetworkRequestCount.removeAt(
3208 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3209 } else {
3210 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3211 }
3212 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003213
Erik Klineacdd6392016-07-07 16:50:58 +09003214 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3215 if (nri.request.isRequest()) {
3216 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003217 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003218 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003219 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003220 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003221 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003222 log(" Removing from current network " + nai.name() +
3223 ", leaving " + nai.numNetworkRequests() + " requests.");
3224 }
3225 // If there are still lingered requests on this network, don't tear it down,
3226 // but resume lingering instead.
3227 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003228 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003229 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3230 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003231 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003232 wasKept = true;
3233 }
Hugo Benichicd952782017-09-20 11:20:14 +09003234 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003235 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3236 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003237 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003238 }
Erik Klineacdd6392016-07-07 16:50:58 +09003239 }
3240
Erik Klineacdd6392016-07-07 16:50:58 +09003241 // Maintain the illusion. When this request arrived, we might have pretended
3242 // that a network connected to serve it, even though the network was already
3243 // connected. Now that this request has gone away, we might have to pretend
3244 // that the network disconnected. LegacyTypeTracker will generate that
3245 // phantom disconnect for this type.
3246 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3247 boolean doRemove = true;
3248 if (wasKept) {
3249 // check if any of the remaining requests for this network are for the
3250 // same legacy type - if so, don't remove the nai
3251 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3252 NetworkRequest otherRequest = nai.requestAt(i);
3253 if (otherRequest.legacyType == nri.request.legacyType &&
3254 otherRequest.isRequest()) {
3255 if (DBG) log(" still have other legacy request - leaving");
3256 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003257 }
3258 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003259 }
3260
Erik Klineacdd6392016-07-07 16:50:58 +09003261 if (doRemove) {
3262 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003263 }
3264 }
Erik Klineacdd6392016-07-07 16:50:58 +09003265
3266 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3267 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3268 nri.request);
3269 }
3270 } else {
3271 // listens don't have a singular affectedNetwork. Check all networks to see
3272 // if this listen request applies and remove it.
3273 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3274 nai.removeRequest(nri.request.requestId);
3275 if (nri.request.networkCapabilities.hasSignalStrength() &&
3276 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3277 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3278 }
3279 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003280 }
3281 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003282
Lorenzo Colitti18660282016-07-04 12:55:44 +09003283 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003284 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003285 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003286 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003287 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003288 }
3289
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003290 @Override
lucasline252a742019-03-12 13:08:03 +08003291 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3292 enforceNetworkStackSettingsOrSetup();
3293 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3294 encodeBool(accept), encodeBool(always), network));
3295 }
3296
3297 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003298 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003299 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003300 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3301 }
3302
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003303 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3304 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3305 " accept=" + accept + " always=" + always);
3306
3307 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3308 if (nai == null) {
3309 // Nothing to do.
3310 return;
3311 }
3312
3313 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003314 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003315 return;
3316 }
3317
3318 if (!nai.networkMisc.explicitlySelected) {
3319 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3320 }
3321
3322 if (accept != nai.networkMisc.acceptUnvalidated) {
3323 int oldScore = nai.getCurrentScore();
3324 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003325 // If network becomes partial connectivity and user already accepted to use this
3326 // network, we should respect the user's option and don't need to popup the
3327 // PARTIAL_CONNECTIVITY notification to user again.
3328 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003329 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003330 sendUpdatedScoreToFactories(nai);
3331 }
3332
3333 if (always) {
3334 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003335 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003336 }
3337
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003338 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003339 // Tell the NetworkAgent to not automatically reconnect to the network.
3340 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003341 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003342 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003343 }
3344
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003345 }
3346
lucasline252a742019-03-12 13:08:03 +08003347 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3348 boolean always) {
3349 if (DBG) {
3350 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3351 + " always=" + always);
3352 }
3353
3354 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3355 if (nai == null) {
3356 // Nothing to do.
3357 return;
3358 }
3359
3360 if (nai.lastValidated) {
3361 // The network validated while the dialog box was up. Take no action.
3362 return;
3363 }
3364
3365 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3366 nai.networkMisc.acceptPartialConnectivity = accept;
3367 }
3368
3369 // TODO: Use the current design or save the user choice into IpMemoryStore.
3370 if (always) {
3371 nai.asyncChannel.sendMessage(
3372 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3373 }
3374
3375 if (!accept) {
3376 // Tell the NetworkAgent to not automatically reconnect to the network.
3377 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3378 // Tear down the network.
3379 teardownUnneededNetwork(nai);
3380 } else {
3381 try {
3382 nai.networkMonitor().notifyAcceptPartialConnectivity();
3383 } catch (RemoteException e) {
3384 e.rethrowFromSystemServer();
3385 }
3386 }
3387 }
3388
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003389 private void handleSetAvoidUnvalidated(Network network) {
3390 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3391 if (nai == null || nai.lastValidated) {
3392 // Nothing to do. The network either disconnected or revalidated.
3393 return;
3394 }
3395 if (!nai.avoidUnvalidated) {
3396 int oldScore = nai.getCurrentScore();
3397 nai.avoidUnvalidated = true;
3398 rematchAllNetworksAndRequests(nai, oldScore);
3399 sendUpdatedScoreToFactories(nai);
3400 }
3401 }
3402
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003403 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003404 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003405 mHandler.sendMessageDelayed(
3406 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3407 PROMPT_UNVALIDATED_DELAY_MS);
3408 }
3409
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003410 @Override
3411 public void startCaptivePortalApp(Network network) {
3412 enforceConnectivityInternalPermission();
3413 mHandler.post(() -> {
3414 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3415 if (nai == null) return;
3416 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003417 try {
3418 nai.networkMonitor().launchCaptivePortalApp();
3419 } catch (RemoteException e) {
3420 e.rethrowFromSystemServer();
3421 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003422 });
3423 }
3424
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003425 /**
3426 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3427 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003428 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003429 * @param appExtras Bundle to use as intent extras for the captive portal application.
3430 * Must be treated as opaque to avoid preventing the captive portal app to
3431 * update its arguments.
3432 */
3433 @Override
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003434 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003435 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3436
3437 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3438 appIntent.putExtras(appExtras);
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003439 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3440 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003441 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3442
3443 Binder.withCleanCallingIdentity(() ->
3444 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3445 }
3446
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003447 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3448 private final Network mNetwork;
3449
3450 private CaptivePortalImpl(Network network) {
3451 mNetwork = network;
3452 }
3453
3454 @Override
3455 public void appResponse(final int response) throws RemoteException {
3456 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3457 enforceSettingsPermission();
3458 }
3459
3460 // getNetworkAgentInfoForNetwork is thread-safe
3461 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3462 if (nai == null) return;
3463
3464 // nai.networkMonitor() is thread-safe
3465 final INetworkMonitor nm = nai.networkMonitor();
3466 if (nm == null) return;
3467
3468 final long token = Binder.clearCallingIdentity();
3469 try {
3470 nm.notifyCaptivePortalAppFinished(response);
3471 } finally {
3472 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3473 Binder.restoreCallingIdentity(token);
3474 }
3475 }
3476
3477 @Override
3478 public void logEvent(int eventId, String packageName) {
3479 enforceSettingsPermission();
3480
3481 new MetricsLogger().action(eventId, packageName);
3482 }
3483 }
3484
Hugo Benichic8e9e122016-09-14 23:23:08 +00003485 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003486 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003487 }
3488
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003489 @Override
3490 public boolean getAvoidBadWifi() {
3491 if (!checkNetworkStackPermission()) {
3492 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3493 }
3494 return avoidBadWifi();
3495 }
3496
3497
Erik Kline065ab6e2016-10-02 18:02:14 +09003498 private void rematchForAvoidBadWifiUpdate() {
3499 rematchAllNetworksAndRequests(null, 0);
3500 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3501 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3502 sendUpdatedScoreToFactories(nai);
3503 }
3504 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003505 }
3506
Erik Kline065ab6e2016-10-02 18:02:14 +09003507 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003508 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003509 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003510 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003511 if (!configRestrict) {
3512 pw.println("Bad Wi-Fi avoidance: unrestricted");
3513 return;
3514 }
3515
3516 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3517 pw.increaseIndent();
3518 pw.println("Config restrict: " + configRestrict);
3519
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003520 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003521 String description;
3522 // Can't use a switch statement because strings are legal case labels, but null is not.
3523 if ("0".equals(value)) {
3524 description = "get stuck";
3525 } else if (value == null) {
3526 description = "prompt";
3527 } else if ("1".equals(value)) {
3528 description = "avoid";
3529 } else {
3530 description = value + " (?)";
3531 }
3532 pw.println("User setting: " + description);
3533 pw.println("Network overrides:");
3534 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003535 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003536 if (nai.avoidUnvalidated) {
3537 pw.println(nai.name());
3538 }
3539 }
3540 pw.decreaseIndent();
3541 pw.decreaseIndent();
3542 }
3543
lucaslind2e045e02019-01-24 15:55:30 +08003544 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003545 final String action;
3546 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003547 case LOGGED_IN:
3548 action = Settings.ACTION_WIFI_SETTINGS;
3549 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3550 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3551 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3552 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003553 case NO_INTERNET:
3554 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3555 break;
3556 case LOST_INTERNET:
3557 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3558 break;
lucasline252a742019-03-12 13:08:03 +08003559 case PARTIAL_CONNECTIVITY:
3560 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3561 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003562 default:
3563 Slog.wtf(TAG, "Unknown notification type " + type);
3564 return;
3565 }
3566
3567 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003568 if (type != NotificationType.LOGGED_IN) {
3569 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3570 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3571 intent.setClassName("com.android.settings",
3572 "com.android.settings.wifi.WifiNoInternetDialog");
3573 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003574
3575 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3576 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3577 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3578 }
3579
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003580 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003581 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003582 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3583
lucasline252a742019-03-12 13:08:03 +08003584 // Only prompt if the network is unvalidated or network has partial internet connectivity
3585 // and was explicitly selected by the user, and if we haven't already been told to switch
3586 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3587 // because we're already prompting the user to sign in.
3588 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3589 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
3590 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003591 return;
3592 }
lucasline252a742019-03-12 13:08:03 +08003593 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3594 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3595 // popup the notification immediately when the network is partial connectivity.
3596 if (nai.partialConnectivity) {
3597 // Treat PARTIAL_CONNECTIVITY as NO_INTERNET temporary until Settings has been updated.
3598 // TODO: Need to change back to PARTIAL_CONNECTIVITY when Settings part is merged.
3599 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3600 } else {
3601 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3602 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003603 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003604
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003605 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3606 NetworkCapabilities nc = nai.networkCapabilities;
3607 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003608
lucasline252a742019-03-12 13:08:03 +08003609 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3610 return;
3611 }
3612
3613 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003614 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003615 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003616 }
3617
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003618 @Override
3619 public int getMultipathPreference(Network network) {
3620 enforceAccessPermission();
3621
3622 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003623 if (nai != null && nai.networkCapabilities
3624 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003625 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3626 }
3627
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003628 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3629 if (networkPreference != null) {
3630 return networkPreference;
3631 }
3632
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003633 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3634 }
3635
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003636 @Override
3637 public NetworkRequest getDefaultRequest() {
3638 return mDefaultRequest;
3639 }
3640
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003641 private class InternalHandler extends Handler {
3642 public InternalHandler(Looper looper) {
3643 super(looper);
3644 }
3645
3646 @Override
3647 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003648 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003649 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003650 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003651 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003652 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003653 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003654 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003655 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003656 break;
3657 }
Jason Monkdecd2952013-10-10 14:02:51 -04003658 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003659 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003660 break;
3661 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003662 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003663 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3664 break;
3665 }
3666 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3667 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003668 break;
3669 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003670 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003671 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3672 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3673 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003674 break;
3675 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003676 case EVENT_REGISTER_NETWORK_REQUEST:
3677 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003678 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003679 break;
3680 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003681 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3682 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003683 handleRegisterNetworkRequestWithIntent(msg);
3684 break;
3685 }
Erik Kline57faba92015-11-25 12:49:38 +09003686 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3687 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3688 handleTimedOutNetworkRequest(nri);
3689 break;
3690 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003691 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3692 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3693 break;
3694 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003695 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenae574a82019-01-08 12:09:18 -08003696 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3697 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003698 break;
3699 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003700 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003701 Network network = (Network) msg.obj;
3702 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003703 break;
3704 }
lucasline252a742019-03-12 13:08:03 +08003705 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3706 Network network = (Network) msg.obj;
3707 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3708 toBool(msg.arg2));
3709 break;
3710 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003711 case EVENT_SET_AVOID_UNVALIDATED: {
3712 handleSetAvoidUnvalidated((Network) msg.obj);
3713 break;
3714 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003715 case EVENT_PROMPT_UNVALIDATED: {
3716 handlePromptUnvalidated((Network) msg.obj);
3717 break;
3718 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003719 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3720 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003721 break;
3722 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003723 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003724 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003725 mKeepaliveTracker.handleStartKeepalive(msg);
3726 break;
3727 }
3728 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003729 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003730 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3731 int slot = msg.arg1;
3732 int reason = msg.arg2;
3733 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3734 break;
3735 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003736 case EVENT_SYSTEM_READY: {
3737 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003738 // Might have been called already in handleRegisterNetworkAgent since
3739 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3740 // this several times is fine.
3741 try {
3742 nai.networkMonitor().notifySystemReady();
3743 } catch (RemoteException e) {
3744 e.rethrowFromSystemServer();
3745 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003746 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003747 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003748 break;
3749 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003750 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003751 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003752 break;
3753 }
Erik Klinea24d4592018-01-11 21:07:29 +09003754 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3755 handlePrivateDnsSettingsChanged();
3756 break;
dalyk7301aa42018-03-05 12:42:22 -05003757 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3758 handlePrivateDnsValidationUpdate(
3759 (PrivateDnsValidationUpdate) msg.obj);
3760 break;
junyulai05986c62018-08-07 19:50:45 +08003761 case EVENT_UID_RULES_CHANGED:
3762 handleUidRulesChanged(msg.arg1, msg.arg2);
3763 break;
3764 case EVENT_DATA_SAVER_CHANGED:
3765 handleRestrictBackgroundChanged(toBool(msg.arg1));
3766 break;
lucaslind2e045e02019-01-24 15:55:30 +08003767 case EVENT_TIMEOUT_NOTIFICATION:
3768 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3769 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 }
3771 }
3772 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003773
3774 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003775 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003776 public int tether(String iface, String callerPkg) {
3777 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003778 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003779 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003780 } else {
3781 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3782 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003783 }
3784
3785 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003786 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003787 public int untether(String iface, String callerPkg) {
3788 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003789
3790 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003791 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003792 } else {
3793 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3794 }
3795 }
3796
3797 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003798 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003799 public int getLastTetherError(String iface) {
3800 enforceTetherAccessPermission();
3801
3802 if (isTetheringSupported()) {
3803 return mTethering.getLastTetherError(iface);
3804 } else {
3805 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3806 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003807 }
3808
3809 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003810 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003811 public String[] getTetherableUsbRegexs() {
3812 enforceTetherAccessPermission();
3813 if (isTetheringSupported()) {
3814 return mTethering.getTetherableUsbRegexs();
3815 } else {
3816 return new String[0];
3817 }
3818 }
3819
Lorenzo Colitti18660282016-07-04 12:55:44 +09003820 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003821 public String[] getTetherableWifiRegexs() {
3822 enforceTetherAccessPermission();
3823 if (isTetheringSupported()) {
3824 return mTethering.getTetherableWifiRegexs();
3825 } else {
3826 return new String[0];
3827 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003828 }
3829
Lorenzo Colitti18660282016-07-04 12:55:44 +09003830 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003831 public String[] getTetherableBluetoothRegexs() {
3832 enforceTetherAccessPermission();
3833 if (isTetheringSupported()) {
3834 return mTethering.getTetherableBluetoothRegexs();
3835 } else {
3836 return new String[0];
3837 }
3838 }
3839
Lorenzo Colitti18660282016-07-04 12:55:44 +09003840 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003841 public int setUsbTethering(boolean enable, String callerPkg) {
3842 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003843 if (isTetheringSupported()) {
3844 return mTethering.setUsbTethering(enable);
3845 } else {
3846 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3847 }
3848 }
3849
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003850 // TODO - move iface listing, queries, etc to new module
3851 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003852 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003853 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003854 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003855 return mTethering.getTetherableIfaces();
3856 }
3857
Lorenzo Colitti18660282016-07-04 12:55:44 +09003858 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003859 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003860 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003861 return mTethering.getTetheredIfaces();
3862 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003863
Lorenzo Colitti18660282016-07-04 12:55:44 +09003864 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003865 public String[] getTetheringErroredIfaces() {
3866 enforceTetherAccessPermission();
3867 return mTethering.getErroredIfaces();
3868 }
3869
Lorenzo Colitti18660282016-07-04 12:55:44 +09003870 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003871 public String[] getTetheredDhcpRanges() {
3872 enforceConnectivityInternalPermission();
3873 return mTethering.getTetheredDhcpRanges();
3874 }
3875
Udam Saini0e94c362017-06-07 12:06:28 -07003876 @Override
3877 public boolean isTetheringSupported(String callerPkg) {
3878 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3879 return isTetheringSupported();
3880 }
3881
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003882 // if ro.tether.denied = true we default to no tethering
3883 // gservices could set the secure setting to 1 though to enable it on a build where it
3884 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003885 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003886 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3887 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3888 Settings.Global.TETHER_SUPPORTED, defaultVal));
3889 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003890 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003891
3892 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3893 boolean adminUser = false;
3894 final long token = Binder.clearCallingIdentity();
3895 try {
3896 adminUser = mUserManager.isAdminUser();
3897 } finally {
3898 Binder.restoreCallingIdentity(token);
3899 }
3900
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003901 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003902 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003903
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003904 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003905 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3906 String callerPkg) {
3907 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003908 if (!isTetheringSupported()) {
3909 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3910 return;
3911 }
3912 mTethering.startTethering(type, receiver, showProvisioningUi);
3913 }
3914
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003915 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003916 public void stopTethering(int type, String callerPkg) {
3917 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003918 mTethering.stopTethering(type);
3919 }
3920
markchienf2731272019-01-16 17:44:13 +08003921 /**
3922 * Get the latest value of the tethering entitlement check.
3923 *
3924 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3925 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3926 * if it's really needed.
3927 */
3928 @Override
markchien9554abf2019-03-06 16:25:00 +08003929 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003930 boolean showEntitlementUi, String callerPkg) {
3931 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003932 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003933 }
3934
markchien6ea34542019-02-27 14:56:11 +08003935 /** Register tethering event callback. */
3936 @Override
3937 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3938 String callerPkg) {
3939 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3940 mTethering.registerTetheringEventCallback(callback);
3941 }
3942
3943 /** Unregister tethering event callback. */
3944 @Override
3945 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3946 String callerPkg) {
3947 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3948 mTethering.unregisterTetheringEventCallback(callback);
3949 }
3950
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003951 // Called when we lose the default network and have no replacement yet.
3952 // This will automatically be cleared after X seconds or a new default network
3953 // becomes CONNECTED, whichever happens first. The timer is started by the
3954 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003955 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003956 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003957 if (mNetTransitionWakeLock.isHeld()) {
3958 return;
3959 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003960 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003961 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3962 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003963 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003964 mWakelockLogs.log("ACQUIRE for " + forWhom);
3965 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3966 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003967 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003968
Hugo Benichi4c31b342017-03-30 23:18:10 +09003969 // Called when we gain a new default network to release the network transition wakelock in a
3970 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3971 // message is cancelled.
3972 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003973 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003974 if (!mNetTransitionWakeLock.isHeld()) {
3975 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003976 }
3977 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003978 // Cancel self timeout on wakelock hold.
3979 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3980 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3981 mHandler.sendMessageDelayed(msg, 1000);
3982 }
3983
3984 // Called when either message of ensureNetworkTransitionWakelock or
3985 // scheduleReleaseNetworkTransitionWakelock is processed.
3986 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3987 String event = eventName(eventId);
3988 synchronized (this) {
3989 if (!mNetTransitionWakeLock.isHeld()) {
3990 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3991 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3992 return;
3993 }
3994 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003995 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3996 mTotalWakelockDurationMs += lockDuration;
3997 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3998 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003999 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004000 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004001 }
4002
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004003 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09004004 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004005 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004006 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004007 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004008 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004009 }
4010
Lorenzo Colitti18660282016-07-04 12:55:44 +09004011 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004012 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004013 enforceAccessPermission();
4014 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004015 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004016 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004017 mHandler.sendMessage(
4018 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4019 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004020
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004021 private void handleReportNetworkConnectivity(
4022 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004023 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004024 if (network == null) {
4025 nai = getDefaultNetwork();
4026 } else {
4027 nai = getNetworkAgentInfoForNetwork(network);
4028 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004029 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4030 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4031 return;
4032 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004033 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004034 if (hasConnectivity == nai.lastValidated) {
4035 return;
4036 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004037 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004038 int netid = nai.network.netId;
4039 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004040 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004041 // Validating a network that has not yet connected could result in a call to
4042 // rematchNetworkAndRequests() which is not meant to work on such networks.
4043 if (!nai.everConnected) {
4044 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004045 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004046 LinkProperties lp = getLinkProperties(nai);
4047 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4048 return;
4049 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004050 try {
4051 nai.networkMonitor().forceReevaluation(uid);
4052 } catch (RemoteException e) {
4053 e.rethrowFromSystemServer();
4054 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 }
4056
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004057 /**
4058 * Returns information about the proxy a certain network is using. If given a null network, it
4059 * it will return the proxy for the bound network for the caller app or the default proxy if
4060 * none.
4061 *
4062 * @param network the network we want to get the proxy information for.
4063 * @return Proxy information if a network has a proxy configured, or otherwise null.
4064 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004065 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004066 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004067 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004068 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004069 if (network == null) {
4070 // Get the network associated with the calling UID.
4071 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4072 true);
4073 if (activeNetwork == null) {
4074 return null;
4075 }
4076 return getLinkPropertiesProxyInfo(activeNetwork);
4077 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4078 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4079 // caller may not have.
4080 return getLinkPropertiesProxyInfo(network);
4081 }
4082 // No proxy info available if the calling UID does not have network access.
4083 return null;
4084 }
4085
4086 @VisibleForTesting
4087 protected boolean queryUserAccess(int uid, int netId) {
4088 return NetworkUtils.queryUserAccess(uid, netId);
4089 }
4090
4091 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004092 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4093 if (nai == null) return null;
4094 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004095 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4096 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004097 }
4098 }
4099
Chalard Jean3c443fc2018-06-07 18:37:59 +09004100 @Override
4101 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004102 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004103 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004104 }
4105
Chalard Jean5afbc832018-06-07 18:02:37 +09004106 @Override
4107 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004108 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004109 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004110 }
4111
Jason Monk207900c2014-04-25 15:00:09 -04004112 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004113 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004114 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004115 proxy = null;
4116 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004117 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004118 }
4119
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004120 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4121 // when any network changes proxy.
4122 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4123 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004124 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004125 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4126 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4127
Chalard Jean4949dd72018-06-07 17:41:29 +09004128 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004129 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004130 }
4131 }
4132
Robert Greenwalt434203a2010-10-11 16:00:27 -07004133 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004134 final private HashMap<Uri, Integer> mUriEventMap;
4135 final private Context mContext;
4136 final private Handler mHandler;
4137
4138 SettingsObserver(Context context, Handler handler) {
4139 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004140 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004141 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004142 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004143 }
4144
Erik Klineda4bfa82015-04-30 12:58:40 +09004145 void observe(Uri uri, int what) {
4146 mUriEventMap.put(uri, what);
4147 final ContentResolver resolver = mContext.getContentResolver();
4148 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004149 }
4150
4151 @Override
4152 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004153 Slog.wtf(TAG, "Should never be reached.");
4154 }
4155
4156 @Override
4157 public void onChange(boolean selfChange, Uri uri) {
4158 final Integer what = mUriEventMap.get(uri);
4159 if (what != null) {
4160 mHandler.obtainMessage(what.intValue()).sendToTarget();
4161 } else {
4162 loge("No matching event to send for URI=" + uri);
4163 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004164 }
4165 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004166
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004167 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004168 Slog.d(TAG, s);
4169 }
4170
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004171 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004172 Slog.e(TAG, s);
4173 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004174
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004175 private static void loge(String s, Throwable t) {
4176 Slog.e(TAG, s, t);
4177 }
4178
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004179 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004180 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004181 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4182 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4183 *
4184 * @param oldPackage Package name of the application which currently controls VPN, which will
4185 * be replaced. If there is no such application, this should should either be
4186 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4187 * @param newPackage Package name of the application which should gain control of VPN, or
4188 * {@code null} to disable.
4189 * @param userId User for whom to prepare the new VPN.
4190 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004191 * @hide
4192 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004193 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004194 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4195 int userId) {
4196 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004197
Hugo Benichi20035e02017-04-26 14:53:28 +09004198 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004199 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004200 Vpn vpn = mVpns.get(userId);
4201 if (vpn != null) {
4202 return vpn.prepare(oldPackage, newPackage);
4203 } else {
4204 return false;
4205 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004206 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004207 }
4208
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004209 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004210 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4211 * This method is used by system-privileged apps.
4212 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4213 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4214 *
4215 * @param packageName The package for which authorization state should change.
4216 * @param userId User for whom {@code packageName} is installed.
4217 * @param authorized {@code true} if this app should be able to start a VPN connection without
4218 * explicit user approval, {@code false} if not.
4219 *
Jeff Davidson05542602014-08-11 14:07:27 -07004220 * @hide
4221 */
4222 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004223 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4224 enforceCrossUserPermission(userId);
4225
Hugo Benichi20035e02017-04-26 14:53:28 +09004226 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004227 Vpn vpn = mVpns.get(userId);
4228 if (vpn != null) {
4229 vpn.setPackageAuthorization(packageName, authorized);
4230 }
Jeff Davidson05542602014-08-11 14:07:27 -07004231 }
4232 }
4233
4234 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004235 * Configure a TUN interface and return its file descriptor. Parameters
4236 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004237 * and not available in ConnectivityManager. Permissions are checked in
4238 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004239 * @hide
4240 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004241 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004242 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004243 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004244 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004245 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004246 return mVpns.get(user).establish(config);
4247 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004248 }
4249
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004250 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004251 * Start legacy VPN, controlling native daemons as needed. Creates a
4252 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004253 */
4254 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004255 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004256 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004257 final LinkProperties egress = getActiveLinkProperties();
4258 if (egress == null) {
4259 throw new IllegalStateException("Missing active network connection");
4260 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004261 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004262 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004263 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4264 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004265 }
4266
4267 /**
4268 * Return the information of the ongoing legacy VPN. This method is used
4269 * by VpnSettings and not available in ConnectivityManager. Permissions
4270 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004271 */
4272 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004273 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4274 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004275
Hugo Benichi20035e02017-04-26 14:53:28 +09004276 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004277 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004278 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004279 }
4280
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004281 /**
Varun Anand02c50ef2019-02-07 14:13:13 -08004282 * Return the information of all ongoing VPNs.
4283 *
4284 * <p>This method is used to update NetworkStatsService.
4285 *
4286 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004287 */
Varun Anand02c50ef2019-02-07 14:13:13 -08004288 private VpnInfo[] getAllVpnInfo() {
4289 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004290 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004291 if (mLockdownEnabled) {
4292 return new VpnInfo[0];
4293 }
4294
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004295 List<VpnInfo> infoList = new ArrayList<>();
4296 for (int i = 0; i < mVpns.size(); i++) {
4297 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4298 if (info != null) {
4299 infoList.add(info);
4300 }
4301 }
4302 return infoList.toArray(new VpnInfo[infoList.size()]);
4303 }
4304 }
4305
4306 /**
4307 * @return VPN information for accounting, or null if we can't retrieve all required
4308 * information, e.g primary underlying iface.
4309 */
4310 @Nullable
4311 private VpnInfo createVpnInfo(Vpn vpn) {
4312 VpnInfo info = vpn.getVpnInfo();
4313 if (info == null) {
4314 return null;
4315 }
4316 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4317 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4318 // the underlyingNetworks list.
4319 if (underlyingNetworks == null) {
4320 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4321 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4322 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4323 }
4324 } else if (underlyingNetworks.length > 0) {
4325 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4326 if (linkProperties != null) {
4327 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4328 }
4329 }
4330 return info.primaryUnderlyingIface == null ? null : info;
4331 }
4332
4333 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004334 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4335 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004336 * Permissions are checked in Vpn class.
4337 * @hide
4338 */
4339 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004340 public VpnConfig getVpnConfig(int userId) {
4341 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004342 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004343 Vpn vpn = mVpns.get(userId);
4344 if (vpn != null) {
4345 return vpn.getVpnConfig();
4346 } else {
4347 return null;
4348 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004349 }
4350 }
4351
Chalard Jean6b65ec72018-05-18 22:02:56 +09004352 /**
4353 * Ask all VPN objects to recompute and update their capabilities.
4354 *
4355 * When underlying networks change, VPNs may have to update capabilities to reflect things
4356 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4357 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4358 * handler thread through their agent, this is asynchronous. When the capabilities objects
4359 * are computed they will be up-to-date as they are computed synchronously from here and
4360 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004361 */
4362 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004363 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004364 synchronized (mVpns) {
4365 for (int i = 0; i < mVpns.size(); i++) {
4366 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004367 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4368 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004369 }
4370 }
4371 }
4372
Varun Anand4fa80e82019-02-06 10:13:38 -08004373 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4374 ensureRunningOnConnectivityServiceThread();
4375 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4376 if (vpnNai == null || nc == null) {
4377 return;
4378 }
4379 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4380 }
4381
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004382 @Override
4383 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004384 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4385 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4386 return false;
4387 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004388
Hugo Benichi69744342017-11-27 10:57:16 +09004389 synchronized (mVpns) {
4390 // Tear down existing lockdown if profile was removed
4391 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4392 if (mLockdownEnabled) {
4393 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4394 if (profileTag == null) {
4395 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4396 return false;
4397 }
4398 String profileName = new String(profileTag);
4399 final VpnProfile profile = VpnProfile.decode(
4400 profileName, mKeyStore.get(Credentials.VPN + profileName));
4401 if (profile == null) {
4402 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4403 setLockdownTracker(null);
4404 return true;
4405 }
4406 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004407 Vpn vpn = mVpns.get(user);
4408 if (vpn == null) {
4409 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4410 return false;
4411 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004412 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004413 } else {
4414 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004415 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004416 }
4417
4418 return true;
4419 }
4420
4421 /**
4422 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4423 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4424 */
Hugo Benichi69744342017-11-27 10:57:16 +09004425 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004426 private void setLockdownTracker(LockdownVpnTracker tracker) {
4427 // Shutdown any existing tracker
4428 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004429 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4430 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004431 mLockdownTracker = null;
4432 if (existing != null) {
4433 existing.shutdown();
4434 }
4435
Robin Leec3736bc2017-03-10 16:19:54 +00004436 if (tracker != null) {
4437 mLockdownTracker = tracker;
4438 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004439 }
4440 }
4441
Hugo Benichi69744342017-11-27 10:57:16 +09004442 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004443 private void throwIfLockdownEnabled() {
4444 if (mLockdownEnabled) {
4445 throw new IllegalStateException("Unavailable in lockdown mode");
4446 }
4447 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004448
Robin Lee244ce8e2016-01-05 18:03:46 +00004449 /**
Robin Lee17e61832016-05-09 13:46:28 +01004450 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4451 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004452 *
Robin Lee17e61832016-05-09 13:46:28 +01004453 * @return {@code true} if the service was started, the service was already connected, or there
4454 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004455 */
Robin Lee17e61832016-05-09 13:46:28 +01004456 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004457 synchronized (mVpns) {
4458 Vpn vpn = mVpns.get(userId);
4459 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004460 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004461 // exists already.
4462 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4463 return false;
4464 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004465
Robin Lee812800c2016-05-13 15:38:08 +01004466 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004467 }
4468 }
4469
4470 @Override
Charles He36738632017-05-15 17:07:18 +01004471 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4472 enforceSettingsPermission();
4473 enforceCrossUserPermission(userId);
4474
4475 synchronized (mVpns) {
4476 Vpn vpn = mVpns.get(userId);
4477 if (vpn == null) {
4478 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4479 return false;
4480 }
4481 return vpn.isAlwaysOnPackageSupported(packageName);
4482 }
4483 }
4484
4485 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004486 public boolean setAlwaysOnVpnPackage(
4487 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4488 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004489 enforceCrossUserPermission(userId);
4490
Robin Lee244ce8e2016-01-05 18:03:46 +00004491 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004492 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4493 if (LockdownVpnTracker.isEnabled()) {
4494 return false;
4495 }
4496
Robin Lee244ce8e2016-01-05 18:03:46 +00004497 Vpn vpn = mVpns.get(userId);
4498 if (vpn == null) {
4499 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4500 return false;
4501 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004502 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004503 return false;
4504 }
Robin Lee17e61832016-05-09 13:46:28 +01004505 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004506 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004507 return false;
4508 }
4509 }
4510 return true;
4511 }
4512
4513 @Override
4514 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004515 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004516 enforceCrossUserPermission(userId);
4517
4518 synchronized (mVpns) {
4519 Vpn vpn = mVpns.get(userId);
4520 if (vpn == null) {
4521 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4522 return null;
4523 }
4524 return vpn.getAlwaysOnPackage();
4525 }
4526 }
4527
Wink Savilleab9321d2013-06-29 21:10:57 -07004528 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004529 public boolean isVpnLockdownEnabled(int userId) {
4530 enforceControlAlwaysOnVpnPermission();
4531 enforceCrossUserPermission(userId);
4532
4533 synchronized (mVpns) {
4534 Vpn vpn = mVpns.get(userId);
4535 if (vpn == null) {
4536 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4537 return false;
4538 }
4539 return vpn.getLockdown();
4540 }
4541 }
4542
4543 @Override
4544 public List<String> getVpnLockdownWhitelist(int userId) {
4545 enforceControlAlwaysOnVpnPermission();
4546 enforceCrossUserPermission(userId);
4547
4548 synchronized (mVpns) {
4549 Vpn vpn = mVpns.get(userId);
4550 if (vpn == null) {
4551 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4552 return null;
4553 }
4554 return vpn.getLockdownWhitelist();
4555 }
4556 }
4557
4558 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004559 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004560 // TODO: Remove? Any reason to trigger a provisioning check?
4561 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004562 }
4563
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004564 /** Location to an updatable file listing carrier provisioning urls.
4565 * An example:
4566 *
4567 * <?xml version="1.0" encoding="utf-8"?>
4568 * <provisioningUrls>
4569 * <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 -07004570 * </provisioningUrls>
4571 */
4572 private static final String PROVISIONING_URL_PATH =
4573 "/data/misc/radio/provisioning_urls.xml";
4574 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004575
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004576 /** XML tag for root element. */
4577 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4578 /** XML tag for individual url */
4579 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004580 /** XML attribute for mcc */
4581 private static final String ATTR_MCC = "mcc";
4582 /** XML attribute for mnc */
4583 private static final String ATTR_MNC = "mnc";
4584
Paul Jensen434dde82015-06-11 09:43:30 -04004585 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004586 FileReader fileReader = null;
4587 XmlPullParser parser = null;
4588 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004589
4590 try {
4591 fileReader = new FileReader(mProvisioningUrlFile);
4592 parser = Xml.newPullParser();
4593 parser.setInput(fileReader);
4594 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4595
4596 while (true) {
4597 XmlUtils.nextElement(parser);
4598
4599 String element = parser.getName();
4600 if (element == null) break;
4601
Paul Jensen434dde82015-06-11 09:43:30 -04004602 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004603 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4604 try {
4605 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4606 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4607 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4608 parser.next();
4609 if (parser.getEventType() == XmlPullParser.TEXT) {
4610 return parser.getText();
4611 }
4612 }
4613 }
4614 } catch (NumberFormatException e) {
4615 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4616 }
4617 }
4618 }
4619 return null;
4620 } catch (FileNotFoundException e) {
4621 loge("Carrier Provisioning Urls file not found");
4622 } catch (XmlPullParserException e) {
4623 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4624 } catch (IOException e) {
4625 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4626 } finally {
4627 if (fileReader != null) {
4628 try {
4629 fileReader.close();
4630 } catch (IOException e) {}
4631 }
4632 }
4633 return null;
4634 }
4635
Wink Saville42d4f082013-07-20 20:31:59 -07004636 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004637 public String getMobileProvisioningUrl() {
4638 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004639 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004640 if (TextUtils.isEmpty(url)) {
4641 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004642 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004643 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004644 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004645 }
Wink Saville8cf35602013-07-10 23:00:07 -07004646 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004647 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004648 String phoneNumber = mTelephonyManager.getLine1Number();
4649 if (TextUtils.isEmpty(phoneNumber)) {
4650 phoneNumber = "0000000000";
4651 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004652 url = String.format(url,
4653 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4654 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004655 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004656 }
4657
Wink Savilleab9321d2013-06-29 21:10:57 -07004658 return url;
4659 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004660
Wink Saville948282b2013-08-29 08:55:16 -07004661 @Override
4662 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004663 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004664 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004665 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4666 return;
4667 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004668 final long ident = Binder.clearCallingIdentity();
4669 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004670 // Concatenate the range of types onto the range of NetIDs.
4671 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4672 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004673 } finally {
4674 Binder.restoreCallingIdentity(ident);
4675 }
Wink Saville948282b2013-08-29 08:55:16 -07004676 }
Wink Saville7788c612013-08-29 14:57:08 -07004677
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004678 @Override
4679 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004680 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004681 final long ident = Binder.clearCallingIdentity();
4682 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004683 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004684 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004685 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4686 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004687 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004688 } finally {
4689 Binder.restoreCallingIdentity(ident);
4690 }
4691 }
4692
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004693 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004694 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004695 Vpn userVpn = mVpns.get(userId);
4696 if (userVpn != null) {
4697 loge("Starting user already has a VPN");
4698 return;
4699 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004700 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004701 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004702 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4703 updateLockdownVpn();
4704 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004705 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004706 }
4707
4708 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004709 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004710 Vpn userVpn = mVpns.get(userId);
4711 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004712 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004713 return;
4714 }
Robin Lee17e61832016-05-09 13:46:28 +01004715 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004716 mVpns.delete(userId);
4717 }
4718 }
4719
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004720 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004721 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004722 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004723 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004724 final int vpnsSize = mVpns.size();
4725 for (int i = 0; i < vpnsSize; i++) {
4726 Vpn vpn = mVpns.valueAt(i);
4727 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004728 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4729 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004730 }
4731 }
4732 }
4733
4734 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004735 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004736 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004737 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004738 final int vpnsSize = mVpns.size();
4739 for (int i = 0; i < vpnsSize; i++) {
4740 Vpn vpn = mVpns.valueAt(i);
4741 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004742 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4743 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004744 }
4745 }
4746 }
4747
junyulai2454b692018-11-01 17:16:31 +08004748 private void onPackageAdded(String packageName, int uid) {
4749 if (TextUtils.isEmpty(packageName) || uid < 0) {
4750 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4751 return;
4752 }
4753 mPermissionMonitor.onPackageAdded(packageName, uid);
4754 }
4755
junyulaiefb04d32018-11-12 22:39:30 +08004756 private void onPackageReplaced(String packageName, int uid) {
4757 if (TextUtils.isEmpty(packageName) || uid < 0) {
4758 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4759 return;
4760 }
4761 final int userId = UserHandle.getUserId(uid);
4762 synchronized (mVpns) {
4763 final Vpn vpn = mVpns.get(userId);
4764 if (vpn == null) {
4765 return;
4766 }
4767 // Legacy always-on VPN won't be affected since the package name is not set.
4768 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4769 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4770 + userId);
4771 vpn.startAlwaysOnVpn();
4772 }
4773 }
4774 }
4775
4776 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004777 if (TextUtils.isEmpty(packageName) || uid < 0) {
4778 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4779 return;
4780 }
4781 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004782
4783 final int userId = UserHandle.getUserId(uid);
4784 synchronized (mVpns) {
4785 final Vpn vpn = mVpns.get(userId);
4786 if (vpn == null) {
4787 return;
4788 }
4789 // Legacy always-on VPN won't be affected since the package name is not set.
4790 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4791 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4792 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004793 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004794 }
4795 }
junyulai2454b692018-11-01 17:16:31 +08004796 }
4797
Robin Lee89e7a692016-02-29 14:38:17 +00004798 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004799 synchronized (mVpns) {
4800 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4801 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4802 updateLockdownVpn();
4803 } else {
4804 startAlwaysOnVpn(userId);
4805 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004806 }
4807 }
4808
junyulai2454b692018-11-01 17:16:31 +08004809 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004810 @Override
4811 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004812 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004813 final String action = intent.getAction();
4814 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004815 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4816 final Uri packageData = intent.getData();
4817 final String packageName =
4818 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004819 if (userId == UserHandle.USER_NULL) return;
4820
Robin Lee323f29d2016-05-04 16:38:06 +01004821 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004822 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004823 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004824 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004825 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4826 onUserAdded(userId);
4827 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4828 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004829 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4830 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004831 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4832 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004833 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4834 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004835 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004836 final boolean isReplacing = intent.getBooleanExtra(
4837 Intent.EXTRA_REPLACING, false);
4838 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004839 }
4840 }
4841 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004842
Robin Lee95204e02017-01-27 11:59:22 +00004843 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4844 @Override
4845 public void onReceive(Context context, Intent intent) {
4846 // Try creating lockdown tracker, since user present usually means
4847 // unlocked keystore.
4848 updateLockdownVpn();
4849 mContext.unregisterReceiver(this);
4850 }
4851 };
4852
Chalard Jean4133a122018-06-04 13:33:12 +09004853 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4854 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004855
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004856 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4857 // Map from UID to number of NetworkRequests that UID has filed.
4858 @GuardedBy("mUidToNetworkRequestCount")
4859 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4860
Robert Greenwalta67be032014-05-16 15:49:14 -07004861 private static class NetworkFactoryInfo {
4862 public final String name;
4863 public final Messenger messenger;
4864 public final AsyncChannel asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004865 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004866
Chalard Jean08577fc2018-05-02 21:14:54 +09004867 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4868 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004869 this.name = name;
4870 this.messenger = messenger;
4871 this.asyncChannel = asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004872 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004873 }
4874 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004875
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004876 private void ensureNetworkRequestHasType(NetworkRequest request) {
4877 if (request.type == NetworkRequest.Type.NONE) {
4878 throw new IllegalArgumentException(
4879 "All NetworkRequests in ConnectivityService must have a type");
4880 }
4881 }
4882
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004883 /**
4884 * Tracks info about the requester.
4885 * Also used to notice when the calling process dies so we can self-expire
4886 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004887 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004888 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004889 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004890 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004891 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004892 final int mPid;
4893 final int mUid;
4894 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004895
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004896 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004897 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004898 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004899 mPendingIntent = pi;
4900 messenger = null;
4901 mBinder = null;
4902 mPid = getCallingPid();
4903 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004904 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004905 }
4906
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004907 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004908 super();
4909 messenger = m;
4910 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004911 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004912 mBinder = binder;
4913 mPid = getCallingPid();
4914 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004915 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004916 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004917
4918 try {
4919 mBinder.linkToDeath(this, 0);
4920 } catch (RemoteException e) {
4921 binderDied();
4922 }
4923 }
4924
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004925 private void enforceRequestCountLimit() {
4926 synchronized (mUidToNetworkRequestCount) {
4927 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4928 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004929 throw new ServiceSpecificException(
4930 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004931 }
4932 mUidToNetworkRequestCount.put(mUid, networkRequests);
4933 }
4934 }
4935
Robert Greenwalt9258c642014-03-26 16:47:06 -07004936 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004937 if (mBinder != null) {
4938 mBinder.unlinkToDeath(this, 0);
4939 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004940 }
4941
4942 public void binderDied() {
4943 log("ConnectivityService NetworkRequestInfo binderDied(" +
4944 request + ", " + mBinder + ")");
4945 releaseNetworkRequest(request);
4946 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004947
4948 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004949 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004950 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004951 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004952 }
4953
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004954 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4955 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4956 if (badCapability != null) {
4957 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004958 }
4959 }
4960
Chalard Jeanb03a6222018-04-11 21:09:10 +09004961 // This checks that the passed capabilities either do not request a specific SSID, or the
4962 // calling app has permission to do so.
4963 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4964 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004965 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004966 throw new SecurityException("Insufficient permissions to request a specific SSID");
4967 }
4968 }
4969
Erik Kline9d598e12015-07-13 16:37:51 +09004970 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004971 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004972 synchronized (nai) {
4973 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4974 if (nri.request.networkCapabilities.hasSignalStrength() &&
4975 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4976 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4977 }
4978 }
4979 }
Chalard Jean4133a122018-06-04 13:33:12 +09004980 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004981 }
4982
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004983 private void updateSignalStrengthThresholds(
4984 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4985 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004986 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004987 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4988
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004989 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004990 String detail;
4991 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4992 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4993 } else {
4994 detail = reason;
4995 }
4996 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4997 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4998 }
4999
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005000 nai.asyncChannel.sendMessage(
5001 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09005002 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005003 }
5004
Etan Cohen859748f2017-04-03 17:42:34 -07005005 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5006 if (nc == null) {
5007 return;
5008 }
5009 NetworkSpecifier ns = nc.getNetworkSpecifier();
5010 if (ns == null) {
5011 return;
5012 }
5013 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5014 ns.assertValidFromUid(Binder.getCallingUid());
5015 }
5016
Robert Greenwalt9258c642014-03-26 16:47:06 -07005017 @Override
5018 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005019 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005020 final NetworkRequest.Type type = (networkCapabilities == null)
5021 ? NetworkRequest.Type.TRACK_DEFAULT
5022 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005023 // If the requested networkCapabilities is null, take them instead from
5024 // the default network request. This allows callers to keep track of
5025 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005026 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005027 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005028 enforceAccessPermission();
5029 } else {
5030 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5031 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005032 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5033 // of the app when the request is filed, but we never change the request if the app
5034 // changes network state. http://b/29964605
5035 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005036 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005037 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005038 ensureSufficientPermissionsForRequest(networkCapabilities,
5039 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005040 // Set the UID range for this request to the single UID of the requester, or to an empty
5041 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005042 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5043 // are no visible methods to set the UIDs, an app could use reflection to try and get
5044 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005045 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005046
Etan Cohenba07c8c2017-02-05 10:42:27 -08005047 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005048 throw new IllegalArgumentException("Bad timeout specified");
5049 }
Etan Cohen859748f2017-04-03 17:42:34 -07005050 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005051
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005052 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005053 nextNetworkRequestId(), type);
5054 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005055 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005056
5057 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005058 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005059 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005060 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005061 }
5062 return networkRequest;
5063 }
5064
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005065 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005066 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005067 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005068 } else {
5069 enforceChangePermission();
5070 }
5071 }
5072
fenglub15e72b2015-03-20 11:29:56 -07005073 @Override
fengludb571472015-04-21 17:12:05 -07005074 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005075 enforceAccessPermission();
5076 NetworkAgentInfo nai = null;
5077 if (network == null) {
5078 return false;
5079 }
5080 synchronized (mNetworkForNetId) {
5081 nai = mNetworkForNetId.get(network.netId);
5082 }
5083 if (nai != null) {
5084 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005085 synchronized (mBandwidthRequests) {
5086 final int uid = Binder.getCallingUid();
5087 Integer uidReqs = mBandwidthRequests.get(uid);
5088 if (uidReqs == null) {
5089 uidReqs = new Integer(0);
5090 }
5091 mBandwidthRequests.put(uid, ++uidReqs);
5092 }
fenglub15e72b2015-03-20 11:29:56 -07005093 return true;
5094 }
5095 return false;
5096 }
5097
Felipe Lemeee27cab2016-06-20 16:36:29 -07005098 private boolean isSystem(int uid) {
5099 return uid < Process.FIRST_APPLICATION_UID;
5100 }
fenglub15e72b2015-03-20 11:29:56 -07005101
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005102 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005103 final int uid = Binder.getCallingUid();
5104 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005105 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005106 return;
5107 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005108 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5109 // Policy already enforced.
5110 return;
5111 }
5112 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5113 // If UID is restricted, don't allow them to bring up metered APNs.
5114 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005115 }
5116 }
5117
Robert Greenwalt9258c642014-03-26 16:47:06 -07005118 @Override
5119 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5120 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005121 checkNotNull(operation, "PendingIntent cannot be null.");
5122 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5123 enforceNetworkRequestPermissions(networkCapabilities);
5124 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005125 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005126 ensureSufficientPermissionsForRequest(networkCapabilities,
5127 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005128 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005129 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005130
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005131 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005132 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5133 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005134 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005135 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5136 nri));
5137 return networkRequest;
5138 }
5139
Jeremy Joslin79294842014-12-03 17:15:28 -08005140 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5141 mHandler.sendMessageDelayed(
5142 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5143 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5144 }
5145
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005146 @Override
5147 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005148 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005149 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5150 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005151 }
5152
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005153 // In order to implement the compatibility measure for pre-M apps that call
5154 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5155 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5156 // This ensures it has permission to do so.
5157 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5158 if (nc == null) {
5159 return false;
5160 }
5161 int[] transportTypes = nc.getTransportTypes();
5162 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5163 return false;
5164 }
5165 try {
5166 mContext.enforceCallingOrSelfPermission(
5167 android.Manifest.permission.ACCESS_WIFI_STATE,
5168 "ConnectivityService");
5169 } catch (SecurityException e) {
5170 return false;
5171 }
5172 return true;
5173 }
5174
Robert Greenwalt9258c642014-03-26 16:47:06 -07005175 @Override
5176 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5177 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005178 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5179 enforceAccessPermission();
5180 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005181
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005182 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005183 ensureSufficientPermissionsForRequest(networkCapabilities,
5184 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005185 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005186 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5187 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5188 // onLost and onAvailable callbacks when networks move in and out of the background.
5189 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5190 // can't request networks.
5191 restrictBackgroundRequestForCaller(nc);
5192 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005193
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005194 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005195 NetworkRequest.Type.LISTEN);
5196 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005197 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005198
5199 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5200 return networkRequest;
5201 }
5202
5203 @Override
5204 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5205 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005206 checkNotNull(operation, "PendingIntent cannot be null.");
5207 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5208 enforceAccessPermission();
5209 }
Etan Cohen859748f2017-04-03 17:42:34 -07005210 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005211 ensureSufficientPermissionsForRequest(networkCapabilities,
5212 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005213
Chalard Jeandda156a2018-01-10 21:19:32 +09005214 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005215 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005216
5217 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005218 NetworkRequest.Type.LISTEN);
5219 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005220 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005221
5222 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005223 }
5224
Erik Klineacdd6392016-07-07 16:50:58 +09005225 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005226 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005227 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005228 mHandler.sendMessage(mHandler.obtainMessage(
5229 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005230 }
5231
5232 @Override
Chalard Jean08577fc2018-05-02 21:14:54 +09005233 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005234 enforceConnectivityInternalPermission();
Chalard Jean08577fc2018-05-02 21:14:54 +09005235 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5236 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005237 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean08577fc2018-05-02 21:14:54 +09005238 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005239 }
5240
Robert Greenwalta67be032014-05-16 15:49:14 -07005241 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005242 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005243 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5244 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5245 }
5246
5247 @Override
5248 public void unregisterNetworkFactory(Messenger messenger) {
5249 enforceConnectivityInternalPermission();
5250 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5251 }
5252
5253 private void handleUnregisterNetworkFactory(Messenger messenger) {
5254 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5255 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005256 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005257 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005258 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005259 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005260 }
5261
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262 /**
5263 * NetworkAgentInfo supporting a request by requestId.
5264 * These have already been vetted (their Capabilities satisfy the request)
5265 * and the are the highest scored network available.
5266 * the are keyed off the Requests requestId.
5267 */
Hugo Benichicd952782017-09-20 11:20:14 +09005268 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5269 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005270 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005271
Paul Jensen31a94f42015-02-13 14:18:39 -05005272 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5273 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005274 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005275 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5276 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5277 // there may not be a strict 1:1 correlation between the two.
5278 @GuardedBy("mNetworkForNetId")
5279 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005280
Robert Greenwalt7b816022014-04-18 15:25:25 -07005281 // NetworkAgentInfo keyed off its connecting messenger
5282 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005283 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005284 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005285
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005286 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005287 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005288
Paul Jensen2c311d62014-11-17 12:34:51 -05005289 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005290 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005291
Erik Klineda4bfa82015-04-30 12:58:40 +09005292 // Request used to optionally keep mobile data active even when higher
5293 // priority networks like Wi-Fi are active.
5294 private final NetworkRequest mDefaultMobileDataRequest;
5295
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005296 // Request used to optionally keep wifi data active even when higher
5297 // priority networks like ethernet are active.
5298 private final NetworkRequest mDefaultWifiRequest;
5299
Hugo Benichicd952782017-09-20 11:20:14 +09005300 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5301 synchronized (mNetworkForRequestId) {
5302 return mNetworkForRequestId.get(requestId);
5303 }
5304 }
5305
5306 private void clearNetworkForRequest(int requestId) {
5307 synchronized (mNetworkForRequestId) {
5308 mNetworkForRequestId.remove(requestId);
5309 }
5310 }
5311
5312 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5313 synchronized (mNetworkForRequestId) {
5314 mNetworkForRequestId.put(requestId, nai);
5315 }
5316 }
5317
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005318 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005319 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005320 }
5321
Varun Anand4fa80e82019-02-06 10:13:38 -08005322 @Nullable
5323 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5324 return nai != null ? nai.network : null;
5325 }
5326
5327 private void ensureRunningOnConnectivityServiceThread() {
5328 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5329 throw new IllegalStateException(
5330 "Not running on ConnectivityService thread: "
5331 + Thread.currentThread().getName());
5332 }
5333 }
5334
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005335 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005336 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005337 }
5338
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005339 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5340 return nri.request.requestId == mDefaultRequest.requestId;
5341 }
5342
Chalard Jean08577fc2018-05-02 21:14:54 +09005343 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5344 // changes that would conflict throughout the automerger graph. Having this method temporarily
5345 // helps with the process of going through with all these dependent changes across the entire
5346 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005347 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005348 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005349 int currentScore, NetworkMisc networkMisc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005350 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5351 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5352 }
5353
5354 /**
5355 * Register a new agent with ConnectivityService to handle a network.
5356 *
5357 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5358 * @param networkInfo the initial info associated with this network. It can be updated later :
5359 * see {@link #updateNetworkInfo}.
5360 * @param linkProperties the initial link properties of this network. They can be updated
5361 * later : see {@link #updateLinkProperties}.
5362 * @param networkCapabilities the initial capabilites of this network. They can be updated
5363 * later : see {@link #updateNetworkCapabilities}.
5364 * @param currentScore the initial score of the network. See
5365 * {@link NetworkAgentInfo#getCurrentScore}.
5366 * @param networkMisc metadata about the network. This is never updated.
5367 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5368 */
5369 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5370 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5371 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005372 enforceConnectivityInternalPermission();
5373
Rubin Xu1bb5c082017-09-05 18:40:49 +01005374 LinkProperties lp = new LinkProperties(linkProperties);
5375 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005376 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5377 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005378 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005379 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005380 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean08577fc2018-05-02 21:14:54 +09005381 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5382 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005383 // Make sure the network capabilities reflect what the agent info says.
5384 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005385 final String extraInfo = networkInfo.getExtraInfo();
5386 final String name = TextUtils.isEmpty(extraInfo)
5387 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005388 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005389 final long token = Binder.clearCallingIdentity();
5390 try {
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005391 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +09005392 toStableParcelable(nai.network), name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005393 } finally {
5394 Binder.restoreCallingIdentity(token);
5395 }
5396 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5397 // If the network disconnects or sends any other event before that, messages are deferred by
5398 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5399 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005400 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005401 }
5402
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005403 @VisibleForTesting
5404 protected NetworkStackClient getNetworkStack() {
5405 return NetworkStackClient.getInstance();
5406 }
5407
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005408 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5409 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005410 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005411 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005412 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005413 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005414 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005415 synchronized (this) {
5416 if (mSystemReady) {
5417 try {
5418 networkMonitor.notifySystemReady();
5419 } catch (RemoteException e) {
5420 e.rethrowFromSystemServer();
5421 }
5422 }
5423 }
5424
5425 try {
5426 networkMonitor.start();
5427 } catch (RemoteException e) {
5428 e.rethrowFromSystemServer();
5429 }
Erik Klinee5dac902018-03-04 21:01:01 +09005430 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5431 NetworkInfo networkInfo = nai.networkInfo;
5432 nai.networkInfo = null;
5433 updateNetworkInfo(nai, networkInfo);
5434 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005435 }
5436
lucaslin25a4ec32018-11-28 12:51:55 +08005437 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5438 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005439 int netId = networkAgent.network.netId;
5440
Lorenzo Colittidf595632019-01-08 14:43:37 +09005441 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5442 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5443 // are accurate.
5444 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005445
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005446 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005447 updateMtu(newLp, oldLp);
5448 // TODO - figure out what to do for clat
5449// for (LinkProperties lp : newLp.getStackedLinks()) {
5450// updateMtu(lp, null);
5451// }
lucaslin041a1af2018-11-28 19:27:52 +08005452 if (isDefaultNetwork(networkAgent)) {
5453 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5454 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005455
Erik Kline94887872016-04-05 13:30:49 +09005456 updateRoutes(newLp, oldLp, netId);
5457 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005458 // Make sure LinkProperties represents the latest private DNS status.
5459 // This does not need to be done before updateDnses because the
5460 // LinkProperties are not the source of the private DNS configuration.
5461 // updateDnses will fetch the private DNS configuration from DnsManager.
5462 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005463
Paul Jensene0bef712014-12-10 15:12:18 -05005464 if (isDefaultNetwork(networkAgent)) {
5465 handleApplyDefaultProxy(newLp.getHttpProxy());
5466 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005467 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005468 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005469 // TODO - move this check to cover the whole function
5470 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005471 synchronized (networkAgent) {
5472 networkAgent.linkProperties = newLp;
5473 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005474 // Start or stop DNS64 detection and 464xlat according to network state.
5475 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005476 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005477 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005478 try {
5479 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5480 } catch (RemoteException e) {
5481 e.rethrowFromSystemServer();
5482 }
lucaslin25a4ec32018-11-28 12:51:55 +08005483 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5484 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005485 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005486
5487 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005488 }
5489
Joel Scherpelz668370b2017-06-08 15:35:21 +09005490 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005491 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005492 // marks on unsupported interfaces is harmless.
5493 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5494 return;
5495 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005496
Joel Scherpelz668370b2017-06-08 15:35:21 +09005497 int mark = mContext.getResources().getInteger(
5498 com.android.internal.R.integer.config_networkWakeupPacketMark);
5499 int mask = mContext.getResources().getInteger(
5500 com.android.internal.R.integer.config_networkWakeupPacketMask);
5501
5502 // Mask/mark of zero will not detect anything interesting.
5503 // Don't install rules unless both values are nonzero.
5504 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005505 return;
5506 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005507
5508 final String prefix = "iface:" + iface;
5509 try {
5510 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005511 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005512 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005513 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005514 }
5515 } catch (Exception e) {
5516 loge("Exception modifying wakeup packet monitoring: " + e);
5517 }
5518
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005519 }
5520
5521 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5522 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005523 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005524 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5525 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005526 for (String iface : interfaceDiff.added) {
5527 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005528 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005529 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005530 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005531 } catch (Exception e) {
5532 loge("Exception adding interface: " + e);
5533 }
5534 }
5535 for (String iface : interfaceDiff.removed) {
5536 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005537 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005538 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005539 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005540 } catch (Exception e) {
5541 loge("Exception removing interface: " + e);
5542 }
5543 }
5544 }
5545
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005546 /**
5547 * Have netd update routes from oldLp to newLp.
5548 * @return true if routes changed between oldLp and newLp
5549 */
5550 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005551 // Compare the route diff to determine which routes should be added and removed.
5552 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5553 oldLp != null ? oldLp.getAllRoutes() : null,
5554 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005555
5556 // add routes before removing old in case it helps with continuous connectivity
5557
Chalard Jean4d660112018-06-04 16:52:49 +09005558 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005559 for (RouteInfo route : routeDiff.added) {
5560 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005561 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005562 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005563 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005564 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005565 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5566 loge("Exception in addRoute for non-gateway: " + e);
5567 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005568 }
5569 }
5570 for (RouteInfo route : routeDiff.added) {
5571 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005572 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005573 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005574 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005575 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005576 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5577 loge("Exception in addRoute for gateway: " + e);
5578 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005579 }
5580 }
5581
5582 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005583 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005584 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005585 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005586 } catch (Exception e) {
5587 loge("Exception in removeRoute: " + e);
5588 }
5589 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005590 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005591 }
Erik Kline41368502015-06-17 13:19:54 +09005592
Erik Kline94887872016-04-05 13:30:49 +09005593 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5594 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5595 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005596 }
Erik Kline94887872016-04-05 13:30:49 +09005597
Erik Kline1742fe12017-12-13 19:40:49 +09005598 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5599 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5600
Erik Klinea24d4592018-01-11 21:07:29 +09005601 if (DBG) {
5602 final Collection<InetAddress> dnses = newLp.getDnsServers();
5603 log("Setting DNS servers for network " + netId + " to " + dnses);
5604 }
Erik Kline94887872016-04-05 13:30:49 +09005605 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005606 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005607 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005608 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005609 }
Erik Kline4edba012017-04-07 15:29:29 +09005610 }
5611
Luke Huang8a462ec2018-08-24 20:33:16 +08005612 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005613 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005614 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005615 }
5616 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005617 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005618 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005619 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005620 }
5621
Paul Jensen3d194ea2015-06-16 14:27:36 -04005622 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005623 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5624 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5625 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005626 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005627 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005628 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005629 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5630 // causing a connect/teardown loop.
5631 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5632 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005633 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005634 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005635 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5636 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005637 // does not cause any request (that is not a listen) currently matching that agent to
5638 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005639 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005640 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005641 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005642 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005643 }
5644
Paul Jensen3d194ea2015-06-16 14:27:36 -04005645 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005646 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005647 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005648 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005649 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005650 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005651 }
Paul Jensene0988542015-06-25 15:30:08 -04005652 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005653 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005654 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005655 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005656 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005657 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005658 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005659 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005660 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005661 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005662 if (nai.isSuspended()) {
5663 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5664 } else {
5665 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5666 }
lucasline252a742019-03-12 13:08:03 +08005667 if (nai.partialConnectivity) {
5668 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5669 } else {
5670 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5671 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005672
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005673 return newNc;
5674 }
5675
5676 /**
5677 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5678 *
5679 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5680 * capabilities we manage and store in {@code nai}, such as validated status and captive
5681 * portal status)
5682 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5683 * potentially triggers rematches.
5684 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5685 * change.)
5686 *
5687 * @param oldScore score of the network before any of the changes that prompted us
5688 * to call this function.
5689 * @param nai the network having its capabilities updated.
5690 * @param nc the new network capabilities.
5691 */
5692 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5693 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5694
5695 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005696
Luke Huang8a462ec2018-08-24 20:33:16 +08005697 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5698 final int newPermission = getNetworkPermission(newNc);
5699 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005700 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005701 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005702 } catch (RemoteException e) {
5703 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005704 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005705 }
5706
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005707 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005708 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005709 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005710 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005711 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005712
Chalard Jeanf213ca12018-01-16 18:43:05 +09005713 updateUids(nai, prevNc, newNc);
5714
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005715 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005716 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5717 // the change we're processing can't affect any requests, it can only affect the listens
5718 // on this network. We might have been called by rematchNetworkAndRequests when a
5719 // network changed foreground state.
5720 processListenRequests(nai, true);
5721 } else {
5722 // If the requestable capabilities have changed or the score changed, we can't have been
5723 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005724 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005725 try {
5726 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5727 } catch (RemoteException e) {
5728 e.rethrowFromSystemServer();
5729 }
Paul Jensene0988542015-06-25 15:30:08 -04005730 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005731 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005732
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005733 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005734 final boolean oldMetered = prevNc.isMetered();
5735 final boolean newMetered = newNc.isMetered();
5736 final boolean meteredChanged = oldMetered != newMetered;
5737
5738 if (meteredChanged) {
5739 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5740 mRestrictBackground);
5741 }
5742
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005743 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005744 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005745
5746 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005747 if (meteredChanged || roamingChanged) {
5748 notifyIfacesChangedForNetworkStats();
5749 }
5750 }
5751
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005752 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005753 // Tell VPNs about updated capabilities, since they may need to
5754 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005755 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005756 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005757 }
5758
Chalard Jeanf213ca12018-01-16 18:43:05 +09005759 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5760 NetworkCapabilities newNc) {
5761 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5762 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5763 if (null == prevRanges) prevRanges = new ArraySet<>();
5764 if (null == newRanges) newRanges = new ArraySet<>();
5765 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5766
5767 prevRanges.removeAll(newRanges);
5768 newRanges.removeAll(prevRangesCopy);
5769
5770 try {
5771 if (!newRanges.isEmpty()) {
5772 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5773 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005774 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005775 }
5776 if (!prevRanges.isEmpty()) {
5777 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5778 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005779 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005780 }
5781 } catch (Exception e) {
5782 // Never crash!
5783 loge("Exception in updateUids: " + e);
5784 }
5785 }
5786
Hugo Benichief502882017-09-01 01:23:32 +00005787 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005788 ensureRunningOnConnectivityServiceThread();
5789
Erik Kline736353a2018-03-21 07:18:33 -07005790 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005791 // Ignore updates for disconnected networks
5792 return;
5793 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005794 // newLp is already a defensive copy.
5795 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005796 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005797 log("Update of LinkProperties for " + nai.name() +
5798 "; created=" + nai.created +
5799 "; everConnected=" + nai.everConnected);
5800 }
lucaslin25a4ec32018-11-28 12:51:55 +08005801 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005802 }
5803
Paul Jensenc8b9a742014-09-30 15:37:41 -04005804 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005805 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5806 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005807 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005808 if (nr.isListen()) continue;
Chalard Jean08577fc2018-05-02 21:14:54 +09005809 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005810 }
5811 }
5812
Chalard Jean08577fc2018-05-02 21:14:54 +09005813 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5814 int score = 0;
5815 int serial = 0;
5816 if (nai != null) {
5817 score = nai.getCurrentScore();
5818 serial = nai.factorySerialNumber;
5819 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005820 if (VDBG || DDBG){
5821 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5822 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005823 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005824 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5825 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005826 }
5827 }
5828
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005829 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5830 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005831 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005832 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005833 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5834 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005835 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005836 sendIntent(nri.mPendingIntent, intent);
5837 }
5838 // else not handled
5839 }
5840
5841 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5842 mPendingIntentWakeLock.acquire();
5843 try {
5844 if (DBG) log("Sending " + pendingIntent);
5845 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5846 } catch (PendingIntent.CanceledException e) {
5847 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5848 mPendingIntentWakeLock.release();
5849 releasePendingNetworkRequest(pendingIntent);
5850 }
5851 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5852 }
5853
5854 @Override
5855 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5856 String resultData, Bundle resultExtras) {
5857 if (DBG) log("Finished sending " + pendingIntent);
5858 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005859 // Release with a delay so the receiving client has an opportunity to put in its
5860 // own request.
5861 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005862 }
5863
Chalard Jeanf19db372018-01-26 19:24:40 +09005864 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005865 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005866 if (nri.messenger == null) {
5867 return; // Default request has no msgr
5868 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005869 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005870 // TODO: check if defensive copies of data is needed.
5871 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005872 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005873 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5874 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005875 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005876 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005877 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005878 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5879 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005880 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005881 // For this notification, arg1 contains the blocked status.
5882 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005883 break;
5884 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005885 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005886 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005887 break;
5888 }
5889 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005890 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005891 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005892 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005893 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005894 break;
5895 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005896 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005897 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005898 break;
5899 }
junyulai05986c62018-08-07 19:50:45 +08005900 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005901 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005902 msg.arg1 = arg1;
5903 break;
5904 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005905 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005906 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005907 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005908 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005909 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005910 String notification = ConnectivityManager.getCallbackName(notificationType);
5911 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005912 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005913 nri.messenger.send(msg);
5914 } catch (RemoteException e) {
5915 // may occur naturally in the race of binder death.
5916 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5917 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005918 }
5919
Hugo Benichidba33db2017-03-23 22:40:44 +09005920 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5921 bundle.putParcelable(t.getClass().getSimpleName(), t);
5922 }
5923
Paul Jensenc8b9a742014-09-30 15:37:41 -04005924 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005925 if (nai.numRequestNetworkRequests() != 0) {
5926 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5927 NetworkRequest nr = nai.requestAt(i);
5928 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005929 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005930 loge("Dead network still had at least " + nr);
5931 break;
5932 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005933 }
5934 nai.asyncChannel.disconnect();
5935 }
5936
Robert Greenwalt7b816022014-04-18 15:25:25 -07005937 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5938 if (oldNetwork == null) {
5939 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5940 return;
5941 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005942 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005943
5944 // If we get here it means that the last linger timeout for this network expired. So there
5945 // must be no other active linger timers, and we must stop lingering.
5946 oldNetwork.clearLingerState();
5947
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005948 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005949 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005950 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005951 } else {
5952 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005953 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5954 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005955 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005956 }
5957
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005958 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005959 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005960
Paul Jensen27b02b72014-07-14 12:03:33 -04005961 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005962 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005963 } catch (Exception e) {
5964 loge("Exception setting default network :" + e);
5965 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005966
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005967 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005968 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005969 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005970 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005971 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005972 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5973 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005974 }
5975
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005976 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005977 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5978 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5979 NetworkRequest nr = nri.request;
5980 if (!nr.isListen()) continue;
5981 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5982 nai.removeRequest(nri.request.requestId);
5983 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5984 }
5985 }
5986
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005987 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005988 try {
5989 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5990 } catch (RemoteException e) {
5991 e.rethrowFromSystemServer();
5992 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005993 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5994 }
5995
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005996 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5997 NetworkRequest nr = nri.request;
5998 if (!nr.isListen()) continue;
5999 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
6000 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006001 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006002 }
6003 }
6004 }
6005
Paul Jensen2161a8e2014-09-11 11:00:39 -04006006 // Handles a network appearing or improving its score.
6007 //
6008 // - Evaluates all current NetworkRequests that can be
6009 // satisfied by newNetwork, and reassigns to newNetwork
6010 // any such requests for which newNetwork is the best.
6011 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006012 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006013 // needed. A network is needed if it is the best network for
6014 // one or more NetworkRequests, or if it is a VPN.
6015 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006016 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006017 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006018 //
6019 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6020 // networks that have no chance (i.e. even if validated)
6021 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006022 //
6023 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6024 // it does not remove NetworkRequests that other Networks could better satisfy.
6025 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6026 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6027 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006028 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006029 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006030 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6031 // performed to tear down unvalidated networks that have no chance (i.e. even if
6032 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006033 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006034 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006035 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006036 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006037 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006038 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006039
6040 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6041 final int score = newNetwork.getCurrentScore();
6042
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006043 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006044
Paul Jensen2161a8e2014-09-11 11:00:39 -04006045 // Find and migrate to this Network any NetworkRequests for
6046 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006047 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6048 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006049 NetworkCapabilities nc = newNetwork.networkCapabilities;
6050 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006051 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006052 // Process requests in the first pass and listens in the second pass. This allows us to
6053 // change a network's capabilities depending on which requests it has. This is only
6054 // correct if the change in capabilities doesn't affect whether the network satisfies
6055 // requests or not, and doesn't affect the network's score.
6056 if (nri.request.isListen()) continue;
6057
Hugo Benichicd952782017-09-20 11:20:14 +09006058 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006059 final boolean satisfies = newNetwork.satisfies(nri.request);
6060 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006061 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006062 log("Network " + newNetwork.name() + " was already satisfying" +
6063 " request " + nri.request.requestId + ". No change.");
6064 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006065 keep = true;
6066 continue;
6067 }
6068
6069 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006070 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006071 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006072 // next check if it's better than any current network we're using for
6073 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006074 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006075 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006076 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006077 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006078 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006079 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006080 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006081 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006082 if (VDBG || DDBG){
6083 log(" accepting network in place of " + currentNetwork.name());
6084 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006085 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006086 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006087 affectedNetworks.add(currentNetwork);
6088 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006089 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006090 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006091 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006092 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006093 if (!newNetwork.addRequest(nri.request)) {
6094 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6095 }
6096 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006097 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006098 // Tell NetworkFactories about the new score, so they can stop
6099 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006100 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006101 // network. Think about if there is a way to reduce this. Push
6102 // netid->request mapping to each factory?
Chalard Jean08577fc2018-05-02 21:14:54 +09006103 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006104 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006105 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006106 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006107 if (currentNetwork != null) {
6108 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6109 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006110 }
6111 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006112 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006113 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6114 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006115 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006116 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6117 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6118 // This means this code doesn't have to handle the case where "currentNetwork" no
6119 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6120 if (DBG) {
6121 log("Network " + newNetwork.name() + " stopped satisfying" +
6122 " request " + nri.request.requestId);
6123 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006124 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006125 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006126 clearNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09006127 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006128 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006129 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6130 newNetwork.name() +
6131 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006132 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006133 // TODO: Technically, sending CALLBACK_LOST here is
6134 // incorrect if there is a replacement network currently
6135 // connected that can satisfy nri, which is a request
6136 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006137 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6138 // so this code is only incorrect for a network that loses
6139 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006140 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006141 }
6142 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006143 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006144 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006145 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006146 makeDefault(newNetwork);
6147 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006148 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006149 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006150 // Have a new default network, release the transition wakelock in
6151 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006152 }
6153
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006154 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6155 Slog.wtf(TAG, String.format(
6156 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006157 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006158 }
6159 if (newNetwork.getCurrentScore() != score) {
6160 Slog.wtf(TAG, String.format(
6161 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006162 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006163 }
6164
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006165 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006166 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6167 // If the network went from background to foreground or vice versa, we need to update
6168 // its foreground state. It is safe to do this after rematching the requests because
6169 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6170 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006171 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006172 } else {
6173 processListenRequests(newNetwork, false);
6174 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006175
Paul Jensencf4c2c62015-07-01 14:16:32 -04006176 // do this after the default net is switched, but
6177 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006178 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006179
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006180 // Linger any networks that are no longer needed. This should be done after sending the
6181 // available callback for newNetwork.
6182 for (NetworkAgentInfo nai : affectedNetworks) {
6183 updateLingerState(nai, now);
6184 }
6185 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6186 // does not need to be done in any particular order.
6187 updateLingerState(newNetwork, now);
6188
Paul Jensencf4c2c62015-07-01 14:16:32 -04006189 if (isNewDefault) {
6190 // Maintain the illusion: since the legacy API only
6191 // understands one network at a time, we must pretend
6192 // that the current default network disconnected before
6193 // the new one connected.
6194 if (oldDefaultNetwork != null) {
6195 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6196 oldDefaultNetwork, true);
6197 }
6198 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6199 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6200 notifyLockdownVpn(newNetwork);
6201 }
6202
Robert Greenwalt7b816022014-04-18 15:25:25 -07006203 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006204 // Notify battery stats service about this network, both the normal
6205 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006206 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006207 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006208 final IBatteryStats bs = BatteryStatsService.getService();
6209 final int type = newNetwork.networkInfo.getType();
6210
6211 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6212 bs.noteNetworkInterfaceType(baseIface, type);
6213 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6214 final String stackedIface = stacked.getInterfaceName();
6215 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006216 }
6217 } catch (RemoteException ignored) {
6218 }
6219
Robert Greenwalt152ed372014-12-17 17:19:53 -08006220 // This has to happen after the notifyNetworkCallbacks as that tickles each
6221 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006222 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006223 // and will generally do a dns request so they can ensureRouteToHost and if
6224 // they do that before the callbacks happen they'll use the default network.
6225 //
6226 // TODO: Is there still a race here? We send the broadcast
6227 // after sending the callback, but if the app can receive the
6228 // broadcast before the callback, it might still break.
6229 //
6230 // This *does* introduce a race where if the user uses the new api
6231 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6232 // they may get old info. Reverse this after the old startUsing api is removed.
6233 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006234 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6235 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006236 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006237 // legacy type tracker filters out repeat adds
6238 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6239 }
6240 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006241
6242 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6243 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6244 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6245 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6246 if (newNetwork.isVPN()) {
6247 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6248 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006249 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006250 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6251 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006252 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006253 if (nai.getLingerExpiry() > 0) {
6254 // This network has active linger timers and no requests, but is not
6255 // lingering. Linger it.
6256 //
6257 // One way (the only way?) this can happen if this network is unvalidated
6258 // and became unneeded due to another network improving its score to the
6259 // point where this network will no longer be able to satisfy any requests
6260 // even if it validates.
6261 updateLingerState(nai, now);
6262 } else {
6263 if (DBG) log("Reaping " + nai.name());
6264 teardownUnneededNetwork(nai);
6265 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006266 }
6267 }
6268 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006269 }
6270
Paul Jensen1c7ba022015-06-16 14:27:36 -04006271 /**
6272 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6273 * being disconnected.
6274 * @param changed If only one Network's score or capabilities have been modified since the last
6275 * time this function was called, pass this Network in this argument, otherwise pass
6276 * null.
6277 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6278 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6279 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6280 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6281 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006282 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006283 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006284 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6285 // to avoid the slowness. It is not simply enough to process just "changed", for
6286 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006287 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006288
6289 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6290 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6291 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006292 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006293 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006294 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006295 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006296 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6297 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6298 // Rematch higher scoring networks first to prevent requests first matching a lower
6299 // scoring network and then a higher scoring network, which could produce multiple
6300 // callbacks and inadvertently unlinger networks.
6301 Arrays.sort(nais);
6302 for (NetworkAgentInfo nai : nais) {
6303 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006304 // Only reap the last time through the loop. Reaping before all rematching
6305 // is complete could incorrectly teardown a network that hasn't yet been
6306 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006307 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006308 : ReapUnvalidatedNetworks.REAP,
6309 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006310 }
6311 }
6312 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006313
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006314 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006315 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006316 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006317 // For now only update icons for default connection.
6318 // TODO: Update WiFi and cellular icons separately. b/17237507
6319 if (!isDefaultNetwork(nai)) return;
6320
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006321 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006322 // Don't repeat publish.
6323 if (newInetCondition == mDefaultInetConditionPublished) return;
6324
6325 mDefaultInetConditionPublished = newInetCondition;
6326 sendInetConditionBroadcast(nai.networkInfo);
6327 }
6328
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006329 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006330 synchronized (mVpns) {
6331 if (mLockdownTracker != null) {
6332 if (nai != null && nai.isVPN()) {
6333 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6334 } else {
6335 mLockdownTracker.onNetworkInfoChanged();
6336 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006337 }
6338 }
6339 }
6340
Robert Greenwalt7b816022014-04-18 15:25:25 -07006341 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006342 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006343 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006344 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006345 synchronized (networkAgent) {
6346 oldInfo = networkAgent.networkInfo;
6347 networkAgent.networkInfo = newInfo;
6348 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006349 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006350
Robert Greenwalt7b816022014-04-18 15:25:25 -07006351 if (DBG) {
6352 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6353 (oldInfo == null ? "null" : oldInfo.getState()) +
6354 " to " + state);
6355 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006356
Robin Lee585e2482016-05-01 23:00:00 +01006357 if (!networkAgent.created
6358 && (state == NetworkInfo.State.CONNECTED
6359 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006360
6361 // A network that has just connected has zero requests and is thus a foreground network.
6362 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6363
Robert Greenwalt7b816022014-04-18 15:25:25 -07006364 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006365 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006366 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006367 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006368 (networkAgent.networkMisc == null ||
6369 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006370 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006371 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006372 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006373 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006374 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006375 loge("Error creating network " + networkAgent.network.netId + ": "
6376 + e.getMessage());
6377 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006378 }
Paul Jenseneec75412014-08-04 12:21:19 -04006379 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006380 }
6381
6382 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6383 networkAgent.everConnected = true;
6384
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006385 if (networkAgent.linkProperties == null) {
6386 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6387 }
6388
Erik Kline736353a2018-03-21 07:18:33 -07006389 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006390 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6391 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006392
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006393 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6394 // command must be sent after updating LinkProperties to maximize chances of
6395 // NetworkMonitor seeing the correct LinkProperties when starting.
6396 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6397 try {
6398 networkAgent.networkMonitor().notifyNetworkConnected();
6399 } catch (RemoteException e) {
6400 e.rethrowFromSystemServer();
6401 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006402 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006403
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006404 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6405 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6406 // capabilities, so it only needs to be done once on initial connect, not every time the
6407 // network's capabilities change. Note that we do this before rematching the network,
6408 // so we could decide to tear it down immediately afterwards. That's fine though - on
6409 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6410 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006411 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006412
Varun Anand4fa80e82019-02-06 10:13:38 -08006413 if (networkAgent.isVPN()) {
6414 updateAllVpnsCapabilities();
6415 }
6416
Paul Jensen2161a8e2014-09-11 11:00:39 -04006417 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006418 final long now = SystemClock.elapsedRealtime();
6419 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006420
6421 // This has to happen after matching the requests, because callbacks are just requests.
6422 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006423 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006424 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006425 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006426 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006427 }
Chalard Jean392971c2018-05-11 20:19:20 +09006428 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006429 if (networkAgent.isVPN()) {
6430 // As the active or bound network changes for apps, broadcast the default proxy, as
6431 // apps may need to update their proxy data. This is called after disconnecting from
6432 // VPN to make sure we do not broadcast the old proxy data.
6433 // TODO(b/122649188): send the broadcast only to VPN users.
6434 mProxyTracker.sendProxyBroadcast();
6435 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006436 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6437 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006438 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006439 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006440 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006441 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006442 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6443 networkAgent.networkCapabilities);
6444 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6445 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006446 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6447 ConnectivityManager.CALLBACK_SUSPENDED :
6448 ConnectivityManager.CALLBACK_RESUMED));
6449 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006450 }
6451 }
6452
Robert Greenwaltac96c522014-06-03 16:43:57 -07006453 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006454 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006455 if (score < 0) {
6456 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6457 "). Bumping score to min of 0");
6458 score = 0;
6459 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006460
Paul Jensen2161a8e2014-09-11 11:00:39 -04006461 final int oldScore = nai.getCurrentScore();
6462 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006463
Paul Jensen85cf78e2015-06-25 13:25:07 -04006464 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006465
Paul Jensenc8b9a742014-09-30 15:37:41 -04006466 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006467 }
6468
Erik Klinec75d4fa2017-02-15 19:59:17 +09006469 // Notify only this one new request of the current state. Transfer all the
6470 // current state by calling NetworkCapabilities and LinkProperties callbacks
6471 // so that callers can be guaranteed to have as close to atomicity in state
6472 // transfer as can be supported by this current API.
6473 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006474 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006475 if (nri.mPendingIntent != null) {
6476 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6477 // Attempt no subsequent state pushes where intents are involved.
6478 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006479 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006480
junyulai05986c62018-08-07 19:50:45 +08006481 final boolean metered = nai.networkCapabilities.isMetered();
6482 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6483 metered, mRestrictBackground);
6484 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6485 }
6486
6487 /**
6488 * Notify of the blocked state apps with a registered callback matching a given NAI.
6489 *
6490 * Unlike other callbacks, blocked status is different between each individual uid. So for
6491 * any given nai, all requests need to be considered according to the uid who filed it.
6492 *
6493 * @param nai The target NetworkAgentInfo.
6494 * @param oldMetered True if the previous network capabilities is metered.
6495 * @param newRestrictBackground True if data saver is enabled.
6496 */
6497 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6498 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6499
6500 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6501 NetworkRequest nr = nai.requestAt(i);
6502 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6503 final int uidRules = mUidRules.get(nri.mUid);
6504 final boolean oldBlocked, newBlocked;
6505 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6506 // between these two calls.
6507 synchronized (mVpns) {
6508 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6509 oldRestrictBackground);
6510 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6511 newRestrictBackground);
6512 }
6513 if (oldBlocked != newBlocked) {
6514 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6515 encodeBool(newBlocked));
6516 }
6517 }
6518 }
6519
6520 /**
6521 * Notify apps with a given UID of the new blocked state according to new uid rules.
6522 * @param uid The uid for which the rules changed.
6523 * @param newRules The new rules to apply.
6524 */
6525 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6526 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6527 final boolean metered = nai.networkCapabilities.isMetered();
6528 final boolean oldBlocked, newBlocked;
6529 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6530 // rules changed event. And this function actually loop through all connected nai and
6531 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6532 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6533 synchronized (mVpns) {
6534 oldBlocked = isUidNetworkingWithVpnBlocked(
6535 uid, mUidRules.get(uid), metered, mRestrictBackground);
6536 newBlocked = isUidNetworkingWithVpnBlocked(
6537 uid, newRules, metered, mRestrictBackground);
6538 }
6539 if (oldBlocked == newBlocked) {
6540 return;
6541 }
6542 final int arg = encodeBool(newBlocked);
6543 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6544 NetworkRequest nr = nai.requestAt(i);
6545 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6546 if (nri != null && nri.mUid == uid) {
6547 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6548 }
6549 }
6550 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006551 }
6552
Robert Greenwalt8d482522015-06-24 13:23:42 -07006553 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006554 // The NetworkInfo we actually send out has no bearing on the real
6555 // state of affairs. For example, if the default connection is mobile,
6556 // and a request for HIPRI has just gone away, we need to pretend that
6557 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6558 // the state to DISCONNECTED, even though the network is of type MOBILE
6559 // and is still connected.
6560 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6561 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006562 if (state != DetailedState.DISCONNECTED) {
6563 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006564 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006565 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006566 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006567 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6568 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6569 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6570 if (info.isFailover()) {
6571 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6572 nai.networkInfo.setFailover(false);
6573 }
6574 if (info.getReason() != null) {
6575 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6576 }
6577 if (info.getExtraInfo() != null) {
6578 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6579 }
6580 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006581 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006582 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006583 if (newDefaultAgent != null) {
6584 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6585 newDefaultAgent.networkInfo);
6586 } else {
6587 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6588 }
6589 }
6590 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6591 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006592 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006593 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006594 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006595 }
6596 }
6597 }
6598
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006599 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006600 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006601 String notification = ConnectivityManager.getCallbackName(notifyType);
6602 log("notifyType " + notification + " for " + networkAgent.name());
6603 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006604 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6605 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006606 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6607 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006608 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6609 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006610 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006611 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006612 } else {
6613 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6614 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006615 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006616 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006617
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006618 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6619 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6620 }
6621
Jeff Sharkey69736342014-12-08 14:50:12 -08006622 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006623 * Returns the list of all interfaces that could be used by network traffic that does not
6624 * explicitly specify a network. This includes the default network, but also all VPNs that are
6625 * currently connected.
6626 *
6627 * Must be called on the handler thread.
6628 */
6629 private Network[] getDefaultNetworks() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006630 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006631 ArrayList<Network> defaultNetworks = new ArrayList<>();
6632 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6633 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6634 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6635 defaultNetworks.add(nai.network);
6636 }
6637 }
6638 return defaultNetworks.toArray(new Network[0]);
6639 }
6640
6641 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006642 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6643 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006644 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006645 private void notifyIfacesChangedForNetworkStats() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006646 ensureRunningOnConnectivityServiceThread();
6647 String activeIface = null;
6648 LinkProperties activeLinkProperties = getActiveLinkProperties();
6649 if (activeLinkProperties != null) {
6650 activeIface = activeLinkProperties.getInterfaceName();
6651 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006652 try {
Varun Anand02c50ef2019-02-07 14:13:13 -08006653 mStatsService.forceUpdateIfaces(
6654 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006655 } catch (Exception ignored) {
6656 }
6657 }
6658
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006659 @Override
6660 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006661 int user = UserHandle.getUserId(Binder.getCallingUid());
6662 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006663 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006664 return mVpns.get(user).addAddress(address, prefixLength);
6665 }
6666 }
6667
6668 @Override
6669 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006670 int user = UserHandle.getUserId(Binder.getCallingUid());
6671 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006672 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006673 return mVpns.get(user).removeAddress(address, prefixLength);
6674 }
6675 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006676
6677 @Override
6678 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006679 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006680 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006681 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006682 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006683 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006684 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006685 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006686 mHandler.post(() -> {
6687 // Update VPN's capabilities based on updated underlying network set.
6688 updateAllVpnsCapabilities();
6689 notifyIfacesChangedForNetworkStats();
6690 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006691 }
6692 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006693 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006694
6695 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006696 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006697 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006698 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006699 }
6700
6701 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006702 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
6703 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
6704 enforceKeepalivePermission();
6705 mKeepaliveTracker.startNattKeepalive(
6706 getNetworkAgentInfoForNetwork(network),
6707 intervalSeconds, messenger, binder,
junyulaie4135282019-01-03 18:50:15 +08006708 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006709 }
6710
6711 @Override
junyulai215b8772019-01-15 11:32:44 +08006712 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
6713 int intervalSeconds, Messenger messenger, IBinder binder, String srcAddr,
6714 String dstAddr) {
6715 enforceKeepalivePermission();
6716 mKeepaliveTracker.startNattKeepalive(
6717 getNetworkAgentInfoForNetwork(network), fd, resourceId,
6718 intervalSeconds, messenger, binder,
6719 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6720 }
6721
6722 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006723 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
6724 Messenger messenger, IBinder binder) {
6725 enforceKeepalivePermission();
6726 mKeepaliveTracker.startTcpKeepalive(
6727 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, messenger, binder);
6728 }
6729
6730 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006731 public void stopKeepalive(Network network, int slot) {
6732 mHandler.sendMessage(mHandler.obtainMessage(
junyulaie4135282019-01-03 18:50:15 +08006733 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006734 }
6735
6736 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006737 public void factoryReset() {
6738 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006739
6740 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6741 return;
6742 }
6743
Robin Lee3b3dd942015-05-12 18:14:58 +01006744 final int userId = UserHandle.getCallingUserId();
6745
Stuart Scottf1fb3972015-04-02 18:00:02 -07006746 // Turn airplane mode off
6747 setAirplaneMode(false);
6748
Stuart Scotte3e314d2015-04-20 14:07:45 -07006749 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6750 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006751 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006752 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006753 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006754 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006755 }
6756
Stuart Scotte3e314d2015-04-20 14:07:45 -07006757 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006758 // Remove always-on package
6759 synchronized (mVpns) {
6760 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6761 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006762 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006763 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6764 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006765
Hugo Benichi69744342017-11-27 10:57:16 +09006766 // Turn Always-on VPN off
6767 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6768 final long ident = Binder.clearCallingIdentity();
6769 try {
6770 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6771 mLockdownEnabled = false;
6772 setLockdownTracker(null);
6773 } finally {
6774 Binder.restoreCallingIdentity(ident);
6775 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006776 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006777
Hugo Benichi69744342017-11-27 10:57:16 +09006778 // Turn VPN off
6779 VpnConfig vpnConfig = getVpnConfig(userId);
6780 if (vpnConfig != null) {
6781 if (vpnConfig.legacy) {
6782 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6783 } else {
6784 // Prevent this app (packagename = vpnConfig.user) from initiating
6785 // VPN connections in the future without user intervention.
6786 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006787
Hugo Benichi69744342017-11-27 10:57:16 +09006788 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6789 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006790 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006791 }
6792 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006793
6794 Settings.Global.putString(mContext.getContentResolver(),
6795 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006796 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006797
Ricky Wai44dcbde2018-01-23 04:09:45 +00006798 @Override
6799 public byte[] getNetworkWatchlistConfigHash() {
6800 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6801 if (nwm == null) {
6802 loge("Unable to get NetworkWatchlistManager");
6803 return null;
6804 }
6805 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6806 return nwm.getWatchlistConfigHash();
6807 }
6808
Paul Jensencf4c2c62015-07-01 14:16:32 -04006809 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006810 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6811 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006812 }
6813
6814 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006815 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6816 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6817 }
6818
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006819 @VisibleForTesting
6820 public boolean hasService(String name) {
6821 return ServiceManager.checkService(name) != null;
6822 }
6823
Hugo Benichi64901e52017-10-19 14:42:40 +09006824 @VisibleForTesting
6825 protected IpConnectivityMetrics.Logger metricsLogger() {
6826 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6827 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006828 }
6829
6830 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006831 int[] transports = nai.networkCapabilities.getTransportTypes();
6832 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006833 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006834
6835 private static boolean toBool(int encodedBoolean) {
6836 return encodedBoolean != 0; // Only 0 means false.
6837 }
6838
6839 private static int encodeBool(boolean b) {
6840 return b ? 1 : 0;
6841 }
mswest46386886f2018-03-12 10:34:34 -07006842
6843 @Override
6844 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6845 FileDescriptor err, String[] args, ShellCallback callback,
6846 ResultReceiver resultReceiver) {
6847 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6848 }
6849
6850 private class ShellCmd extends ShellCommand {
6851
6852 @Override
6853 public int onCommand(String cmd) {
6854 if (cmd == null) {
6855 return handleDefaultCommands(cmd);
6856 }
6857 final PrintWriter pw = getOutPrintWriter();
6858 try {
6859 switch (cmd) {
6860 case "airplane-mode":
6861 final String action = getNextArg();
6862 if ("enable".equals(action)) {
6863 setAirplaneMode(true);
6864 return 0;
6865 } else if ("disable".equals(action)) {
6866 setAirplaneMode(false);
6867 return 0;
6868 } else if (action == null) {
6869 final ContentResolver cr = mContext.getContentResolver();
6870 final int enabled = Settings.Global.getInt(cr,
6871 Settings.Global.AIRPLANE_MODE_ON);
6872 pw.println(enabled == 0 ? "disabled" : "enabled");
6873 return 0;
6874 } else {
6875 onHelp();
6876 return -1;
6877 }
6878 default:
6879 return handleDefaultCommands(cmd);
6880 }
6881 } catch (Exception e) {
6882 pw.println(e);
6883 }
6884 return -1;
6885 }
6886
6887 @Override
6888 public void onHelp() {
6889 PrintWriter pw = getOutPrintWriter();
6890 pw.println("Connectivity service commands:");
6891 pw.println(" help");
6892 pw.println(" Print this help text.");
6893 pw.println(" airplane-mode [enable|disable]");
6894 pw.println(" Turn airplane mode on or off.");
6895 pw.println(" airplane-mode");
6896 pw.println(" Get airplane mode.");
6897 }
6898 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006899
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006900 @GuardedBy("mVpns")
6901 private Vpn getVpnIfOwner() {
6902 final int uid = Binder.getCallingUid();
6903 final int user = UserHandle.getUserId(uid);
6904
6905 final Vpn vpn = mVpns.get(user);
6906 if (vpn == null) {
6907 return null;
6908 } else {
6909 final VpnInfo info = vpn.getVpnInfo();
6910 return (info == null || info.ownerUid != uid) ? null : vpn;
6911 }
6912 }
6913
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006914 /**
6915 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6916 * for testing.
6917 */
6918 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6919 if (checkNetworkStackPermission()) {
6920 return null;
6921 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006922 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006923 Vpn vpn = getVpnIfOwner();
6924 if (vpn != null) {
6925 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006926 }
6927 }
6928 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6929 + "permission");
6930 }
6931
6932 /**
6933 * @param connectionInfo the connection to resolve.
6934 * @return {@code uid} if the connection is found and the app has permission to observe it
6935 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6936 * connection is not found.
6937 */
6938 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6939 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6940 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6941 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6942 }
6943
6944 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6945 connectionInfo.local, connectionInfo.remote);
6946
6947 /* Filter out Uids not associated with the VPN. */
6948 if (vpn != null && !vpn.appliesToUid(uid)) {
6949 return INVALID_UID;
6950 }
6951
6952 return uid;
6953 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006954
6955 @Override
6956 public boolean isCallerCurrentAlwaysOnVpnApp() {
6957 synchronized (mVpns) {
6958 Vpn vpn = getVpnIfOwner();
6959 return vpn != null && vpn.getAlwaysOn();
6960 }
6961 }
6962
6963 @Override
6964 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6965 synchronized (mVpns) {
6966 Vpn vpn = getVpnIfOwner();
6967 return vpn != null && vpn.getLockdown();
6968 }
6969 }
Benedict Wong99a48412018-11-09 14:45:34 -08006970
6971 /**
6972 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
6973 *
6974 * <p>The TestNetworkService must be run in the system server due to TUN creation.
6975 */
6976 @Override
6977 public IBinder startOrGetTestNetworkService() {
6978 synchronized (mTNSLock) {
6979 TestNetworkService.enforceTestNetworkPermissions(mContext);
6980
6981 if (mTNS == null) {
6982 mTNS = new TestNetworkService(mContext, mNMS);
6983 }
6984
6985 return mTNS;
6986 }
6987 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006988}