blob: 5f3c67fb353b4991ed37c2f0e118fec69f94cdee [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
lucasline252a742019-03-12 13:08:03 +080028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090029import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040030import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090032import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
34import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
lucasline252a742019-03-12 13:08:03 +080038import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090039import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060040import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080041import static android.net.NetworkPolicyManager.RULE_NONE;
42import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090043import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070044import static android.os.Process.INVALID_UID;
45import static android.system.OsConstants.IPPROTO_TCP;
46import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060047
Hugo Benichia0385682017-03-22 17:07:57 +090048import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060049
Wenchao Tongf5ea3402015-03-04 13:26:38 -080050import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080051import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090052import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070053import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070054import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.ContentResolver;
56import android.content.Context;
57import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070058import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070059import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070060import android.database.ContentObserver;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090061import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070062import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.ConnectivityManager;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090064import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050066import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080067import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050068import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070069import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090070import android.net.INetworkMonitor;
71import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070072import android.net.INetworkPolicyListener;
73import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070074import android.net.INetworkStatsService;
junyulai7c469172019-01-16 20:23:34 +080075import android.net.ISocketKeepaliveCallback;
markchien26299ed2019-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 Jean05ab6812018-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 VAN5db454c2019-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;
junyulai06835112019-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 VANde602212019-01-30 15:22:01 +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 Wonga341fbc2018-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
junyulai0c666972019-03-04 22:45:36 +0800991 mKeepaliveTracker = new KeepaliveTracker(mContext, 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 Cohenddb720a2019-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
paulhu3d67f532019-03-22 16:35:06 +08001885 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
1886 for (String permission : permissions) {
1887 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
1888 return true;
1889 }
1890 }
1891 return false;
1892 }
1893
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001894 private void enforceAnyPermissionOf(String... permissions) {
1895 if (!checkAnyPermissionOf(permissions)) {
1896 throw new SecurityException("Requires one of the following permissions: "
1897 + String.join(", ", permissions) + ".");
1898 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001899 }
1900
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001901 private void enforceInternetPermission() {
1902 mContext.enforceCallingOrSelfPermission(
1903 android.Manifest.permission.INTERNET,
1904 "ConnectivityService");
1905 }
1906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001908 mContext.enforceCallingOrSelfPermission(
1909 android.Manifest.permission.ACCESS_NETWORK_STATE,
1910 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
1912
1913 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001914 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
1916
Charles He36738632017-05-15 17:07:18 +01001917 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001918 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001919 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001920 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001921 }
1922
Chalard Jeanb552c462018-02-21 18:43:54 +09001923 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001924 return checkAnyPermissionOf(
1925 android.Manifest.permission.NETWORK_SETTINGS,
1926 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001927 }
1928
1929 private boolean checkSettingsPermission(int pid, int uid) {
1930 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001931 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1932 || PERMISSION_GRANTED == mContext.checkPermission(
1933 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001934 }
1935
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001936 private void enforceTetherAccessPermission() {
1937 mContext.enforceCallingOrSelfPermission(
1938 android.Manifest.permission.ACCESS_NETWORK_STATE,
1939 "ConnectivityService");
1940 }
1941
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001942 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001943 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001944 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001945 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001946 }
1947
Pavel Grafova462bcb2019-01-25 08:50:06 +00001948 private void enforceControlAlwaysOnVpnPermission() {
1949 mContext.enforceCallingOrSelfPermission(
1950 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1951 "ConnectivityService");
1952 }
1953
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001954 private void enforceNetworkStackSettingsOrSetup() {
1955 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001956 android.Manifest.permission.NETWORK_SETTINGS,
1957 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001958 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001959 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001960 }
1961
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001962 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001963 return checkAnyPermissionOf(
1964 android.Manifest.permission.NETWORK_STACK,
1965 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001966 }
1967
paulhu3d67f532019-03-22 16:35:06 +08001968 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
1969 return checkAnyPermissionOf(pid, uid,
1970 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
1971 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
1972 }
1973
Hugo Benichi514da602016-07-19 15:59:27 +09001974 private void enforceConnectivityRestrictedNetworksPermission() {
1975 try {
1976 mContext.enforceCallingOrSelfPermission(
1977 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1978 "ConnectivityService");
1979 return;
1980 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1981 enforceConnectivityInternalPermission();
1982 }
1983
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001984 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001985 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001986 }
1987
Lorenzo Colitti18660282016-07-04 12:55:44 +09001988 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001989 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001990 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001991 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001992 }
1993
1994 private void sendInetConditionBroadcast(NetworkInfo info) {
1995 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1996 }
1997
Wink Saville628b0852011-08-04 15:01:58 -07001998 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001999 synchronized (mVpns) {
2000 if (mLockdownTracker != null) {
2001 info = new NetworkInfo(info);
2002 mLockdownTracker.augmentNetworkInfo(info);
2003 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002004 }
2005
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07002006 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002007 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07002008 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 if (info.isFailover()) {
2010 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2011 info.setFailover(false);
2012 }
2013 if (info.getReason() != null) {
2014 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2015 }
2016 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002017 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2018 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002020 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002021 return intent;
2022 }
2023
2024 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2025 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2026 }
2027
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002028 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002029 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2030 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2031 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002032 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002033 final long ident = Binder.clearCallingIdentity();
2034 try {
2035 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2036 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2037 } finally {
2038 Binder.restoreCallingIdentity(ident);
2039 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002040 }
2041
Mike Lockwood0f79b542009-08-14 14:18:49 -04002042 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002043 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002044 if (!mSystemReady
2045 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002046 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002047 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002048 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002049 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002050 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002051 }
2052
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002053 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002054 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002055 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002056 final NetworkInfo ni = intent.getParcelableExtra(
2057 ConnectivityManager.EXTRA_NETWORK_INFO);
2058 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2059 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2060 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002061 } else {
2062 BroadcastOptions opts = BroadcastOptions.makeBasic();
2063 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2064 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002065 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002066 final IBatteryStats bs = BatteryStatsService.getService();
2067 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002068 bs.noteConnectivityChanged(intent.getIntExtra(
2069 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002070 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002071 } catch (RemoteException e) {
2072 }
Chad Brubakerac925012018-03-08 10:37:09 -08002073 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002074 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002075 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002076 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002077 } finally {
2078 Binder.restoreCallingIdentity(ident);
2079 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002080 }
2081 }
2082
2083 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002084 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002085 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002086 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002087
Hugo Benichi20035e02017-04-26 14:53:28 +09002088 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002089 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002090 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002091 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002092 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002093 }
2094 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002095
Robin Lee244ce8e2016-01-05 18:03:46 +00002096 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2097 // for user to unlock device too.
2098 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002099
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002100 // Create network requests for always-on networks.
2101 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002102
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002103 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002104
2105 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 }
2107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002109 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002110 *
2111 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002112 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002113 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2115 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002116
2117 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002119
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 if (networkAgent.networkCapabilities.hasTransport(
2121 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002122 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2123 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002124 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002125 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002126 } else if (networkAgent.networkCapabilities.hasTransport(
2127 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002128 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2129 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002130 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002132 } else {
2133 // do not track any other networks
2134 timeout = 0;
2135 }
2136
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002138 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002139 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002140 } catch (Exception e) {
2141 // You shall not crash!
2142 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002143 }
2144 }
2145 }
2146
2147 /**
2148 * Remove data activity tracking when network disconnects.
2149 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2151 final String iface = networkAgent.linkProperties.getInterfaceName();
2152 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002153
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2155 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002156 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002157 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002158 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002159 } catch (Exception e) {
2160 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002161 }
2162 }
2163 }
2164
2165 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002166 * Update data activity tracking when network state is updated.
2167 */
2168 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2169 NetworkAgentInfo oldNetwork) {
2170 if (newNetwork != null) {
2171 setupDataActivityTracking(newNetwork);
2172 }
2173 if (oldNetwork != null) {
2174 removeDataActivityTracking(oldNetwork);
2175 }
2176 }
2177 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002178 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002179 * and set it on it's iface.
2180 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002181 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2182 final String iface = newLp.getInterfaceName();
2183 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002184 if (oldLp == null && mtu == 0) {
2185 // Silently ignore unset MTU value.
2186 return;
2187 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002188 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2189 if (VDBG) log("identical MTU - not setting");
2190 return;
2191 }
paulhud9736de2019-03-08 16:35:20 +08002192 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002193 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002194 return;
2195 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002196
w1997615afd812014-08-05 15:18:11 -07002197 // Cannot set MTU without interface name
2198 if (TextUtils.isEmpty(iface)) {
2199 loge("Setting MTU size with null iface.");
2200 return;
2201 }
2202
Robert Greenwalt7b816022014-04-18 15:25:25 -07002203 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002204 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002205 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002206 } catch (Exception e) {
2207 Slog.e(TAG, "exception in setMtu()" + e);
2208 }
2209 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002210
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002211 @VisibleForTesting
2212 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002213 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2214
2215 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002216 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002217 protected MockableSystemProperties getSystemProperties() {
2218 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002219 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002220
lucaslin041a1af2018-11-28 19:27:52 +08002221 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002222 String[] values = null;
2223 if (tcpBufferSizes != null) {
2224 values = tcpBufferSizes.split(",");
2225 }
2226
2227 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002228 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002229 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2230 values = tcpBufferSizes.split(",");
2231 }
2232
2233 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2234
2235 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002236 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002237
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002238 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2239 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2240 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002241 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002242 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002243 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002244 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002245
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002246 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002247 Settings.Global.TCP_DEFAULT_INIT_RWND,
2248 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002249 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2250 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002251 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002252 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002253 }
2254
Robert Greenwalt562cc542014-05-15 18:07:26 -07002255 @Override
2256 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002257 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002258 NETWORK_RESTORE_DELAY_PROP_NAME);
2259 if(restoreDefaultNetworkDelayStr != null &&
2260 restoreDefaultNetworkDelayStr.length() != 0) {
2261 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002262 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002263 } catch (NumberFormatException e) {
2264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002266 // if the system property isn't set, use the value for the apn type
2267 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2268
2269 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2270 (mNetConfigs[networkType] != null)) {
2271 ret = mNetConfigs[networkType].restoreTime;
2272 }
2273 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 }
2275
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002276 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2277 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2278 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002279 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002280 // Start gathering diagnostic information.
2281 netDiags.add(new NetworkDiagnostics(
2282 nai.network,
2283 new LinkProperties(nai.linkProperties), // Must be a copy.
2284 DIAG_TIME_MS));
2285 }
2286
2287 for (NetworkDiagnostics netDiag : netDiags) {
2288 pw.println();
2289 netDiag.waitForMeasurements();
2290 netDiag.dump(pw);
2291 }
2292 }
2293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002295 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002296 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2297 }
2298
2299 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002300 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002301 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002302 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002303
Erik Kline3f8306b2018-05-01 16:51:44 +09002304 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002305 dumpNetworkDiagnostics(pw);
2306 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002307 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002308 mTethering.dump(fd, pw, args);
2309 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002310 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2311 dumpNetworks(pw);
2312 return;
2313 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2314 dumpNetworkRequests(pw);
2315 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002316 }
Erik Kline379747a2015-06-05 17:47:34 +09002317
Lorenzo Colittie3805462015-06-03 11:18:24 +09002318 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002319 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002320 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002321 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002322 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002323 pw.println();
2324
Paul Jensen85cf78e2015-06-25 13:25:07 -04002325 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002326 pw.print("Active default network: ");
2327 if (defaultNai == null) {
2328 pw.println("none");
2329 } else {
2330 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002332 pw.println();
2333
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002334 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002335 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002336 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002337 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002338 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002339
junyulai05986c62018-08-07 19:50:45 +08002340 pw.print("Restrict background: ");
2341 pw.println(mRestrictBackground);
2342 pw.println();
2343
2344 pw.println("Status for known UIDs:");
2345 pw.increaseIndent();
2346 final int size = mUidRules.size();
2347 for (int i = 0; i < size; i++) {
2348 // Don't crash if the array is modified while dumping in bugreports.
2349 try {
2350 final int uid = mUidRules.keyAt(i);
2351 final int uidRules = mUidRules.get(uid, RULE_NONE);
2352 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2353 } catch (ArrayIndexOutOfBoundsException e) {
2354 pw.println(" ArrayIndexOutOfBoundsException");
2355 } catch (ConcurrentModificationException e) {
2356 pw.println(" ConcurrentModificationException");
2357 }
2358 }
2359 pw.println();
2360 pw.decreaseIndent();
2361
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002362 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002363 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002364 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002365 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002366 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002367
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002368 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002369
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002370 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002371 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002372
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002373 pw.println();
2374 mKeepaliveTracker.dump(pw);
2375
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002376 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002377 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002378
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002379 pw.println();
2380 mMultipathPolicyTracker.dump(pw);
2381
Erik Kline3f8306b2018-05-01 16:51:44 +09002382 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002383 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002384 pw.println("mNetworkRequestInfoLogs (most recent first):");
2385 pw.increaseIndent();
2386 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2387 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002388
2389 pw.println();
2390 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2391 pw.increaseIndent();
2392 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2393 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002394
2395 pw.println();
2396 pw.println("NetTransition WakeLock activity (most recent first):");
2397 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002398 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2399 pw.println("total releases: " + mTotalWakelockReleases);
2400 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2401 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2402 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2403 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2404 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2405 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002406 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002407
2408 pw.println();
2409 pw.println("bandwidth update requests (by uid):");
2410 pw.increaseIndent();
2411 synchronized (mBandwidthRequests) {
2412 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2413 pw.println("[" + mBandwidthRequests.keyAt(i)
2414 + "]: " + mBandwidthRequests.valueAt(i));
2415 }
2416 }
2417 pw.decreaseIndent();
2418
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002419 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002420 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002421
2422 pw.println();
2423 pw.println("NetworkStackClient logs:");
2424 pw.increaseIndent();
2425 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 }
2427
Hugo Benichi14683812018-09-03 08:32:56 +09002428 private void dumpNetworks(IndentingPrintWriter pw) {
2429 for (NetworkAgentInfo nai : networksSortedById()) {
2430 pw.println(nai.toString());
2431 pw.increaseIndent();
2432 pw.println(String.format(
2433 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2434 nai.numForegroundNetworkRequests(),
2435 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2436 nai.numBackgroundNetworkRequests(),
2437 nai.numNetworkRequests()));
2438 pw.increaseIndent();
2439 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2440 pw.println(nai.requestAt(i).toString());
2441 }
2442 pw.decreaseIndent();
2443 pw.println("Lingered:");
2444 pw.increaseIndent();
2445 nai.dumpLingerTimers(pw);
2446 pw.decreaseIndent();
2447 pw.decreaseIndent();
2448 }
2449 }
2450
2451 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2452 for (NetworkRequestInfo nri : requestsSortedById()) {
2453 pw.println(nri.toString());
2454 }
2455 }
2456
Hugo Benichia2a917c2018-09-03 08:19:02 +09002457 /**
2458 * Return an array of all current NetworkAgentInfos sorted by network id.
2459 */
2460 private NetworkAgentInfo[] networksSortedById() {
2461 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2462 networks = mNetworkAgentInfos.values().toArray(networks);
2463 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2464 return networks;
2465 }
2466
2467 /**
2468 * Return an array of all current NetworkRequest sorted by request id.
2469 */
2470 private NetworkRequestInfo[] requestsSortedById() {
2471 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2472 requests = mNetworkRequests.values().toArray(requests);
2473 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2474 return requests;
2475 }
2476
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002477 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002478 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002479 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002480 if (officialNai != null && officialNai.equals(nai)) return true;
2481 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002482 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002483 " - " + nai);
2484 }
2485 return false;
2486 }
2487
Robert Greenwalt42acef32009-08-12 16:08:25 -07002488 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002489 private class NetworkStateTrackerHandler extends Handler {
2490 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002491 super(looper);
2492 }
2493
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002494 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002496 default:
2497 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002498 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002499 handleAsyncChannelHalfConnect(msg);
2500 break;
2501 }
2502 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2503 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2504 if (nai != null) nai.asyncChannel.disconnect();
2505 break;
2506 }
2507 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2508 handleAsyncChannelDisconnected(msg);
2509 break;
2510 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002511 }
2512 return true;
2513 }
2514
2515 private void maybeHandleNetworkAgentMessage(Message msg) {
2516 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2517 if (nai == null) {
2518 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002519 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002520 }
2521 return;
2522 }
2523
2524 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002525 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002526 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002527 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002528 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002529 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002530 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002531 break;
2532 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002533 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002534 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002535 break;
2536 }
2537 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002538 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002539 updateNetworkInfo(nai, info);
2540 break;
2541 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002542 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002543 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002544 break;
2545 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002546 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002547 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2548 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002549 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002550 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002551 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002552 // Mark the network as temporarily accepting partial connectivity so that it
2553 // will be validated (and possibly become default) even if it only provides
2554 // partial internet access. Note that if user connects to partial connectivity
2555 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2556 // out of wifi coverage) and if the same wifi is available again, the device
2557 // will auto connect to this wifi even though the wifi has "no internet".
2558 // TODO: Evaluate using a separate setting in IpMemoryStore.
2559 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002560 break;
2561 }
junyulai06835112019-01-03 18:50:15 +08002562 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2563 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002564 break;
2565 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002566 }
2567 }
2568
2569 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2570 switch (msg.what) {
2571 default:
2572 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002573 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002574 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002575 if (nai == null) break;
2576
lucasline252a742019-03-12 13:08:03 +08002577 final boolean partialConnectivity =
2578 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
lucasline252a742019-03-12 13:08:03 +08002579 || (nai.networkMisc.acceptPartialConnectivity
2580 && nai.partialConnectivity);
2581 // Once a network is determined to have partial connectivity, it cannot
lucaslin975b7d32019-03-21 11:59:22 +08002582 // go back to full connectivity without a disconnect. This is because
2583 // NetworkMonitor can only communicate either PARTIAL_CONNECTIVITY or VALID,
2584 // but not both.
2585 // TODO: Provide multi-testResult to improve the communication between
2586 // ConnectivityService and NetworkMonitor, so that ConnectivityService could
2587 // know the real status of network.
lucaslin43338992019-03-20 18:21:59 +08002588 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002589 (partialConnectivity && !nai.partialConnectivity);
2590
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002591 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002592 final boolean wasValidated = nai.lastValidated;
2593 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002594 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2595 && valid) {
2596 nai.captivePortalLoginNotified = true;
2597 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2598 }
Erik Klinea24d4592018-01-11 21:07:29 +09002599
Erik Klinea24d4592018-01-11 21:07:29 +09002600 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2601
Erik Klinea24d4592018-01-11 21:07:29 +09002602 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002603 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2604 ? " with redirect to " + redirectUrl
2605 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002606 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2607 }
Erik Klinea24d4592018-01-11 21:07:29 +09002608 if (valid != nai.lastValidated) {
2609 if (wasDefault) {
2610 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2611 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002612 }
Erik Klinea24d4592018-01-11 21:07:29 +09002613 final int oldScore = nai.getCurrentScore();
2614 nai.lastValidated = valid;
2615 nai.everValidated |= valid;
2616 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2617 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2618 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002619 if (valid) {
2620 handleFreshlyValidatedNetwork(nai);
2621 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2622 // valid.
2623 mNotifier.clearNotification(nai.network.netId,
2624 NotificationType.NO_INTERNET);
2625 mNotifier.clearNotification(nai.network.netId,
2626 NotificationType.LOST_INTERNET);
2627 }
lucaslin43338992019-03-20 18:21:59 +08002628 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002629 nai.partialConnectivity = partialConnectivity;
2630 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002631 }
2632 updateInetCondition(nai);
2633 // Let the NetworkAgent know the state of its network
2634 Bundle redirectUrlBundle = new Bundle();
2635 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2636 nai.asyncChannel.sendMessage(
2637 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2638 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2639 0, redirectUrlBundle);
2640 if (wasValidated && !nai.lastValidated) {
2641 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002642 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002643 break;
2644 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002645 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002646 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002647 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002648 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002649 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002650 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002651 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002652 nai.lastCaptivePortalDetected = visible;
2653 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002654 if (visible) {
2655 nai.captivePortalLoginNotified = false;
2656 }
Calvin Onbe96da12016-10-11 15:10:46 -07002657 if (nai.lastCaptivePortalDetected &&
2658 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2659 if (DBG) log("Avoiding captive portal network: " + nai.name());
2660 nai.asyncChannel.sendMessage(
2661 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2662 teardownUnneededNetwork(nai);
2663 break;
2664 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002665 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002666 }
2667 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002668 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002669 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002670 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2671 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002672 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002673 if (nai == null) {
2674 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2675 break;
2676 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002677 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002678 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002679 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002680 }
Paul Jensen869868be2014-05-15 10:33:05 -04002681 }
Paul Jensen869868be2014-05-15 10:33:05 -04002682 break;
2683 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002684 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002685 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002686 if (nai == null) break;
2687
Erik Kline736353a2018-03-21 07:18:33 -07002688 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002689 break;
2690 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002691 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002692 return true;
2693 }
2694
Calvin Onbe96da12016-10-11 15:10:46 -07002695 private int getCaptivePortalMode() {
2696 return Settings.Global.getInt(mContext.getContentResolver(),
2697 Settings.Global.CAPTIVE_PORTAL_MODE,
2698 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2699 }
2700
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002701 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2702 switch (msg.what) {
2703 default:
2704 return false;
2705 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2706 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2707 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2708 handleLingerComplete(nai);
2709 }
2710 break;
2711 }
2712 }
2713 return true;
2714 }
2715
Etan Cohenddb720a2019-01-08 12:09:18 -08002716 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2717 switch (msg.what) {
2718 default:
2719 return false;
2720 case android.net.NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2721 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2722 /* callOnUnavailable */ true);
2723 break;
2724 }
2725 }
2726 return true;
2727 }
2728
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002729 @Override
2730 public void handleMessage(Message msg) {
Etan Cohenddb720a2019-01-08 12:09:18 -08002731 if (!maybeHandleAsyncChannelMessage(msg)
2732 && !maybeHandleNetworkMonitorMessage(msg)
2733 && !maybeHandleNetworkAgentInfoMessage(msg)
2734 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002735 maybeHandleNetworkAgentMessage(msg);
2736 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002737 }
2738 }
2739
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002740 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2741 private final NetworkAgentInfo mNai;
2742
2743 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2744 mNai = nai;
2745 }
2746
2747 @Override
2748 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2749 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2750 new Pair<>(mNai, networkMonitor)));
2751 }
2752
2753 @Override
2754 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2755 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2756 testResult, mNai.network.netId, redirectUrl));
2757 }
2758
2759 @Override
2760 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2761 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2762 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2763 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2764 }
2765
2766 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002767 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002768 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002769 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002770
2771 final PendingIntent pendingIntent;
2772 // Only the system server can register notifications with package "android"
2773 final long token = Binder.clearCallingIdentity();
2774 try {
2775 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2776 } finally {
2777 Binder.restoreCallingIdentity(token);
2778 }
2779 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2780 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2781 mNai.network.netId,
2782 pendingIntent));
2783 }
2784
2785 @Override
2786 public void hideProvisioningNotification() {
2787 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2788 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2789 mNai.network.netId));
2790 }
2791 }
2792
Erik Kline736353a2018-03-21 07:18:33 -07002793 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002794 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002795 }
2796
Erik Klinec6d00222018-06-26 18:53:43 +09002797 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2798 if (nai == null) return;
2799 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2800 // in order to restart a validation pass from within netd.
2801 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2802 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2803 updateDnses(nai.linkProperties, null, nai.network.netId);
2804 }
2805 }
2806
Erik Klinea24d4592018-01-11 21:07:29 +09002807 private void handlePrivateDnsSettingsChanged() {
2808 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2809
2810 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002811 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002812 if (networkRequiresValidation(nai)) {
2813 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2814 }
Erik Klinea24d4592018-01-11 21:07:29 +09002815 }
2816 }
2817
Erik Kline736353a2018-03-21 07:18:33 -07002818 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2819 // Private DNS only ever applies to networks that might provide
2820 // Internet access and therefore also require validation.
2821 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002822
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002823 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002824 // schedule DNS resolutions. If a DNS resolution is required the
2825 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002826 try {
2827 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2828 } catch (RemoteException e) {
2829 e.rethrowFromSystemServer();
2830 }
Erik Kline736353a2018-03-21 07:18:33 -07002831
2832 // With Private DNS bypass support, we can proceed to update the
2833 // Private DNS config immediately, even if we're in strict mode
2834 // and have not yet resolved the provider name into a set of IPs.
2835 updatePrivateDns(nai, cfg);
2836 }
2837
2838 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2839 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002840 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002841 }
2842
dalyk7301aa42018-03-05 12:42:22 -05002843 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2844 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2845 if (nai == null) {
2846 return;
2847 }
2848 mDnsManager.updatePrivateDnsValidation(update);
2849 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2850 }
2851
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002852 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2853 int prefixLength) {
2854 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2855 if (nai == null) return;
2856
2857 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2858 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2859
2860 IpPrefix prefix = null;
2861 if (added) {
2862 try {
2863 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2864 prefixLength);
2865 } catch (IllegalArgumentException e) {
2866 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2867 return;
2868 }
2869 }
2870
2871 nai.clatd.setNat64Prefix(prefix);
2872 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2873 }
2874
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002875 private void updateLingerState(NetworkAgentInfo nai, long now) {
2876 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2877 // 2. If the network was lingering and there are now requests, unlinger it.
2878 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2879 // one lingered request, start lingering.
2880 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002881 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002882 if (DBG) log("Unlingering " + nai.name());
2883 nai.unlinger();
2884 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002885 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002886 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002887 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002888 nai.linger();
2889 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2890 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2891 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002892 }
2893
Robert Greenwalt7b816022014-04-18 15:25:25 -07002894 private void handleAsyncChannelHalfConnect(Message msg) {
2895 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002896 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002897 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2898 if (VDBG) log("NetworkFactory connected");
Etan Cohenddb720a2019-01-08 12:09:18 -08002899 // Finish setting up the full connection
2900 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2901 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002902 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002903 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002904 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002905 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09002906 final int score;
2907 final int serial;
2908 if (nai != null) {
2909 score = nai.getCurrentScore();
2910 serial = nai.factorySerialNumber;
2911 } else {
2912 score = 0;
2913 serial = NetworkFactory.SerialNumber.NONE;
2914 }
2915 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2916 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002917 }
2918 } else {
2919 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002920 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002921 }
2922 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2923 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2924 if (VDBG) log("NetworkAgent connected");
2925 // A network agent has requested a connection. Establish the connection.
2926 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2927 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2928 } else {
2929 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002930 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002931 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002932 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002933 synchronized (mNetworkForNetId) {
2934 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002935 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002936 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002937 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002938 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002939 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002940 }
2941 }
2942 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002943
Chalard Jean392971c2018-05-11 20:19:20 +09002944 // This is a no-op if it's called with a message designating a network that has
2945 // already been destroyed, because its reference will not be found in the relevant
2946 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002947 private void handleAsyncChannelDisconnected(Message msg) {
2948 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2949 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002950 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002951 } else {
2952 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2953 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002954 }
2955 }
2956
Chalard Jean392971c2018-05-11 20:19:20 +09002957 // Destroys a network, remove references to it from the internal state managed by
2958 // ConnectivityService, free its interfaces and clean up.
2959 // Must be called on the Handler thread.
2960 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2961 if (DBG) {
2962 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2963 }
lucaslinf80b83b2019-02-12 15:30:13 +08002964 // Clear all notifications of this network.
2965 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002966 // A network agent has disconnected.
2967 // TODO - if we move the logic to the network agent (have them disconnect
2968 // because they lost all their requests or because their score isn't good)
2969 // then they would disconnect organically, report their new state and then
2970 // disconnect the channel.
2971 if (nai.networkInfo.isConnected()) {
2972 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2973 null, null);
2974 }
2975 final boolean wasDefault = isDefaultNetwork(nai);
2976 if (wasDefault) {
2977 mDefaultInetConditionPublished = 0;
2978 // Log default network disconnection before required book-keeping.
2979 // Let rematchAllNetworksAndRequests() below record a new default network event
2980 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2981 // whose timestamps tell how long it takes to recover a default network.
2982 long now = SystemClock.elapsedRealtime();
2983 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2984 }
2985 notifyIfacesChangedForNetworkStats();
2986 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2987 // by other networks that are already connected. Perhaps that can be done by
2988 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2989 // of rematchAllNetworksAndRequests
2990 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai06835112019-01-03 18:50:15 +08002991 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002992 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2993 // Disable wakeup packet monitoring for each interface.
2994 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2995 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002996 try {
2997 nai.networkMonitor().notifyNetworkDisconnected();
2998 } catch (RemoteException e) {
2999 e.rethrowFromSystemServer();
3000 }
Chalard Jean392971c2018-05-11 20:19:20 +09003001 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09003002 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09003003 synchronized (mNetworkForNetId) {
3004 // Remove the NetworkAgent, but don't mark the netId as
3005 // available until we've told netd to delete it below.
3006 mNetworkForNetId.remove(nai.network.netId);
3007 }
3008 // Remove all previously satisfied requests.
3009 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3010 NetworkRequest request = nai.requestAt(i);
3011 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
3012 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3013 clearNetworkForRequest(request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09003014 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003015 }
3016 }
3017 nai.clearLingerState();
3018 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003019 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003020 notifyLockdownVpn(nai);
3021 ensureNetworkTransitionWakelock(nai.name());
3022 }
3023 mLegacyTypeTracker.remove(nai, wasDefault);
3024 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3025 updateAllVpnsCapabilities();
3026 }
3027 rematchAllNetworksAndRequests(null, 0);
3028 mLingerMonitor.noteDisconnect(nai);
3029 if (nai.created) {
3030 // Tell netd to clean up the configuration for this network
3031 // (routing rules, DNS, etc).
3032 // This may be slow as it requires a lot of netd shelling out to ip and
3033 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3034 // after we've rematched networks with requests which should make a potential
3035 // fallback network the default or requested a new network from the
3036 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3037 // long time.
3038 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08003039 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003040 } catch (Exception e) {
3041 loge("Exception removing network: " + e);
3042 }
3043 mDnsManager.removeNetwork(nai.network);
3044 }
3045 synchronized (mNetworkForNetId) {
3046 mNetIdInUse.delete(nai.network.netId);
3047 }
3048 }
3049
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003050 // If this method proves to be too slow then we can maintain a separate
3051 // pendingIntent => NetworkRequestInfo map.
3052 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3053 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3054 Intent intent = pendingIntent.getIntent();
3055 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3056 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3057 if (existingPendingIntent != null &&
3058 existingPendingIntent.getIntent().filterEquals(intent)) {
3059 return entry.getValue();
3060 }
3061 }
3062 return null;
3063 }
3064
3065 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3066 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3067
3068 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3069 if (existingRequest != null) { // remove the existing request.
3070 if (DBG) log("Replacing " + existingRequest.request + " with "
3071 + nri.request + " because their intents matched.");
Etan Cohenddb720a2019-01-08 12:09:18 -08003072 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3073 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003074 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003075 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003076 }
3077
Erik Klineda4bfa82015-04-30 12:58:40 +09003078 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003079 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003080 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003081 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003082 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003083 if (nri.request.networkCapabilities.hasSignalStrength() &&
3084 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3085 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003086 }
3087 }
3088 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003089 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003090 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003091 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003092 }
3093 }
3094
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003095 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3096 int callingUid) {
3097 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3098 if (nri != null) {
Etan Cohenddb720a2019-01-08 12:09:18 -08003099 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003100 }
3101 }
3102
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003103 // Determines whether the network is the best (or could become the best, if it validated), for
3104 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3105 // on the value of reason:
3106 //
3107 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3108 // then it should be torn down.
3109 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3110 // then it should be lingered.
3111 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3112 final int numRequests;
3113 switch (reason) {
3114 case TEARDOWN:
3115 numRequests = nai.numRequestNetworkRequests();
3116 break;
3117 case LINGER:
3118 numRequests = nai.numForegroundNetworkRequests();
3119 break;
3120 default:
3121 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3122 return true;
3123 }
3124
3125 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003126 return false;
3127 }
Paul Jensene0988542015-06-25 15:30:08 -04003128 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003129 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3130 // Background requests don't affect lingering.
3131 continue;
3132 }
3133
Paul Jensene0988542015-06-25 15:30:08 -04003134 // If this Network is already the highest scoring Network for a request, or if
3135 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003136 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003137 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003138 // Note that this catches two important cases:
3139 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3140 // is currently satisfying the request. This is desirable when
3141 // cellular ends up validating but WiFi does not.
3142 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003143 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003144 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003145 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003146 nai.getCurrentScoreAsValidated())) {
3147 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003148 }
3149 }
Paul Jensene0988542015-06-25 15:30:08 -04003150 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003151 }
3152
Erik Klineacdd6392016-07-07 16:50:58 +09003153 private NetworkRequestInfo getNriForAppRequest(
3154 NetworkRequest request, int callingUid, String requestedOperation) {
3155 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3156
Robert Greenwalt9258c642014-03-26 16:47:06 -07003157 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003158 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003159 log(String.format("UID %d attempted to %s for unowned request %s",
3160 callingUid, requestedOperation, nri));
3161 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003162 }
Erik Klineacdd6392016-07-07 16:50:58 +09003163 }
3164
3165 return nri;
3166 }
3167
Erik Kline57faba92015-11-25 12:49:38 +09003168 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003169 if (mNetworkRequests.get(nri.request) == null) {
3170 return;
Erik Kline57faba92015-11-25 12:49:38 +09003171 }
Hugo Benichicd952782017-09-20 11:20:14 +09003172 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003173 return;
3174 }
3175 if (VDBG || (DBG && nri.request.isRequest())) {
3176 log("releasing " + nri.request + " (timeout)");
3177 }
3178 handleRemoveNetworkRequest(nri);
3179 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003180 }
3181
Etan Cohenddb720a2019-01-08 12:09:18 -08003182 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3183 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003184 final NetworkRequestInfo nri =
3185 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3186 if (nri == null) {
3187 return;
Erik Kline57faba92015-11-25 12:49:38 +09003188 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003189 if (VDBG || (DBG && nri.request.isRequest())) {
3190 log("releasing " + nri.request + " (release request)");
3191 }
3192 handleRemoveNetworkRequest(nri);
Etan Cohenddb720a2019-01-08 12:09:18 -08003193 if (callOnUnavailable) {
3194 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3195 }
Erik Kline57faba92015-11-25 12:49:38 +09003196 }
Erik Klineacdd6392016-07-07 16:50:58 +09003197
Hugo Benichidba33db2017-03-23 22:40:44 +09003198 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003199 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003200 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003201
Erik Klineacdd6392016-07-07 16:50:58 +09003202 synchronized (mUidToNetworkRequestCount) {
3203 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3204 if (requests < 1) {
3205 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3206 nri.mUid);
3207 } else if (requests == 1) {
3208 mUidToNetworkRequestCount.removeAt(
3209 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3210 } else {
3211 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3212 }
3213 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003214
Erik Klineacdd6392016-07-07 16:50:58 +09003215 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3216 if (nri.request.isRequest()) {
3217 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003218 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003219 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003220 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003221 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003222 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003223 log(" Removing from current network " + nai.name() +
3224 ", leaving " + nai.numNetworkRequests() + " requests.");
3225 }
3226 // If there are still lingered requests on this network, don't tear it down,
3227 // but resume lingering instead.
3228 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003229 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003230 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3231 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003232 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003233 wasKept = true;
3234 }
Hugo Benichicd952782017-09-20 11:20:14 +09003235 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003236 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3237 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003238 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003239 }
Erik Klineacdd6392016-07-07 16:50:58 +09003240 }
3241
Erik Klineacdd6392016-07-07 16:50:58 +09003242 // Maintain the illusion. When this request arrived, we might have pretended
3243 // that a network connected to serve it, even though the network was already
3244 // connected. Now that this request has gone away, we might have to pretend
3245 // that the network disconnected. LegacyTypeTracker will generate that
3246 // phantom disconnect for this type.
3247 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3248 boolean doRemove = true;
3249 if (wasKept) {
3250 // check if any of the remaining requests for this network are for the
3251 // same legacy type - if so, don't remove the nai
3252 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3253 NetworkRequest otherRequest = nai.requestAt(i);
3254 if (otherRequest.legacyType == nri.request.legacyType &&
3255 otherRequest.isRequest()) {
3256 if (DBG) log(" still have other legacy request - leaving");
3257 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003258 }
3259 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003260 }
3261
Erik Klineacdd6392016-07-07 16:50:58 +09003262 if (doRemove) {
3263 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003264 }
3265 }
Erik Klineacdd6392016-07-07 16:50:58 +09003266
3267 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3268 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3269 nri.request);
3270 }
3271 } else {
3272 // listens don't have a singular affectedNetwork. Check all networks to see
3273 // if this listen request applies and remove it.
3274 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3275 nai.removeRequest(nri.request.requestId);
3276 if (nri.request.networkCapabilities.hasSignalStrength() &&
3277 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3278 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3279 }
3280 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003281 }
3282 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003283
Lorenzo Colitti18660282016-07-04 12:55:44 +09003284 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003285 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003286 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003287 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003288 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003289 }
3290
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003291 @Override
lucasline252a742019-03-12 13:08:03 +08003292 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3293 enforceNetworkStackSettingsOrSetup();
3294 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3295 encodeBool(accept), encodeBool(always), network));
3296 }
3297
3298 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003299 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003300 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003301 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3302 }
3303
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003304 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3305 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3306 " accept=" + accept + " always=" + always);
3307
3308 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3309 if (nai == null) {
3310 // Nothing to do.
3311 return;
3312 }
3313
3314 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003315 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003316 return;
3317 }
3318
3319 if (!nai.networkMisc.explicitlySelected) {
3320 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3321 }
3322
3323 if (accept != nai.networkMisc.acceptUnvalidated) {
3324 int oldScore = nai.getCurrentScore();
3325 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003326 // If network becomes partial connectivity and user already accepted to use this
3327 // network, we should respect the user's option and don't need to popup the
3328 // PARTIAL_CONNECTIVITY notification to user again.
3329 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003330 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003331 sendUpdatedScoreToFactories(nai);
3332 }
3333
3334 if (always) {
3335 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003336 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003337 }
3338
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003339 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003340 // Tell the NetworkAgent to not automatically reconnect to the network.
3341 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003342 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003343 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003344 }
3345
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003346 }
3347
lucasline252a742019-03-12 13:08:03 +08003348 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3349 boolean always) {
3350 if (DBG) {
3351 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3352 + " always=" + always);
3353 }
3354
3355 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3356 if (nai == null) {
3357 // Nothing to do.
3358 return;
3359 }
3360
3361 if (nai.lastValidated) {
3362 // The network validated while the dialog box was up. Take no action.
3363 return;
3364 }
3365
3366 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3367 nai.networkMisc.acceptPartialConnectivity = accept;
3368 }
3369
3370 // TODO: Use the current design or save the user choice into IpMemoryStore.
3371 if (always) {
3372 nai.asyncChannel.sendMessage(
3373 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3374 }
3375
3376 if (!accept) {
3377 // Tell the NetworkAgent to not automatically reconnect to the network.
3378 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3379 // Tear down the network.
3380 teardownUnneededNetwork(nai);
3381 } else {
lucaslin43338992019-03-20 18:21:59 +08003382 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3383 // result in a partial connectivity result which will be processed by
3384 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003385 try {
lucaslin43338992019-03-20 18:21:59 +08003386 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003387 } catch (RemoteException e) {
3388 e.rethrowFromSystemServer();
3389 }
3390 }
3391 }
3392
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003393 private void handleSetAvoidUnvalidated(Network network) {
3394 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3395 if (nai == null || nai.lastValidated) {
3396 // Nothing to do. The network either disconnected or revalidated.
3397 return;
3398 }
3399 if (!nai.avoidUnvalidated) {
3400 int oldScore = nai.getCurrentScore();
3401 nai.avoidUnvalidated = true;
3402 rematchAllNetworksAndRequests(nai, oldScore);
3403 sendUpdatedScoreToFactories(nai);
3404 }
3405 }
3406
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003407 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003408 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003409 mHandler.sendMessageDelayed(
3410 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3411 PROMPT_UNVALIDATED_DELAY_MS);
3412 }
3413
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003414 @Override
3415 public void startCaptivePortalApp(Network network) {
3416 enforceConnectivityInternalPermission();
3417 mHandler.post(() -> {
3418 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3419 if (nai == null) return;
3420 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003421 try {
3422 nai.networkMonitor().launchCaptivePortalApp();
3423 } catch (RemoteException e) {
3424 e.rethrowFromSystemServer();
3425 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003426 });
3427 }
3428
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003429 /**
3430 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3431 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003432 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003433 * @param appExtras Bundle to use as intent extras for the captive portal application.
3434 * Must be treated as opaque to avoid preventing the captive portal app to
3435 * update its arguments.
3436 */
3437 @Override
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003438 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003439 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3440
3441 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3442 appIntent.putExtras(appExtras);
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003443 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3444 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003445 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3446
3447 Binder.withCleanCallingIdentity(() ->
3448 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3449 }
3450
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003451 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3452 private final Network mNetwork;
3453
3454 private CaptivePortalImpl(Network network) {
3455 mNetwork = network;
3456 }
3457
3458 @Override
3459 public void appResponse(final int response) throws RemoteException {
3460 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3461 enforceSettingsPermission();
3462 }
3463
3464 // getNetworkAgentInfoForNetwork is thread-safe
3465 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3466 if (nai == null) return;
3467
3468 // nai.networkMonitor() is thread-safe
3469 final INetworkMonitor nm = nai.networkMonitor();
3470 if (nm == null) return;
3471
3472 final long token = Binder.clearCallingIdentity();
3473 try {
3474 nm.notifyCaptivePortalAppFinished(response);
3475 } finally {
3476 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3477 Binder.restoreCallingIdentity(token);
3478 }
3479 }
3480
3481 @Override
3482 public void logEvent(int eventId, String packageName) {
3483 enforceSettingsPermission();
3484
3485 new MetricsLogger().action(eventId, packageName);
3486 }
3487 }
3488
Hugo Benichic8e9e122016-09-14 23:23:08 +00003489 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003490 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003491 }
3492
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09003493 /**
3494 * Return whether the device should maintain continuous, working connectivity by switching away
3495 * from WiFi networks having no connectivity.
3496 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3497 */
3498 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003499 if (!checkNetworkStackPermission()) {
3500 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3501 }
3502 return avoidBadWifi();
3503 }
3504
3505
Erik Kline065ab6e2016-10-02 18:02:14 +09003506 private void rematchForAvoidBadWifiUpdate() {
3507 rematchAllNetworksAndRequests(null, 0);
3508 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3509 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3510 sendUpdatedScoreToFactories(nai);
3511 }
3512 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003513 }
3514
Erik Kline065ab6e2016-10-02 18:02:14 +09003515 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003516 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003517 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003518 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003519 if (!configRestrict) {
3520 pw.println("Bad Wi-Fi avoidance: unrestricted");
3521 return;
3522 }
3523
3524 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3525 pw.increaseIndent();
3526 pw.println("Config restrict: " + configRestrict);
3527
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003528 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003529 String description;
3530 // Can't use a switch statement because strings are legal case labels, but null is not.
3531 if ("0".equals(value)) {
3532 description = "get stuck";
3533 } else if (value == null) {
3534 description = "prompt";
3535 } else if ("1".equals(value)) {
3536 description = "avoid";
3537 } else {
3538 description = value + " (?)";
3539 }
3540 pw.println("User setting: " + description);
3541 pw.println("Network overrides:");
3542 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003543 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003544 if (nai.avoidUnvalidated) {
3545 pw.println(nai.name());
3546 }
3547 }
3548 pw.decreaseIndent();
3549 pw.decreaseIndent();
3550 }
3551
lucaslind2e045e02019-01-24 15:55:30 +08003552 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003553 final String action;
3554 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003555 case LOGGED_IN:
3556 action = Settings.ACTION_WIFI_SETTINGS;
3557 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3558 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3559 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3560 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003561 case NO_INTERNET:
3562 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3563 break;
3564 case LOST_INTERNET:
3565 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3566 break;
lucasline252a742019-03-12 13:08:03 +08003567 case PARTIAL_CONNECTIVITY:
3568 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3569 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003570 default:
3571 Slog.wtf(TAG, "Unknown notification type " + type);
3572 return;
3573 }
3574
3575 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003576 if (type != NotificationType.LOGGED_IN) {
3577 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3578 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3579 intent.setClassName("com.android.settings",
3580 "com.android.settings.wifi.WifiNoInternetDialog");
3581 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003582
3583 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3584 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3585 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3586 }
3587
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003588 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003589 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003590 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3591
lucasline252a742019-03-12 13:08:03 +08003592 // Only prompt if the network is unvalidated or network has partial internet connectivity
3593 // and was explicitly selected by the user, and if we haven't already been told to switch
3594 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3595 // because we're already prompting the user to sign in.
3596 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3597 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003598 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3599 // we should reevaluate how to handle acceptPartialConnectivity when network just
3600 // connected.
lucasline252a742019-03-12 13:08:03 +08003601 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003602 return;
3603 }
lucasline252a742019-03-12 13:08:03 +08003604 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3605 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3606 // popup the notification immediately when the network is partial connectivity.
3607 if (nai.partialConnectivity) {
lucaslin975b7d32019-03-21 11:59:22 +08003608 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucasline252a742019-03-12 13:08:03 +08003609 } else {
3610 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3611 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003612 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003613
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003614 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3615 NetworkCapabilities nc = nai.networkCapabilities;
3616 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003617
lucasline252a742019-03-12 13:08:03 +08003618 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3619 return;
3620 }
3621
3622 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003623 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003624 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003625 }
3626
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003627 @Override
3628 public int getMultipathPreference(Network network) {
3629 enforceAccessPermission();
3630
3631 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003632 if (nai != null && nai.networkCapabilities
3633 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003634 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3635 }
3636
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003637 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3638 if (networkPreference != null) {
3639 return networkPreference;
3640 }
3641
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003642 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3643 }
3644
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003645 @Override
3646 public NetworkRequest getDefaultRequest() {
3647 return mDefaultRequest;
3648 }
3649
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003650 private class InternalHandler extends Handler {
3651 public InternalHandler(Looper looper) {
3652 super(looper);
3653 }
3654
3655 @Override
3656 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003657 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003658 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003659 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003660 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003661 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003662 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003663 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003664 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003665 break;
3666 }
Jason Monkdecd2952013-10-10 14:02:51 -04003667 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003668 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003669 break;
3670 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003671 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003672 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3673 break;
3674 }
3675 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3676 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003677 break;
3678 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003679 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003680 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3681 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3682 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003683 break;
3684 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003685 case EVENT_REGISTER_NETWORK_REQUEST:
3686 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003687 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003688 break;
3689 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003690 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3691 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003692 handleRegisterNetworkRequestWithIntent(msg);
3693 break;
3694 }
Erik Kline57faba92015-11-25 12:49:38 +09003695 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3696 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3697 handleTimedOutNetworkRequest(nri);
3698 break;
3699 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003700 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3701 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3702 break;
3703 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003704 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenddb720a2019-01-08 12:09:18 -08003705 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3706 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003707 break;
3708 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003709 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003710 Network network = (Network) msg.obj;
3711 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003712 break;
3713 }
lucasline252a742019-03-12 13:08:03 +08003714 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3715 Network network = (Network) msg.obj;
3716 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3717 toBool(msg.arg2));
3718 break;
3719 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003720 case EVENT_SET_AVOID_UNVALIDATED: {
3721 handleSetAvoidUnvalidated((Network) msg.obj);
3722 break;
3723 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003724 case EVENT_PROMPT_UNVALIDATED: {
3725 handlePromptUnvalidated((Network) msg.obj);
3726 break;
3727 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003728 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3729 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003730 break;
3731 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003732 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003733 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003734 mKeepaliveTracker.handleStartKeepalive(msg);
3735 break;
3736 }
3737 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003738 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003739 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3740 int slot = msg.arg1;
3741 int reason = msg.arg2;
3742 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3743 break;
3744 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003745 case EVENT_SYSTEM_READY: {
3746 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003747 // Might have been called already in handleRegisterNetworkAgent since
3748 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3749 // this several times is fine.
3750 try {
3751 nai.networkMonitor().notifySystemReady();
3752 } catch (RemoteException e) {
3753 e.rethrowFromSystemServer();
3754 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003755 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003756 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003757 break;
3758 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003759 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003760 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003761 break;
3762 }
Erik Klinea24d4592018-01-11 21:07:29 +09003763 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3764 handlePrivateDnsSettingsChanged();
3765 break;
dalyk7301aa42018-03-05 12:42:22 -05003766 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3767 handlePrivateDnsValidationUpdate(
3768 (PrivateDnsValidationUpdate) msg.obj);
3769 break;
junyulai05986c62018-08-07 19:50:45 +08003770 case EVENT_UID_RULES_CHANGED:
3771 handleUidRulesChanged(msg.arg1, msg.arg2);
3772 break;
3773 case EVENT_DATA_SAVER_CHANGED:
3774 handleRestrictBackgroundChanged(toBool(msg.arg1));
3775 break;
lucaslind2e045e02019-01-24 15:55:30 +08003776 case EVENT_TIMEOUT_NOTIFICATION:
3777 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3778 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 }
3780 }
3781 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003782
3783 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003784 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003785 public int tether(String iface, String callerPkg) {
3786 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003787 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003788 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003789 } else {
3790 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3791 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003792 }
3793
3794 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003795 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003796 public int untether(String iface, String callerPkg) {
3797 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003798
3799 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003800 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003801 } else {
3802 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3803 }
3804 }
3805
3806 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003807 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003808 public int getLastTetherError(String iface) {
3809 enforceTetherAccessPermission();
3810
3811 if (isTetheringSupported()) {
3812 return mTethering.getLastTetherError(iface);
3813 } else {
3814 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3815 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003816 }
3817
3818 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003819 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003820 public String[] getTetherableUsbRegexs() {
3821 enforceTetherAccessPermission();
3822 if (isTetheringSupported()) {
3823 return mTethering.getTetherableUsbRegexs();
3824 } else {
3825 return new String[0];
3826 }
3827 }
3828
Lorenzo Colitti18660282016-07-04 12:55:44 +09003829 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003830 public String[] getTetherableWifiRegexs() {
3831 enforceTetherAccessPermission();
3832 if (isTetheringSupported()) {
3833 return mTethering.getTetherableWifiRegexs();
3834 } else {
3835 return new String[0];
3836 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003837 }
3838
Lorenzo Colitti18660282016-07-04 12:55:44 +09003839 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003840 public String[] getTetherableBluetoothRegexs() {
3841 enforceTetherAccessPermission();
3842 if (isTetheringSupported()) {
3843 return mTethering.getTetherableBluetoothRegexs();
3844 } else {
3845 return new String[0];
3846 }
3847 }
3848
Lorenzo Colitti18660282016-07-04 12:55:44 +09003849 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003850 public int setUsbTethering(boolean enable, String callerPkg) {
3851 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003852 if (isTetheringSupported()) {
3853 return mTethering.setUsbTethering(enable);
3854 } else {
3855 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3856 }
3857 }
3858
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003859 // TODO - move iface listing, queries, etc to new module
3860 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003861 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003862 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003863 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003864 return mTethering.getTetherableIfaces();
3865 }
3866
Lorenzo Colitti18660282016-07-04 12:55:44 +09003867 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003868 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003869 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003870 return mTethering.getTetheredIfaces();
3871 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003872
Lorenzo Colitti18660282016-07-04 12:55:44 +09003873 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003874 public String[] getTetheringErroredIfaces() {
3875 enforceTetherAccessPermission();
3876 return mTethering.getErroredIfaces();
3877 }
3878
Lorenzo Colitti18660282016-07-04 12:55:44 +09003879 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003880 public String[] getTetheredDhcpRanges() {
3881 enforceConnectivityInternalPermission();
3882 return mTethering.getTetheredDhcpRanges();
3883 }
3884
Udam Saini0e94c362017-06-07 12:06:28 -07003885 @Override
3886 public boolean isTetheringSupported(String callerPkg) {
3887 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3888 return isTetheringSupported();
3889 }
3890
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003891 // if ro.tether.denied = true we default to no tethering
3892 // gservices could set the secure setting to 1 though to enable it on a build where it
3893 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003894 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003895 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3896 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3897 Settings.Global.TETHER_SUPPORTED, defaultVal));
3898 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003899 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003900
3901 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3902 boolean adminUser = false;
3903 final long token = Binder.clearCallingIdentity();
3904 try {
3905 adminUser = mUserManager.isAdminUser();
3906 } finally {
3907 Binder.restoreCallingIdentity(token);
3908 }
3909
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003910 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003911 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003912
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003913 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003914 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3915 String callerPkg) {
3916 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003917 if (!isTetheringSupported()) {
3918 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3919 return;
3920 }
3921 mTethering.startTethering(type, receiver, showProvisioningUi);
3922 }
3923
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003924 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003925 public void stopTethering(int type, String callerPkg) {
3926 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003927 mTethering.stopTethering(type);
3928 }
3929
markchienf2731272019-01-16 17:44:13 +08003930 /**
3931 * Get the latest value of the tethering entitlement check.
3932 *
3933 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3934 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3935 * if it's really needed.
3936 */
3937 @Override
markchien9554abf2019-03-06 16:25:00 +08003938 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003939 boolean showEntitlementUi, String callerPkg) {
3940 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003941 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003942 }
3943
markchien26299ed2019-02-27 14:56:11 +08003944 /** Register tethering event callback. */
3945 @Override
3946 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3947 String callerPkg) {
3948 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3949 mTethering.registerTetheringEventCallback(callback);
3950 }
3951
3952 /** Unregister tethering event callback. */
3953 @Override
3954 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3955 String callerPkg) {
3956 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3957 mTethering.unregisterTetheringEventCallback(callback);
3958 }
3959
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003960 // Called when we lose the default network and have no replacement yet.
3961 // This will automatically be cleared after X seconds or a new default network
3962 // becomes CONNECTED, whichever happens first. The timer is started by the
3963 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003964 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003965 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003966 if (mNetTransitionWakeLock.isHeld()) {
3967 return;
3968 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003969 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003970 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3971 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003972 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003973 mWakelockLogs.log("ACQUIRE for " + forWhom);
3974 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3975 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003976 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003977
Hugo Benichi4c31b342017-03-30 23:18:10 +09003978 // Called when we gain a new default network to release the network transition wakelock in a
3979 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3980 // message is cancelled.
3981 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003982 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003983 if (!mNetTransitionWakeLock.isHeld()) {
3984 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003985 }
3986 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003987 // Cancel self timeout on wakelock hold.
3988 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3989 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3990 mHandler.sendMessageDelayed(msg, 1000);
3991 }
3992
3993 // Called when either message of ensureNetworkTransitionWakelock or
3994 // scheduleReleaseNetworkTransitionWakelock is processed.
3995 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3996 String event = eventName(eventId);
3997 synchronized (this) {
3998 if (!mNetTransitionWakeLock.isHeld()) {
3999 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4000 Slog.w(TAG, "expected Net Transition WakeLock to be held");
4001 return;
4002 }
4003 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09004004 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4005 mTotalWakelockDurationMs += lockDuration;
4006 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4007 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004008 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09004009 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09004010 }
4011
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004012 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09004013 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07004014 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004015 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004016 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004017 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004018 }
4019
Lorenzo Colitti18660282016-07-04 12:55:44 +09004020 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004021 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004022 enforceAccessPermission();
4023 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004024 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004025 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004026 mHandler.sendMessage(
4027 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4028 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004029
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004030 private void handleReportNetworkConnectivity(
4031 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004032 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004033 if (network == null) {
4034 nai = getDefaultNetwork();
4035 } else {
4036 nai = getNetworkAgentInfoForNetwork(network);
4037 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004038 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4039 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4040 return;
4041 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004042 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004043 if (hasConnectivity == nai.lastValidated) {
4044 return;
4045 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004046 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004047 int netid = nai.network.netId;
4048 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004049 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004050 // Validating a network that has not yet connected could result in a call to
4051 // rematchNetworkAndRequests() which is not meant to work on such networks.
4052 if (!nai.everConnected) {
4053 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004054 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004055 LinkProperties lp = getLinkProperties(nai);
4056 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4057 return;
4058 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004059 try {
4060 nai.networkMonitor().forceReevaluation(uid);
4061 } catch (RemoteException e) {
4062 e.rethrowFromSystemServer();
4063 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004064 }
4065
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004066 /**
4067 * Returns information about the proxy a certain network is using. If given a null network, it
4068 * it will return the proxy for the bound network for the caller app or the default proxy if
4069 * none.
4070 *
4071 * @param network the network we want to get the proxy information for.
4072 * @return Proxy information if a network has a proxy configured, or otherwise null.
4073 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004074 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004075 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004076 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004077 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004078 if (network == null) {
4079 // Get the network associated with the calling UID.
4080 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4081 true);
4082 if (activeNetwork == null) {
4083 return null;
4084 }
4085 return getLinkPropertiesProxyInfo(activeNetwork);
4086 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4087 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4088 // caller may not have.
4089 return getLinkPropertiesProxyInfo(network);
4090 }
4091 // No proxy info available if the calling UID does not have network access.
4092 return null;
4093 }
4094
4095 @VisibleForTesting
4096 protected boolean queryUserAccess(int uid, int netId) {
4097 return NetworkUtils.queryUserAccess(uid, netId);
4098 }
4099
4100 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004101 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4102 if (nai == null) return null;
4103 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004104 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4105 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004106 }
4107 }
4108
Chalard Jean3c443fc2018-06-07 18:37:59 +09004109 @Override
4110 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004111 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004112 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004113 }
4114
Chalard Jean5afbc832018-06-07 18:02:37 +09004115 @Override
4116 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004117 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004118 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004119 }
4120
Jason Monk207900c2014-04-25 15:00:09 -04004121 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004122 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004123 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004124 proxy = null;
4125 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004126 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004127 }
4128
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004129 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4130 // when any network changes proxy.
4131 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4132 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004133 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004134 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4135 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4136
Chalard Jean4949dd72018-06-07 17:41:29 +09004137 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004138 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004139 }
4140 }
4141
Robert Greenwalt434203a2010-10-11 16:00:27 -07004142 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004143 final private HashMap<Uri, Integer> mUriEventMap;
4144 final private Context mContext;
4145 final private Handler mHandler;
4146
4147 SettingsObserver(Context context, Handler handler) {
4148 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004149 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004150 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004151 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004152 }
4153
Erik Klineda4bfa82015-04-30 12:58:40 +09004154 void observe(Uri uri, int what) {
4155 mUriEventMap.put(uri, what);
4156 final ContentResolver resolver = mContext.getContentResolver();
4157 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004158 }
4159
4160 @Override
4161 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004162 Slog.wtf(TAG, "Should never be reached.");
4163 }
4164
4165 @Override
4166 public void onChange(boolean selfChange, Uri uri) {
4167 final Integer what = mUriEventMap.get(uri);
4168 if (what != null) {
4169 mHandler.obtainMessage(what.intValue()).sendToTarget();
4170 } else {
4171 loge("No matching event to send for URI=" + uri);
4172 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004173 }
4174 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004175
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004176 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004177 Slog.d(TAG, s);
4178 }
4179
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004180 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004181 Slog.e(TAG, s);
4182 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004183
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004184 private static void loge(String s, Throwable t) {
4185 Slog.e(TAG, s, t);
4186 }
4187
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004188 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004189 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004190 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4191 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4192 *
4193 * @param oldPackage Package name of the application which currently controls VPN, which will
4194 * be replaced. If there is no such application, this should should either be
4195 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4196 * @param newPackage Package name of the application which should gain control of VPN, or
4197 * {@code null} to disable.
4198 * @param userId User for whom to prepare the new VPN.
4199 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004200 * @hide
4201 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004202 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004203 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4204 int userId) {
4205 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004206
Hugo Benichi20035e02017-04-26 14:53:28 +09004207 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004208 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004209 Vpn vpn = mVpns.get(userId);
4210 if (vpn != null) {
4211 return vpn.prepare(oldPackage, newPackage);
4212 } else {
4213 return false;
4214 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004215 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004216 }
4217
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004218 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004219 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4220 * This method is used by system-privileged apps.
4221 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4222 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4223 *
4224 * @param packageName The package for which authorization state should change.
4225 * @param userId User for whom {@code packageName} is installed.
4226 * @param authorized {@code true} if this app should be able to start a VPN connection without
4227 * explicit user approval, {@code false} if not.
4228 *
Jeff Davidson05542602014-08-11 14:07:27 -07004229 * @hide
4230 */
4231 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004232 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4233 enforceCrossUserPermission(userId);
4234
Hugo Benichi20035e02017-04-26 14:53:28 +09004235 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004236 Vpn vpn = mVpns.get(userId);
4237 if (vpn != null) {
4238 vpn.setPackageAuthorization(packageName, authorized);
4239 }
Jeff Davidson05542602014-08-11 14:07:27 -07004240 }
4241 }
4242
4243 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004244 * Configure a TUN interface and return its file descriptor. Parameters
4245 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004246 * and not available in ConnectivityManager. Permissions are checked in
4247 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004248 * @hide
4249 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004250 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004251 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004252 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004253 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004254 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004255 return mVpns.get(user).establish(config);
4256 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004257 }
4258
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004259 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004260 * Start legacy VPN, controlling native daemons as needed. Creates a
4261 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004262 */
4263 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004264 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004265 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004266 final LinkProperties egress = getActiveLinkProperties();
4267 if (egress == null) {
4268 throw new IllegalStateException("Missing active network connection");
4269 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004270 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004271 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004272 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4273 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004274 }
4275
4276 /**
4277 * Return the information of the ongoing legacy VPN. This method is used
4278 * by VpnSettings and not available in ConnectivityManager. Permissions
4279 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004280 */
4281 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004282 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4283 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004284
Hugo Benichi20035e02017-04-26 14:53:28 +09004285 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004286 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004287 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004288 }
4289
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004290 /**
Varun Anandd33cbc62019-02-07 14:13:13 -08004291 * Return the information of all ongoing VPNs.
4292 *
4293 * <p>This method is used to update NetworkStatsService.
4294 *
4295 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004296 */
Varun Anandd33cbc62019-02-07 14:13:13 -08004297 private VpnInfo[] getAllVpnInfo() {
4298 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004299 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004300 if (mLockdownEnabled) {
4301 return new VpnInfo[0];
4302 }
4303
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004304 List<VpnInfo> infoList = new ArrayList<>();
4305 for (int i = 0; i < mVpns.size(); i++) {
4306 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4307 if (info != null) {
4308 infoList.add(info);
4309 }
4310 }
4311 return infoList.toArray(new VpnInfo[infoList.size()]);
4312 }
4313 }
4314
4315 /**
4316 * @return VPN information for accounting, or null if we can't retrieve all required
4317 * information, e.g primary underlying iface.
4318 */
4319 @Nullable
4320 private VpnInfo createVpnInfo(Vpn vpn) {
4321 VpnInfo info = vpn.getVpnInfo();
4322 if (info == null) {
4323 return null;
4324 }
4325 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4326 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4327 // the underlyingNetworks list.
4328 if (underlyingNetworks == null) {
4329 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4330 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4331 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4332 }
4333 } else if (underlyingNetworks.length > 0) {
4334 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4335 if (linkProperties != null) {
4336 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4337 }
4338 }
4339 return info.primaryUnderlyingIface == null ? null : info;
4340 }
4341
4342 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004343 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4344 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004345 * Permissions are checked in Vpn class.
4346 * @hide
4347 */
4348 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004349 public VpnConfig getVpnConfig(int userId) {
4350 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004351 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004352 Vpn vpn = mVpns.get(userId);
4353 if (vpn != null) {
4354 return vpn.getVpnConfig();
4355 } else {
4356 return null;
4357 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004358 }
4359 }
4360
Chalard Jean6b65ec72018-05-18 22:02:56 +09004361 /**
4362 * Ask all VPN objects to recompute and update their capabilities.
4363 *
4364 * When underlying networks change, VPNs may have to update capabilities to reflect things
4365 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4366 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4367 * handler thread through their agent, this is asynchronous. When the capabilities objects
4368 * are computed they will be up-to-date as they are computed synchronously from here and
4369 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004370 */
4371 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004372 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004373 synchronized (mVpns) {
4374 for (int i = 0; i < mVpns.size(); i++) {
4375 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004376 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4377 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004378 }
4379 }
4380 }
4381
Varun Anand4fa80e82019-02-06 10:13:38 -08004382 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4383 ensureRunningOnConnectivityServiceThread();
4384 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4385 if (vpnNai == null || nc == null) {
4386 return;
4387 }
4388 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4389 }
4390
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004391 @Override
4392 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004393 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4394 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4395 return false;
4396 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004397
Hugo Benichi69744342017-11-27 10:57:16 +09004398 synchronized (mVpns) {
4399 // Tear down existing lockdown if profile was removed
4400 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4401 if (mLockdownEnabled) {
4402 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4403 if (profileTag == null) {
4404 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4405 return false;
4406 }
4407 String profileName = new String(profileTag);
4408 final VpnProfile profile = VpnProfile.decode(
4409 profileName, mKeyStore.get(Credentials.VPN + profileName));
4410 if (profile == null) {
4411 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4412 setLockdownTracker(null);
4413 return true;
4414 }
4415 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004416 Vpn vpn = mVpns.get(user);
4417 if (vpn == null) {
4418 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4419 return false;
4420 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004421 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004422 } else {
4423 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004424 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004425 }
4426
4427 return true;
4428 }
4429
4430 /**
4431 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4432 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4433 */
Hugo Benichi69744342017-11-27 10:57:16 +09004434 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004435 private void setLockdownTracker(LockdownVpnTracker tracker) {
4436 // Shutdown any existing tracker
4437 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004438 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4439 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004440 mLockdownTracker = null;
4441 if (existing != null) {
4442 existing.shutdown();
4443 }
4444
Robin Leec3736bc2017-03-10 16:19:54 +00004445 if (tracker != null) {
4446 mLockdownTracker = tracker;
4447 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004448 }
4449 }
4450
Hugo Benichi69744342017-11-27 10:57:16 +09004451 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004452 private void throwIfLockdownEnabled() {
4453 if (mLockdownEnabled) {
4454 throw new IllegalStateException("Unavailable in lockdown mode");
4455 }
4456 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004457
Robin Lee244ce8e2016-01-05 18:03:46 +00004458 /**
Robin Lee17e61832016-05-09 13:46:28 +01004459 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4460 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004461 *
Robin Lee17e61832016-05-09 13:46:28 +01004462 * @return {@code true} if the service was started, the service was already connected, or there
4463 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004464 */
Robin Lee17e61832016-05-09 13:46:28 +01004465 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004466 synchronized (mVpns) {
4467 Vpn vpn = mVpns.get(userId);
4468 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004469 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004470 // exists already.
4471 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4472 return false;
4473 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004474
Robin Lee812800c2016-05-13 15:38:08 +01004475 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004476 }
4477 }
4478
4479 @Override
Charles He36738632017-05-15 17:07:18 +01004480 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4481 enforceSettingsPermission();
4482 enforceCrossUserPermission(userId);
4483
4484 synchronized (mVpns) {
4485 Vpn vpn = mVpns.get(userId);
4486 if (vpn == null) {
4487 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4488 return false;
4489 }
4490 return vpn.isAlwaysOnPackageSupported(packageName);
4491 }
4492 }
4493
4494 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004495 public boolean setAlwaysOnVpnPackage(
4496 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4497 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004498 enforceCrossUserPermission(userId);
4499
Robin Lee244ce8e2016-01-05 18:03:46 +00004500 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004501 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4502 if (LockdownVpnTracker.isEnabled()) {
4503 return false;
4504 }
4505
Robin Lee244ce8e2016-01-05 18:03:46 +00004506 Vpn vpn = mVpns.get(userId);
4507 if (vpn == null) {
4508 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4509 return false;
4510 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004511 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004512 return false;
4513 }
Robin Lee17e61832016-05-09 13:46:28 +01004514 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004515 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004516 return false;
4517 }
4518 }
4519 return true;
4520 }
4521
4522 @Override
4523 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004524 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004525 enforceCrossUserPermission(userId);
4526
4527 synchronized (mVpns) {
4528 Vpn vpn = mVpns.get(userId);
4529 if (vpn == null) {
4530 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4531 return null;
4532 }
4533 return vpn.getAlwaysOnPackage();
4534 }
4535 }
4536
Wink Savilleab9321d2013-06-29 21:10:57 -07004537 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004538 public boolean isVpnLockdownEnabled(int userId) {
4539 enforceControlAlwaysOnVpnPermission();
4540 enforceCrossUserPermission(userId);
4541
4542 synchronized (mVpns) {
4543 Vpn vpn = mVpns.get(userId);
4544 if (vpn == null) {
4545 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4546 return false;
4547 }
4548 return vpn.getLockdown();
4549 }
4550 }
4551
4552 @Override
4553 public List<String> getVpnLockdownWhitelist(int userId) {
4554 enforceControlAlwaysOnVpnPermission();
4555 enforceCrossUserPermission(userId);
4556
4557 synchronized (mVpns) {
4558 Vpn vpn = mVpns.get(userId);
4559 if (vpn == null) {
4560 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4561 return null;
4562 }
4563 return vpn.getLockdownWhitelist();
4564 }
4565 }
4566
4567 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004568 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004569 // TODO: Remove? Any reason to trigger a provisioning check?
4570 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004571 }
4572
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004573 /** Location to an updatable file listing carrier provisioning urls.
4574 * An example:
4575 *
4576 * <?xml version="1.0" encoding="utf-8"?>
4577 * <provisioningUrls>
4578 * <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 -07004579 * </provisioningUrls>
4580 */
4581 private static final String PROVISIONING_URL_PATH =
4582 "/data/misc/radio/provisioning_urls.xml";
4583 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004584
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004585 /** XML tag for root element. */
4586 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4587 /** XML tag for individual url */
4588 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004589 /** XML attribute for mcc */
4590 private static final String ATTR_MCC = "mcc";
4591 /** XML attribute for mnc */
4592 private static final String ATTR_MNC = "mnc";
4593
Paul Jensen434dde82015-06-11 09:43:30 -04004594 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004595 FileReader fileReader = null;
4596 XmlPullParser parser = null;
4597 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004598
4599 try {
4600 fileReader = new FileReader(mProvisioningUrlFile);
4601 parser = Xml.newPullParser();
4602 parser.setInput(fileReader);
4603 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4604
4605 while (true) {
4606 XmlUtils.nextElement(parser);
4607
4608 String element = parser.getName();
4609 if (element == null) break;
4610
Paul Jensen434dde82015-06-11 09:43:30 -04004611 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004612 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4613 try {
4614 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4615 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4616 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4617 parser.next();
4618 if (parser.getEventType() == XmlPullParser.TEXT) {
4619 return parser.getText();
4620 }
4621 }
4622 }
4623 } catch (NumberFormatException e) {
4624 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4625 }
4626 }
4627 }
4628 return null;
4629 } catch (FileNotFoundException e) {
4630 loge("Carrier Provisioning Urls file not found");
4631 } catch (XmlPullParserException e) {
4632 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4633 } catch (IOException e) {
4634 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4635 } finally {
4636 if (fileReader != null) {
4637 try {
4638 fileReader.close();
4639 } catch (IOException e) {}
4640 }
4641 }
4642 return null;
4643 }
4644
Wink Saville42d4f082013-07-20 20:31:59 -07004645 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004646 public String getMobileProvisioningUrl() {
4647 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004648 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004649 if (TextUtils.isEmpty(url)) {
4650 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004651 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004652 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004653 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004654 }
Wink Saville8cf35602013-07-10 23:00:07 -07004655 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004656 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004657 String phoneNumber = mTelephonyManager.getLine1Number();
4658 if (TextUtils.isEmpty(phoneNumber)) {
4659 phoneNumber = "0000000000";
4660 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004661 url = String.format(url,
4662 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4663 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004664 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004665 }
4666
Wink Savilleab9321d2013-06-29 21:10:57 -07004667 return url;
4668 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004669
Wink Saville948282b2013-08-29 08:55:16 -07004670 @Override
4671 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004672 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004673 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004674 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4675 return;
4676 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004677 final long ident = Binder.clearCallingIdentity();
4678 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004679 // Concatenate the range of types onto the range of NetIDs.
4680 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4681 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004682 } finally {
4683 Binder.restoreCallingIdentity(ident);
4684 }
Wink Saville948282b2013-08-29 08:55:16 -07004685 }
Wink Saville7788c612013-08-29 14:57:08 -07004686
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004687 @Override
4688 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004689 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004690 final long ident = Binder.clearCallingIdentity();
4691 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004692 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004693 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004694 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4695 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004696 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004697 } finally {
4698 Binder.restoreCallingIdentity(ident);
4699 }
4700 }
4701
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004702 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004703 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004704 Vpn userVpn = mVpns.get(userId);
4705 if (userVpn != null) {
4706 loge("Starting user already has a VPN");
4707 return;
4708 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004709 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004710 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004711 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4712 updateLockdownVpn();
4713 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004714 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004715 }
4716
4717 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004718 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004719 Vpn userVpn = mVpns.get(userId);
4720 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004721 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004722 return;
4723 }
Robin Lee17e61832016-05-09 13:46:28 +01004724 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004725 mVpns.delete(userId);
4726 }
4727 }
4728
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004729 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004730 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004731 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004732 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004733 final int vpnsSize = mVpns.size();
4734 for (int i = 0; i < vpnsSize; i++) {
4735 Vpn vpn = mVpns.valueAt(i);
4736 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004737 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4738 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004739 }
4740 }
4741 }
4742
4743 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004744 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004745 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004746 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004747 final int vpnsSize = mVpns.size();
4748 for (int i = 0; i < vpnsSize; i++) {
4749 Vpn vpn = mVpns.valueAt(i);
4750 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004751 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4752 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004753 }
4754 }
4755 }
4756
junyulai2454b692018-11-01 17:16:31 +08004757 private void onPackageAdded(String packageName, int uid) {
4758 if (TextUtils.isEmpty(packageName) || uid < 0) {
4759 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4760 return;
4761 }
4762 mPermissionMonitor.onPackageAdded(packageName, uid);
4763 }
4764
junyulaiefb04d32018-11-12 22:39:30 +08004765 private void onPackageReplaced(String packageName, int uid) {
4766 if (TextUtils.isEmpty(packageName) || uid < 0) {
4767 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4768 return;
4769 }
4770 final int userId = UserHandle.getUserId(uid);
4771 synchronized (mVpns) {
4772 final Vpn vpn = mVpns.get(userId);
4773 if (vpn == null) {
4774 return;
4775 }
4776 // Legacy always-on VPN won't be affected since the package name is not set.
4777 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4778 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4779 + userId);
4780 vpn.startAlwaysOnVpn();
4781 }
4782 }
4783 }
4784
4785 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004786 if (TextUtils.isEmpty(packageName) || uid < 0) {
4787 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4788 return;
4789 }
4790 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004791
4792 final int userId = UserHandle.getUserId(uid);
4793 synchronized (mVpns) {
4794 final Vpn vpn = mVpns.get(userId);
4795 if (vpn == null) {
4796 return;
4797 }
4798 // Legacy always-on VPN won't be affected since the package name is not set.
4799 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4800 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4801 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004802 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004803 }
4804 }
junyulai2454b692018-11-01 17:16:31 +08004805 }
4806
Robin Lee89e7a692016-02-29 14:38:17 +00004807 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004808 synchronized (mVpns) {
4809 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4810 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4811 updateLockdownVpn();
4812 } else {
4813 startAlwaysOnVpn(userId);
4814 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004815 }
4816 }
4817
junyulai2454b692018-11-01 17:16:31 +08004818 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004819 @Override
4820 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004821 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004822 final String action = intent.getAction();
4823 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004824 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4825 final Uri packageData = intent.getData();
4826 final String packageName =
4827 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004828 if (userId == UserHandle.USER_NULL) return;
4829
Robin Lee323f29d2016-05-04 16:38:06 +01004830 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004831 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004832 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004833 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004834 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4835 onUserAdded(userId);
4836 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4837 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004838 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4839 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004840 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4841 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004842 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4843 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004844 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004845 final boolean isReplacing = intent.getBooleanExtra(
4846 Intent.EXTRA_REPLACING, false);
4847 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004848 }
4849 }
4850 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004851
Robin Lee95204e02017-01-27 11:59:22 +00004852 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4853 @Override
4854 public void onReceive(Context context, Intent intent) {
4855 // Try creating lockdown tracker, since user present usually means
4856 // unlocked keystore.
4857 updateLockdownVpn();
4858 mContext.unregisterReceiver(this);
4859 }
4860 };
4861
Chalard Jean4133a122018-06-04 13:33:12 +09004862 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4863 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004864
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004865 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4866 // Map from UID to number of NetworkRequests that UID has filed.
4867 @GuardedBy("mUidToNetworkRequestCount")
4868 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4869
Robert Greenwalta67be032014-05-16 15:49:14 -07004870 private static class NetworkFactoryInfo {
4871 public final String name;
4872 public final Messenger messenger;
4873 public final AsyncChannel asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004874 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004875
Chalard Jean05ab6812018-05-02 21:14:54 +09004876 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4877 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004878 this.name = name;
4879 this.messenger = messenger;
4880 this.asyncChannel = asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004881 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004882 }
4883 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004884
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004885 private void ensureNetworkRequestHasType(NetworkRequest request) {
4886 if (request.type == NetworkRequest.Type.NONE) {
4887 throw new IllegalArgumentException(
4888 "All NetworkRequests in ConnectivityService must have a type");
4889 }
4890 }
4891
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004892 /**
4893 * Tracks info about the requester.
4894 * Also used to notice when the calling process dies so we can self-expire
4895 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004896 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004897 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004898 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004899 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004900 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004901 final int mPid;
4902 final int mUid;
4903 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004904
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004905 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004906 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004907 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004908 mPendingIntent = pi;
4909 messenger = null;
4910 mBinder = null;
4911 mPid = getCallingPid();
4912 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004913 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004914 }
4915
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004916 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004917 super();
4918 messenger = m;
4919 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004920 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004921 mBinder = binder;
4922 mPid = getCallingPid();
4923 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004924 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004925 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004926
4927 try {
4928 mBinder.linkToDeath(this, 0);
4929 } catch (RemoteException e) {
4930 binderDied();
4931 }
4932 }
4933
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004934 private void enforceRequestCountLimit() {
4935 synchronized (mUidToNetworkRequestCount) {
4936 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4937 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004938 throw new ServiceSpecificException(
4939 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004940 }
4941 mUidToNetworkRequestCount.put(mUid, networkRequests);
4942 }
4943 }
4944
Robert Greenwalt9258c642014-03-26 16:47:06 -07004945 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004946 if (mBinder != null) {
4947 mBinder.unlinkToDeath(this, 0);
4948 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004949 }
4950
4951 public void binderDied() {
4952 log("ConnectivityService NetworkRequestInfo binderDied(" +
4953 request + ", " + mBinder + ")");
4954 releaseNetworkRequest(request);
4955 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004956
4957 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004958 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004959 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004960 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004961 }
4962
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004963 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4964 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4965 if (badCapability != null) {
4966 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004967 }
4968 }
4969
paulhu3d67f532019-03-22 16:35:06 +08004970 // This checks that the passed capabilities either do not request a specific SSID/SignalStrength
4971 // , or the calling app has permission to do so.
Chalard Jeanb03a6222018-04-11 21:09:10 +09004972 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4973 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004974 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004975 throw new SecurityException("Insufficient permissions to request a specific SSID");
4976 }
paulhu3d67f532019-03-22 16:35:06 +08004977
4978 if (nc.hasSignalStrength()
4979 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
4980 throw new SecurityException(
4981 "Insufficient permissions to request a specific signal strength");
4982 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09004983 }
4984
Erik Kline9d598e12015-07-13 16:37:51 +09004985 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004986 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004987 synchronized (nai) {
4988 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4989 if (nri.request.networkCapabilities.hasSignalStrength() &&
4990 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4991 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4992 }
4993 }
4994 }
Chalard Jean4133a122018-06-04 13:33:12 +09004995 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004996 }
4997
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004998 private void updateSignalStrengthThresholds(
4999 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5000 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09005001 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005002 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
5003
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005004 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005005 String detail;
5006 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5007 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5008 } else {
5009 detail = reason;
5010 }
5011 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5012 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
5013 }
5014
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005015 nai.asyncChannel.sendMessage(
5016 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09005017 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005018 }
5019
Etan Cohen859748f2017-04-03 17:42:34 -07005020 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5021 if (nc == null) {
5022 return;
5023 }
5024 NetworkSpecifier ns = nc.getNetworkSpecifier();
5025 if (ns == null) {
5026 return;
5027 }
5028 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5029 ns.assertValidFromUid(Binder.getCallingUid());
5030 }
5031
Robert Greenwalt9258c642014-03-26 16:47:06 -07005032 @Override
5033 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005034 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005035 final NetworkRequest.Type type = (networkCapabilities == null)
5036 ? NetworkRequest.Type.TRACK_DEFAULT
5037 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005038 // If the requested networkCapabilities is null, take them instead from
5039 // the default network request. This allows callers to keep track of
5040 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005041 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005042 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005043 enforceAccessPermission();
5044 } else {
5045 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5046 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005047 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5048 // of the app when the request is filed, but we never change the request if the app
5049 // changes network state. http://b/29964605
5050 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005051 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005052 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005053 ensureSufficientPermissionsForRequest(networkCapabilities,
5054 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005055 // Set the UID range for this request to the single UID of the requester, or to an empty
5056 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005057 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5058 // are no visible methods to set the UIDs, an app could use reflection to try and get
5059 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005060 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005061
Etan Cohenba07c8c2017-02-05 10:42:27 -08005062 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005063 throw new IllegalArgumentException("Bad timeout specified");
5064 }
Etan Cohen859748f2017-04-03 17:42:34 -07005065 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005066
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005067 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005068 nextNetworkRequestId(), type);
5069 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005070 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005071
5072 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005073 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005074 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005075 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005076 }
5077 return networkRequest;
5078 }
5079
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005080 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005081 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005082 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005083 } else {
5084 enforceChangePermission();
5085 }
5086 }
5087
fenglub15e72b2015-03-20 11:29:56 -07005088 @Override
fengludb571472015-04-21 17:12:05 -07005089 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005090 enforceAccessPermission();
5091 NetworkAgentInfo nai = null;
5092 if (network == null) {
5093 return false;
5094 }
5095 synchronized (mNetworkForNetId) {
5096 nai = mNetworkForNetId.get(network.netId);
5097 }
5098 if (nai != null) {
5099 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005100 synchronized (mBandwidthRequests) {
5101 final int uid = Binder.getCallingUid();
5102 Integer uidReqs = mBandwidthRequests.get(uid);
5103 if (uidReqs == null) {
5104 uidReqs = new Integer(0);
5105 }
5106 mBandwidthRequests.put(uid, ++uidReqs);
5107 }
fenglub15e72b2015-03-20 11:29:56 -07005108 return true;
5109 }
5110 return false;
5111 }
5112
Felipe Lemeee27cab2016-06-20 16:36:29 -07005113 private boolean isSystem(int uid) {
5114 return uid < Process.FIRST_APPLICATION_UID;
5115 }
fenglub15e72b2015-03-20 11:29:56 -07005116
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005117 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005118 final int uid = Binder.getCallingUid();
5119 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005120 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005121 return;
5122 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005123 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5124 // Policy already enforced.
5125 return;
5126 }
5127 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5128 // If UID is restricted, don't allow them to bring up metered APNs.
5129 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005130 }
5131 }
5132
Robert Greenwalt9258c642014-03-26 16:47:06 -07005133 @Override
5134 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5135 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005136 checkNotNull(operation, "PendingIntent cannot be null.");
5137 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5138 enforceNetworkRequestPermissions(networkCapabilities);
5139 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005140 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005141 ensureSufficientPermissionsForRequest(networkCapabilities,
5142 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005143 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005144 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005145
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005146 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005147 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5148 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005149 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005150 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5151 nri));
5152 return networkRequest;
5153 }
5154
Jeremy Joslin79294842014-12-03 17:15:28 -08005155 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5156 mHandler.sendMessageDelayed(
5157 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5158 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5159 }
5160
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005161 @Override
5162 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005163 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005164 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5165 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005166 }
5167
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005168 // In order to implement the compatibility measure for pre-M apps that call
5169 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5170 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5171 // This ensures it has permission to do so.
5172 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5173 if (nc == null) {
5174 return false;
5175 }
5176 int[] transportTypes = nc.getTransportTypes();
5177 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5178 return false;
5179 }
5180 try {
5181 mContext.enforceCallingOrSelfPermission(
5182 android.Manifest.permission.ACCESS_WIFI_STATE,
5183 "ConnectivityService");
5184 } catch (SecurityException e) {
5185 return false;
5186 }
5187 return true;
5188 }
5189
Robert Greenwalt9258c642014-03-26 16:47:06 -07005190 @Override
5191 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5192 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005193 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5194 enforceAccessPermission();
5195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005196
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005197 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005198 ensureSufficientPermissionsForRequest(networkCapabilities,
5199 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005200 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005201 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5202 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5203 // onLost and onAvailable callbacks when networks move in and out of the background.
5204 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5205 // can't request networks.
5206 restrictBackgroundRequestForCaller(nc);
5207 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005208
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005209 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005210 NetworkRequest.Type.LISTEN);
5211 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005212 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005213
5214 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5215 return networkRequest;
5216 }
5217
5218 @Override
5219 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5220 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005221 checkNotNull(operation, "PendingIntent cannot be null.");
5222 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5223 enforceAccessPermission();
5224 }
Etan Cohen859748f2017-04-03 17:42:34 -07005225 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005226 ensureSufficientPermissionsForRequest(networkCapabilities,
5227 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005228
Chalard Jeandda156a2018-01-10 21:19:32 +09005229 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005230 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005231
5232 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005233 NetworkRequest.Type.LISTEN);
5234 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005235 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005236
5237 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005238 }
5239
Erik Klineacdd6392016-07-07 16:50:58 +09005240 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005241 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005242 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005243 mHandler.sendMessage(mHandler.obtainMessage(
5244 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005245 }
5246
5247 @Override
Chalard Jean05ab6812018-05-02 21:14:54 +09005248 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005249 enforceConnectivityInternalPermission();
Chalard Jean05ab6812018-05-02 21:14:54 +09005250 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5251 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005252 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean05ab6812018-05-02 21:14:54 +09005253 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005254 }
5255
Robert Greenwalta67be032014-05-16 15:49:14 -07005256 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005257 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005258 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5259 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5260 }
5261
5262 @Override
5263 public void unregisterNetworkFactory(Messenger messenger) {
5264 enforceConnectivityInternalPermission();
5265 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5266 }
5267
5268 private void handleUnregisterNetworkFactory(Messenger messenger) {
5269 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5270 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005271 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005272 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005273 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005274 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005275 }
5276
Robert Greenwalt7b816022014-04-18 15:25:25 -07005277 /**
5278 * NetworkAgentInfo supporting a request by requestId.
5279 * These have already been vetted (their Capabilities satisfy the request)
5280 * and the are the highest scored network available.
5281 * the are keyed off the Requests requestId.
5282 */
Hugo Benichicd952782017-09-20 11:20:14 +09005283 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5284 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005285 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005286
Paul Jensen31a94f42015-02-13 14:18:39 -05005287 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5288 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005289 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005290 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5291 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5292 // there may not be a strict 1:1 correlation between the two.
5293 @GuardedBy("mNetworkForNetId")
5294 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005295
Robert Greenwalt7b816022014-04-18 15:25:25 -07005296 // NetworkAgentInfo keyed off its connecting messenger
5297 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005298 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005299 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005300
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005301 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005302 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005303
Paul Jensen2c311d62014-11-17 12:34:51 -05005304 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005305 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005306
Erik Klineda4bfa82015-04-30 12:58:40 +09005307 // Request used to optionally keep mobile data active even when higher
5308 // priority networks like Wi-Fi are active.
5309 private final NetworkRequest mDefaultMobileDataRequest;
5310
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005311 // Request used to optionally keep wifi data active even when higher
5312 // priority networks like ethernet are active.
5313 private final NetworkRequest mDefaultWifiRequest;
5314
Hugo Benichicd952782017-09-20 11:20:14 +09005315 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5316 synchronized (mNetworkForRequestId) {
5317 return mNetworkForRequestId.get(requestId);
5318 }
5319 }
5320
5321 private void clearNetworkForRequest(int requestId) {
5322 synchronized (mNetworkForRequestId) {
5323 mNetworkForRequestId.remove(requestId);
5324 }
5325 }
5326
5327 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5328 synchronized (mNetworkForRequestId) {
5329 mNetworkForRequestId.put(requestId, nai);
5330 }
5331 }
5332
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005333 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005334 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005335 }
5336
Varun Anand4fa80e82019-02-06 10:13:38 -08005337 @Nullable
5338 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5339 return nai != null ? nai.network : null;
5340 }
5341
5342 private void ensureRunningOnConnectivityServiceThread() {
5343 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5344 throw new IllegalStateException(
5345 "Not running on ConnectivityService thread: "
5346 + Thread.currentThread().getName());
5347 }
5348 }
5349
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005350 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005351 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005352 }
5353
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005354 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5355 return nri.request.requestId == mDefaultRequest.requestId;
5356 }
5357
Chalard Jean05ab6812018-05-02 21:14:54 +09005358 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5359 // changes that would conflict throughout the automerger graph. Having this method temporarily
5360 // helps with the process of going through with all these dependent changes across the entire
5361 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005362 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005363 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005364 int currentScore, NetworkMisc networkMisc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005365 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5366 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5367 }
5368
5369 /**
5370 * Register a new agent with ConnectivityService to handle a network.
5371 *
5372 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5373 * @param networkInfo the initial info associated with this network. It can be updated later :
5374 * see {@link #updateNetworkInfo}.
5375 * @param linkProperties the initial link properties of this network. They can be updated
5376 * later : see {@link #updateLinkProperties}.
5377 * @param networkCapabilities the initial capabilites of this network. They can be updated
5378 * later : see {@link #updateNetworkCapabilities}.
5379 * @param currentScore the initial score of the network. See
5380 * {@link NetworkAgentInfo#getCurrentScore}.
5381 * @param networkMisc metadata about the network. This is never updated.
5382 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5383 */
5384 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5385 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5386 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005387 enforceConnectivityInternalPermission();
5388
Rubin Xu1bb5c082017-09-05 18:40:49 +01005389 LinkProperties lp = new LinkProperties(linkProperties);
5390 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005391 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5392 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005393 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005394 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005395 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean05ab6812018-05-02 21:14:54 +09005396 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5397 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005398 // Make sure the network capabilities reflect what the agent info says.
5399 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005400 final String extraInfo = networkInfo.getExtraInfo();
5401 final String name = TextUtils.isEmpty(extraInfo)
5402 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005403 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005404 final long token = Binder.clearCallingIdentity();
5405 try {
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005406 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005407 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005408 } finally {
5409 Binder.restoreCallingIdentity(token);
5410 }
5411 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5412 // If the network disconnects or sends any other event before that, messages are deferred by
5413 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5414 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005415 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005416 }
5417
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005418 @VisibleForTesting
5419 protected NetworkStackClient getNetworkStack() {
5420 return NetworkStackClient.getInstance();
5421 }
5422
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005423 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5424 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005425 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005426 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005427 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005428 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005429 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005430 synchronized (this) {
5431 if (mSystemReady) {
5432 try {
5433 networkMonitor.notifySystemReady();
5434 } catch (RemoteException e) {
5435 e.rethrowFromSystemServer();
5436 }
5437 }
5438 }
5439
5440 try {
5441 networkMonitor.start();
5442 } catch (RemoteException e) {
5443 e.rethrowFromSystemServer();
5444 }
Erik Klinee5dac902018-03-04 21:01:01 +09005445 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5446 NetworkInfo networkInfo = nai.networkInfo;
5447 nai.networkInfo = null;
5448 updateNetworkInfo(nai, networkInfo);
5449 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005450 }
5451
lucaslin25a4ec32018-11-28 12:51:55 +08005452 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5453 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005454 int netId = networkAgent.network.netId;
5455
Lorenzo Colittidf595632019-01-08 14:43:37 +09005456 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5457 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5458 // are accurate.
5459 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005460
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005461 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005462 updateMtu(newLp, oldLp);
5463 // TODO - figure out what to do for clat
5464// for (LinkProperties lp : newLp.getStackedLinks()) {
5465// updateMtu(lp, null);
5466// }
lucaslin041a1af2018-11-28 19:27:52 +08005467 if (isDefaultNetwork(networkAgent)) {
5468 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5469 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005470
Erik Kline94887872016-04-05 13:30:49 +09005471 updateRoutes(newLp, oldLp, netId);
5472 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005473 // Make sure LinkProperties represents the latest private DNS status.
5474 // This does not need to be done before updateDnses because the
5475 // LinkProperties are not the source of the private DNS configuration.
5476 // updateDnses will fetch the private DNS configuration from DnsManager.
5477 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005478
Paul Jensene0bef712014-12-10 15:12:18 -05005479 if (isDefaultNetwork(networkAgent)) {
5480 handleApplyDefaultProxy(newLp.getHttpProxy());
5481 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005482 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005483 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005484 // TODO - move this check to cover the whole function
5485 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005486 synchronized (networkAgent) {
5487 networkAgent.linkProperties = newLp;
5488 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005489 // Start or stop DNS64 detection and 464xlat according to network state.
5490 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005491 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005492 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005493 try {
5494 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5495 } catch (RemoteException e) {
5496 e.rethrowFromSystemServer();
5497 }
lucaslin25a4ec32018-11-28 12:51:55 +08005498 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5499 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005500 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005501
5502 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005503 }
5504
Joel Scherpelz668370b2017-06-08 15:35:21 +09005505 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005506 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005507 // marks on unsupported interfaces is harmless.
5508 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5509 return;
5510 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005511
Joel Scherpelz668370b2017-06-08 15:35:21 +09005512 int mark = mContext.getResources().getInteger(
5513 com.android.internal.R.integer.config_networkWakeupPacketMark);
5514 int mask = mContext.getResources().getInteger(
5515 com.android.internal.R.integer.config_networkWakeupPacketMask);
5516
5517 // Mask/mark of zero will not detect anything interesting.
5518 // Don't install rules unless both values are nonzero.
5519 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005520 return;
5521 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005522
5523 final String prefix = "iface:" + iface;
5524 try {
5525 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005526 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005527 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005528 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005529 }
5530 } catch (Exception e) {
5531 loge("Exception modifying wakeup packet monitoring: " + e);
5532 }
5533
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005534 }
5535
5536 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5537 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005538 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005539 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5540 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005541 for (String iface : interfaceDiff.added) {
5542 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005543 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005544 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005545 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005546 } catch (Exception e) {
5547 loge("Exception adding interface: " + e);
5548 }
5549 }
5550 for (String iface : interfaceDiff.removed) {
5551 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005552 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005553 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005554 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005555 } catch (Exception e) {
5556 loge("Exception removing interface: " + e);
5557 }
5558 }
5559 }
5560
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005561 /**
5562 * Have netd update routes from oldLp to newLp.
5563 * @return true if routes changed between oldLp and newLp
5564 */
5565 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005566 // Compare the route diff to determine which routes should be added and removed.
5567 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5568 oldLp != null ? oldLp.getAllRoutes() : null,
5569 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005570
5571 // add routes before removing old in case it helps with continuous connectivity
5572
Chalard Jean4d660112018-06-04 16:52:49 +09005573 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005574 for (RouteInfo route : routeDiff.added) {
5575 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005576 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005577 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005578 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005579 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005580 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5581 loge("Exception in addRoute for non-gateway: " + e);
5582 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005583 }
5584 }
5585 for (RouteInfo route : routeDiff.added) {
5586 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005587 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005588 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005589 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005590 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005591 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5592 loge("Exception in addRoute for gateway: " + e);
5593 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005594 }
5595 }
5596
5597 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005598 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005599 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005600 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005601 } catch (Exception e) {
5602 loge("Exception in removeRoute: " + e);
5603 }
5604 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005605 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005606 }
Erik Kline41368502015-06-17 13:19:54 +09005607
Erik Kline94887872016-04-05 13:30:49 +09005608 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5609 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5610 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005611 }
Erik Kline94887872016-04-05 13:30:49 +09005612
Erik Kline1742fe12017-12-13 19:40:49 +09005613 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5614 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5615
Erik Klinea24d4592018-01-11 21:07:29 +09005616 if (DBG) {
5617 final Collection<InetAddress> dnses = newLp.getDnsServers();
5618 log("Setting DNS servers for network " + netId + " to " + dnses);
5619 }
Erik Kline94887872016-04-05 13:30:49 +09005620 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005621 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005622 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005623 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005624 }
Erik Kline4edba012017-04-07 15:29:29 +09005625 }
5626
Luke Huang8a462ec2018-08-24 20:33:16 +08005627 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005628 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005629 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005630 }
5631 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005632 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005633 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005634 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005635 }
5636
Paul Jensen3d194ea2015-06-16 14:27:36 -04005637 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005638 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5639 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5640 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005641 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005642 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005643 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005644 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5645 // causing a connect/teardown loop.
5646 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5647 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005648 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005649 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005650 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5651 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005652 // does not cause any request (that is not a listen) currently matching that agent to
5653 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005654 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005655 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005656 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005657 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005658 }
5659
Paul Jensen3d194ea2015-06-16 14:27:36 -04005660 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005661 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005662 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005663 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005664 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005665 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005666 }
Paul Jensene0988542015-06-25 15:30:08 -04005667 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005668 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005669 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005670 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005671 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005672 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005673 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005674 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005675 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005676 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005677 if (nai.isSuspended()) {
5678 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5679 } else {
5680 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5681 }
lucasline252a742019-03-12 13:08:03 +08005682 if (nai.partialConnectivity) {
5683 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5684 } else {
5685 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5686 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005687
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005688 return newNc;
5689 }
5690
5691 /**
5692 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5693 *
5694 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5695 * capabilities we manage and store in {@code nai}, such as validated status and captive
5696 * portal status)
5697 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5698 * potentially triggers rematches.
5699 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5700 * change.)
5701 *
5702 * @param oldScore score of the network before any of the changes that prompted us
5703 * to call this function.
5704 * @param nai the network having its capabilities updated.
5705 * @param nc the new network capabilities.
5706 */
5707 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5708 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5709
5710 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005711
Luke Huang8a462ec2018-08-24 20:33:16 +08005712 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5713 final int newPermission = getNetworkPermission(newNc);
5714 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005715 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005716 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005717 } catch (RemoteException e) {
5718 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005719 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005720 }
5721
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005722 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005723 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005724 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005725 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005726 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005727
Chalard Jeanf213ca12018-01-16 18:43:05 +09005728 updateUids(nai, prevNc, newNc);
5729
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005730 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005731 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5732 // the change we're processing can't affect any requests, it can only affect the listens
5733 // on this network. We might have been called by rematchNetworkAndRequests when a
5734 // network changed foreground state.
5735 processListenRequests(nai, true);
5736 } else {
5737 // If the requestable capabilities have changed or the score changed, we can't have been
5738 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005739 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005740 try {
5741 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5742 } catch (RemoteException e) {
5743 e.rethrowFromSystemServer();
5744 }
Paul Jensene0988542015-06-25 15:30:08 -04005745 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005746 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005747
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005748 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005749 final boolean oldMetered = prevNc.isMetered();
5750 final boolean newMetered = newNc.isMetered();
5751 final boolean meteredChanged = oldMetered != newMetered;
5752
5753 if (meteredChanged) {
5754 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5755 mRestrictBackground);
5756 }
5757
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005758 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005759 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005760
5761 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005762 if (meteredChanged || roamingChanged) {
5763 notifyIfacesChangedForNetworkStats();
5764 }
5765 }
5766
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005767 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005768 // Tell VPNs about updated capabilities, since they may need to
5769 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005770 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005771 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005772 }
5773
Chalard Jeanf213ca12018-01-16 18:43:05 +09005774 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5775 NetworkCapabilities newNc) {
5776 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5777 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5778 if (null == prevRanges) prevRanges = new ArraySet<>();
5779 if (null == newRanges) newRanges = new ArraySet<>();
5780 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5781
5782 prevRanges.removeAll(newRanges);
5783 newRanges.removeAll(prevRangesCopy);
5784
5785 try {
5786 if (!newRanges.isEmpty()) {
5787 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5788 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005789 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005790 }
5791 if (!prevRanges.isEmpty()) {
5792 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5793 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005794 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005795 }
5796 } catch (Exception e) {
5797 // Never crash!
5798 loge("Exception in updateUids: " + e);
5799 }
5800 }
5801
Hugo Benichief502882017-09-01 01:23:32 +00005802 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005803 ensureRunningOnConnectivityServiceThread();
5804
Erik Kline736353a2018-03-21 07:18:33 -07005805 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005806 // Ignore updates for disconnected networks
5807 return;
5808 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005809 // newLp is already a defensive copy.
5810 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005811 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005812 log("Update of LinkProperties for " + nai.name() +
5813 "; created=" + nai.created +
5814 "; everConnected=" + nai.everConnected);
5815 }
lucaslin25a4ec32018-11-28 12:51:55 +08005816 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005817 }
5818
Paul Jensenc8b9a742014-09-30 15:37:41 -04005819 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005820 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5821 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005822 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005823 if (nr.isListen()) continue;
Chalard Jean05ab6812018-05-02 21:14:54 +09005824 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005825 }
5826 }
5827
Chalard Jean05ab6812018-05-02 21:14:54 +09005828 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5829 int score = 0;
5830 int serial = 0;
5831 if (nai != null) {
5832 score = nai.getCurrentScore();
5833 serial = nai.factorySerialNumber;
5834 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005835 if (VDBG || DDBG){
5836 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5837 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005838 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005839 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5840 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005841 }
5842 }
5843
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005844 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5845 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005846 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005847 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005848 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5849 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005850 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005851 sendIntent(nri.mPendingIntent, intent);
5852 }
5853 // else not handled
5854 }
5855
5856 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5857 mPendingIntentWakeLock.acquire();
5858 try {
5859 if (DBG) log("Sending " + pendingIntent);
5860 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5861 } catch (PendingIntent.CanceledException e) {
5862 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5863 mPendingIntentWakeLock.release();
5864 releasePendingNetworkRequest(pendingIntent);
5865 }
5866 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5867 }
5868
5869 @Override
5870 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5871 String resultData, Bundle resultExtras) {
5872 if (DBG) log("Finished sending " + pendingIntent);
5873 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005874 // Release with a delay so the receiving client has an opportunity to put in its
5875 // own request.
5876 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005877 }
5878
Chalard Jeanf19db372018-01-26 19:24:40 +09005879 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005880 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005881 if (nri.messenger == null) {
5882 return; // Default request has no msgr
5883 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005884 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005885 // TODO: check if defensive copies of data is needed.
5886 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005887 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005888 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5889 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005890 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005891 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005892 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005893 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5894 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005895 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005896 // For this notification, arg1 contains the blocked status.
5897 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005898 break;
5899 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005900 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005901 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005902 break;
5903 }
5904 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005905 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005906 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005907 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005908 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005909 break;
5910 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005911 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005912 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005913 break;
5914 }
junyulai05986c62018-08-07 19:50:45 +08005915 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005916 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005917 msg.arg1 = arg1;
5918 break;
5919 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005920 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005921 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005922 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005923 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005924 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005925 String notification = ConnectivityManager.getCallbackName(notificationType);
5926 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005927 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005928 nri.messenger.send(msg);
5929 } catch (RemoteException e) {
5930 // may occur naturally in the race of binder death.
5931 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5932 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005933 }
5934
Hugo Benichidba33db2017-03-23 22:40:44 +09005935 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5936 bundle.putParcelable(t.getClass().getSimpleName(), t);
5937 }
5938
Paul Jensenc8b9a742014-09-30 15:37:41 -04005939 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005940 if (nai.numRequestNetworkRequests() != 0) {
5941 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5942 NetworkRequest nr = nai.requestAt(i);
5943 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005944 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005945 loge("Dead network still had at least " + nr);
5946 break;
5947 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005948 }
5949 nai.asyncChannel.disconnect();
5950 }
5951
Robert Greenwalt7b816022014-04-18 15:25:25 -07005952 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5953 if (oldNetwork == null) {
5954 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5955 return;
5956 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005957 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005958
5959 // If we get here it means that the last linger timeout for this network expired. So there
5960 // must be no other active linger timers, and we must stop lingering.
5961 oldNetwork.clearLingerState();
5962
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005963 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005964 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005965 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005966 } else {
5967 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005968 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5969 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005970 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005971 }
5972
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005973 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005974 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005975
Paul Jensen27b02b72014-07-14 12:03:33 -04005976 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005977 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005978 } catch (Exception e) {
5979 loge("Exception setting default network :" + e);
5980 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005981
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005982 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005983 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005984 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005985 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005986 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005987 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5988 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005989 }
5990
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005991 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005992 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5993 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5994 NetworkRequest nr = nri.request;
5995 if (!nr.isListen()) continue;
5996 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5997 nai.removeRequest(nri.request.requestId);
5998 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5999 }
6000 }
6001
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006002 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006003 try {
6004 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
6005 } catch (RemoteException e) {
6006 e.rethrowFromSystemServer();
6007 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006008 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
6009 }
6010
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006011 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
6012 NetworkRequest nr = nri.request;
6013 if (!nr.isListen()) continue;
6014 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
6015 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006016 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006017 }
6018 }
6019 }
6020
Paul Jensen2161a8e2014-09-11 11:00:39 -04006021 // Handles a network appearing or improving its score.
6022 //
6023 // - Evaluates all current NetworkRequests that can be
6024 // satisfied by newNetwork, and reassigns to newNetwork
6025 // any such requests for which newNetwork is the best.
6026 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006027 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006028 // needed. A network is needed if it is the best network for
6029 // one or more NetworkRequests, or if it is a VPN.
6030 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006031 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006032 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006033 //
6034 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6035 // networks that have no chance (i.e. even if validated)
6036 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006037 //
6038 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6039 // it does not remove NetworkRequests that other Networks could better satisfy.
6040 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6041 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6042 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006043 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006044 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006045 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6046 // performed to tear down unvalidated networks that have no chance (i.e. even if
6047 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006048 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006049 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006050 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006051 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006052 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006053 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006054
6055 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6056 final int score = newNetwork.getCurrentScore();
6057
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006058 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006059
Paul Jensen2161a8e2014-09-11 11:00:39 -04006060 // Find and migrate to this Network any NetworkRequests for
6061 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006062 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6063 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006064 NetworkCapabilities nc = newNetwork.networkCapabilities;
6065 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006066 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006067 // Process requests in the first pass and listens in the second pass. This allows us to
6068 // change a network's capabilities depending on which requests it has. This is only
6069 // correct if the change in capabilities doesn't affect whether the network satisfies
6070 // requests or not, and doesn't affect the network's score.
6071 if (nri.request.isListen()) continue;
6072
Hugo Benichicd952782017-09-20 11:20:14 +09006073 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006074 final boolean satisfies = newNetwork.satisfies(nri.request);
6075 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006076 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006077 log("Network " + newNetwork.name() + " was already satisfying" +
6078 " request " + nri.request.requestId + ". No change.");
6079 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006080 keep = true;
6081 continue;
6082 }
6083
6084 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006085 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006086 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006087 // next check if it's better than any current network we're using for
6088 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006089 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006090 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006091 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006092 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006093 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006094 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006095 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006096 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006097 if (VDBG || DDBG){
6098 log(" accepting network in place of " + currentNetwork.name());
6099 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006100 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006101 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006102 affectedNetworks.add(currentNetwork);
6103 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006104 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006105 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006106 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006107 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006108 if (!newNetwork.addRequest(nri.request)) {
6109 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6110 }
6111 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006112 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006113 // Tell NetworkFactories about the new score, so they can stop
6114 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006115 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006116 // network. Think about if there is a way to reduce this. Push
6117 // netid->request mapping to each factory?
Chalard Jean05ab6812018-05-02 21:14:54 +09006118 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006119 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006120 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006121 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006122 if (currentNetwork != null) {
6123 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006125 }
6126 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006127 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006128 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6129 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006130 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006131 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6132 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6133 // This means this code doesn't have to handle the case where "currentNetwork" no
6134 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6135 if (DBG) {
6136 log("Network " + newNetwork.name() + " stopped satisfying" +
6137 " request " + nri.request.requestId);
6138 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006139 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006140 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006141 clearNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09006142 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006143 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006144 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6145 newNetwork.name() +
6146 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006147 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006148 // TODO: Technically, sending CALLBACK_LOST here is
6149 // incorrect if there is a replacement network currently
6150 // connected that can satisfy nri, which is a request
6151 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006152 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6153 // so this code is only incorrect for a network that loses
6154 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006155 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006156 }
6157 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006158 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006159 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006160 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006161 makeDefault(newNetwork);
6162 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006163 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006164 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006165 // Have a new default network, release the transition wakelock in
6166 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006167 }
6168
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006169 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6170 Slog.wtf(TAG, String.format(
6171 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006172 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006173 }
6174 if (newNetwork.getCurrentScore() != score) {
6175 Slog.wtf(TAG, String.format(
6176 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006177 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006178 }
6179
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006180 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006181 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6182 // If the network went from background to foreground or vice versa, we need to update
6183 // its foreground state. It is safe to do this after rematching the requests because
6184 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6185 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006186 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006187 } else {
6188 processListenRequests(newNetwork, false);
6189 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006190
Paul Jensencf4c2c62015-07-01 14:16:32 -04006191 // do this after the default net is switched, but
6192 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006193 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006194
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006195 // Linger any networks that are no longer needed. This should be done after sending the
6196 // available callback for newNetwork.
6197 for (NetworkAgentInfo nai : affectedNetworks) {
6198 updateLingerState(nai, now);
6199 }
6200 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6201 // does not need to be done in any particular order.
6202 updateLingerState(newNetwork, now);
6203
Paul Jensencf4c2c62015-07-01 14:16:32 -04006204 if (isNewDefault) {
6205 // Maintain the illusion: since the legacy API only
6206 // understands one network at a time, we must pretend
6207 // that the current default network disconnected before
6208 // the new one connected.
6209 if (oldDefaultNetwork != null) {
6210 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6211 oldDefaultNetwork, true);
6212 }
6213 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6214 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6215 notifyLockdownVpn(newNetwork);
6216 }
6217
Robert Greenwalt7b816022014-04-18 15:25:25 -07006218 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006219 // Notify battery stats service about this network, both the normal
6220 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006221 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006222 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006223 final IBatteryStats bs = BatteryStatsService.getService();
6224 final int type = newNetwork.networkInfo.getType();
6225
6226 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6227 bs.noteNetworkInterfaceType(baseIface, type);
6228 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6229 final String stackedIface = stacked.getInterfaceName();
6230 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006231 }
6232 } catch (RemoteException ignored) {
6233 }
6234
Robert Greenwalt152ed372014-12-17 17:19:53 -08006235 // This has to happen after the notifyNetworkCallbacks as that tickles each
6236 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006237 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006238 // and will generally do a dns request so they can ensureRouteToHost and if
6239 // they do that before the callbacks happen they'll use the default network.
6240 //
6241 // TODO: Is there still a race here? We send the broadcast
6242 // after sending the callback, but if the app can receive the
6243 // broadcast before the callback, it might still break.
6244 //
6245 // This *does* introduce a race where if the user uses the new api
6246 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6247 // they may get old info. Reverse this after the old startUsing api is removed.
6248 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006249 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6250 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006251 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006252 // legacy type tracker filters out repeat adds
6253 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6254 }
6255 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006256
6257 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6258 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6259 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6260 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6261 if (newNetwork.isVPN()) {
6262 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6263 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006264 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006265 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6266 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006267 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006268 if (nai.getLingerExpiry() > 0) {
6269 // This network has active linger timers and no requests, but is not
6270 // lingering. Linger it.
6271 //
6272 // One way (the only way?) this can happen if this network is unvalidated
6273 // and became unneeded due to another network improving its score to the
6274 // point where this network will no longer be able to satisfy any requests
6275 // even if it validates.
6276 updateLingerState(nai, now);
6277 } else {
6278 if (DBG) log("Reaping " + nai.name());
6279 teardownUnneededNetwork(nai);
6280 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006281 }
6282 }
6283 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006284 }
6285
Paul Jensen1c7ba022015-06-16 14:27:36 -04006286 /**
6287 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6288 * being disconnected.
6289 * @param changed If only one Network's score or capabilities have been modified since the last
6290 * time this function was called, pass this Network in this argument, otherwise pass
6291 * null.
6292 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6293 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6294 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6295 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6296 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006297 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006298 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006299 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6300 // to avoid the slowness. It is not simply enough to process just "changed", for
6301 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006302 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006303
6304 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6305 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6306 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006307 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006308 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006309 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006310 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006311 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6312 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6313 // Rematch higher scoring networks first to prevent requests first matching a lower
6314 // scoring network and then a higher scoring network, which could produce multiple
6315 // callbacks and inadvertently unlinger networks.
6316 Arrays.sort(nais);
6317 for (NetworkAgentInfo nai : nais) {
6318 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006319 // Only reap the last time through the loop. Reaping before all rematching
6320 // is complete could incorrectly teardown a network that hasn't yet been
6321 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006322 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006323 : ReapUnvalidatedNetworks.REAP,
6324 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006325 }
6326 }
6327 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006328
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006329 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006330 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006331 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006332 // For now only update icons for default connection.
6333 // TODO: Update WiFi and cellular icons separately. b/17237507
6334 if (!isDefaultNetwork(nai)) return;
6335
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006336 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006337 // Don't repeat publish.
6338 if (newInetCondition == mDefaultInetConditionPublished) return;
6339
6340 mDefaultInetConditionPublished = newInetCondition;
6341 sendInetConditionBroadcast(nai.networkInfo);
6342 }
6343
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006344 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006345 synchronized (mVpns) {
6346 if (mLockdownTracker != null) {
6347 if (nai != null && nai.isVPN()) {
6348 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6349 } else {
6350 mLockdownTracker.onNetworkInfoChanged();
6351 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006352 }
6353 }
6354 }
6355
Robert Greenwalt7b816022014-04-18 15:25:25 -07006356 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006357 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006358 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006359 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006360 synchronized (networkAgent) {
6361 oldInfo = networkAgent.networkInfo;
6362 networkAgent.networkInfo = newInfo;
6363 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006364 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006365
Robert Greenwalt7b816022014-04-18 15:25:25 -07006366 if (DBG) {
6367 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6368 (oldInfo == null ? "null" : oldInfo.getState()) +
6369 " to " + state);
6370 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006371
Robin Lee585e2482016-05-01 23:00:00 +01006372 if (!networkAgent.created
6373 && (state == NetworkInfo.State.CONNECTED
6374 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006375
6376 // A network that has just connected has zero requests and is thus a foreground network.
6377 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6378
Robert Greenwalt7b816022014-04-18 15:25:25 -07006379 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006380 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006381 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006382 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006383 (networkAgent.networkMisc == null ||
6384 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006385 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006386 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006387 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006388 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006389 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006390 loge("Error creating network " + networkAgent.network.netId + ": "
6391 + e.getMessage());
6392 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006393 }
Paul Jenseneec75412014-08-04 12:21:19 -04006394 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006395 }
6396
6397 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6398 networkAgent.everConnected = true;
6399
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006400 if (networkAgent.linkProperties == null) {
6401 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6402 }
6403
Erik Kline736353a2018-03-21 07:18:33 -07006404 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006405 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6406 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006407
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006408 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6409 // command must be sent after updating LinkProperties to maximize chances of
6410 // NetworkMonitor seeing the correct LinkProperties when starting.
6411 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6412 try {
lucaslin43338992019-03-20 18:21:59 +08006413 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6414 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6415 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006416 networkAgent.networkMonitor().notifyNetworkConnected();
6417 } catch (RemoteException e) {
6418 e.rethrowFromSystemServer();
6419 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006420 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006421
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006422 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6423 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6424 // capabilities, so it only needs to be done once on initial connect, not every time the
6425 // network's capabilities change. Note that we do this before rematching the network,
6426 // so we could decide to tear it down immediately afterwards. That's fine though - on
6427 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6428 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006429 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006430
Varun Anand4fa80e82019-02-06 10:13:38 -08006431 if (networkAgent.isVPN()) {
6432 updateAllVpnsCapabilities();
6433 }
6434
Paul Jensen2161a8e2014-09-11 11:00:39 -04006435 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006436 final long now = SystemClock.elapsedRealtime();
6437 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006438
6439 // This has to happen after matching the requests, because callbacks are just requests.
6440 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006441 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006442 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006443 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006444 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006445 }
Chalard Jean392971c2018-05-11 20:19:20 +09006446 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006447 if (networkAgent.isVPN()) {
6448 // As the active or bound network changes for apps, broadcast the default proxy, as
6449 // apps may need to update their proxy data. This is called after disconnecting from
6450 // VPN to make sure we do not broadcast the old proxy data.
6451 // TODO(b/122649188): send the broadcast only to VPN users.
6452 mProxyTracker.sendProxyBroadcast();
6453 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006454 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6455 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006456 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006457 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006458 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006459 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006460 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6461 networkAgent.networkCapabilities);
6462 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6463 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006464 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6465 ConnectivityManager.CALLBACK_SUSPENDED :
6466 ConnectivityManager.CALLBACK_RESUMED));
6467 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006468 }
6469 }
6470
Robert Greenwaltac96c522014-06-03 16:43:57 -07006471 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006472 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006473 if (score < 0) {
6474 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6475 "). Bumping score to min of 0");
6476 score = 0;
6477 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006478
Paul Jensen2161a8e2014-09-11 11:00:39 -04006479 final int oldScore = nai.getCurrentScore();
6480 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006481
Paul Jensen85cf78e2015-06-25 13:25:07 -04006482 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006483
Paul Jensenc8b9a742014-09-30 15:37:41 -04006484 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006485 }
6486
Erik Klinec75d4fa2017-02-15 19:59:17 +09006487 // Notify only this one new request of the current state. Transfer all the
6488 // current state by calling NetworkCapabilities and LinkProperties callbacks
6489 // so that callers can be guaranteed to have as close to atomicity in state
6490 // transfer as can be supported by this current API.
6491 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006492 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006493 if (nri.mPendingIntent != null) {
6494 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6495 // Attempt no subsequent state pushes where intents are involved.
6496 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006497 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006498
junyulai05986c62018-08-07 19:50:45 +08006499 final boolean metered = nai.networkCapabilities.isMetered();
6500 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6501 metered, mRestrictBackground);
6502 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6503 }
6504
6505 /**
6506 * Notify of the blocked state apps with a registered callback matching a given NAI.
6507 *
6508 * Unlike other callbacks, blocked status is different between each individual uid. So for
6509 * any given nai, all requests need to be considered according to the uid who filed it.
6510 *
6511 * @param nai The target NetworkAgentInfo.
6512 * @param oldMetered True if the previous network capabilities is metered.
6513 * @param newRestrictBackground True if data saver is enabled.
6514 */
6515 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6516 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6517
6518 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6519 NetworkRequest nr = nai.requestAt(i);
6520 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6521 final int uidRules = mUidRules.get(nri.mUid);
6522 final boolean oldBlocked, newBlocked;
6523 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6524 // between these two calls.
6525 synchronized (mVpns) {
6526 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6527 oldRestrictBackground);
6528 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6529 newRestrictBackground);
6530 }
6531 if (oldBlocked != newBlocked) {
6532 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6533 encodeBool(newBlocked));
6534 }
6535 }
6536 }
6537
6538 /**
6539 * Notify apps with a given UID of the new blocked state according to new uid rules.
6540 * @param uid The uid for which the rules changed.
6541 * @param newRules The new rules to apply.
6542 */
6543 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6544 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6545 final boolean metered = nai.networkCapabilities.isMetered();
6546 final boolean oldBlocked, newBlocked;
6547 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6548 // rules changed event. And this function actually loop through all connected nai and
6549 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6550 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6551 synchronized (mVpns) {
6552 oldBlocked = isUidNetworkingWithVpnBlocked(
6553 uid, mUidRules.get(uid), metered, mRestrictBackground);
6554 newBlocked = isUidNetworkingWithVpnBlocked(
6555 uid, newRules, metered, mRestrictBackground);
6556 }
6557 if (oldBlocked == newBlocked) {
6558 return;
6559 }
6560 final int arg = encodeBool(newBlocked);
6561 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6562 NetworkRequest nr = nai.requestAt(i);
6563 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6564 if (nri != null && nri.mUid == uid) {
6565 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6566 }
6567 }
6568 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006569 }
6570
Robert Greenwalt8d482522015-06-24 13:23:42 -07006571 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006572 // The NetworkInfo we actually send out has no bearing on the real
6573 // state of affairs. For example, if the default connection is mobile,
6574 // and a request for HIPRI has just gone away, we need to pretend that
6575 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6576 // the state to DISCONNECTED, even though the network is of type MOBILE
6577 // and is still connected.
6578 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6579 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006580 if (state != DetailedState.DISCONNECTED) {
6581 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006582 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006583 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006584 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006585 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6586 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6587 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6588 if (info.isFailover()) {
6589 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6590 nai.networkInfo.setFailover(false);
6591 }
6592 if (info.getReason() != null) {
6593 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6594 }
6595 if (info.getExtraInfo() != null) {
6596 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6597 }
6598 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006599 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006600 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006601 if (newDefaultAgent != null) {
6602 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6603 newDefaultAgent.networkInfo);
6604 } else {
6605 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6606 }
6607 }
6608 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6609 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006610 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006611 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006612 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006613 }
6614 }
6615 }
6616
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006617 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006618 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006619 String notification = ConnectivityManager.getCallbackName(notifyType);
6620 log("notifyType " + notification + " for " + networkAgent.name());
6621 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006622 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6623 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006624 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6625 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006626 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6627 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006628 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006629 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006630 } else {
6631 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6632 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006633 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006634 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006635
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006636 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6637 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6638 }
6639
Jeff Sharkey69736342014-12-08 14:50:12 -08006640 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006641 * Returns the list of all interfaces that could be used by network traffic that does not
6642 * explicitly specify a network. This includes the default network, but also all VPNs that are
6643 * currently connected.
6644 *
6645 * Must be called on the handler thread.
6646 */
6647 private Network[] getDefaultNetworks() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006648 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006649 ArrayList<Network> defaultNetworks = new ArrayList<>();
6650 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6651 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6652 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6653 defaultNetworks.add(nai.network);
6654 }
6655 }
6656 return defaultNetworks.toArray(new Network[0]);
6657 }
6658
6659 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006660 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6661 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006662 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006663 private void notifyIfacesChangedForNetworkStats() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006664 ensureRunningOnConnectivityServiceThread();
6665 String activeIface = null;
6666 LinkProperties activeLinkProperties = getActiveLinkProperties();
6667 if (activeLinkProperties != null) {
6668 activeIface = activeLinkProperties.getInterfaceName();
6669 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006670 try {
Varun Anandd33cbc62019-02-07 14:13:13 -08006671 mStatsService.forceUpdateIfaces(
6672 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006673 } catch (Exception ignored) {
6674 }
6675 }
6676
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006677 @Override
6678 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006679 int user = UserHandle.getUserId(Binder.getCallingUid());
6680 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006681 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006682 return mVpns.get(user).addAddress(address, prefixLength);
6683 }
6684 }
6685
6686 @Override
6687 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006688 int user = UserHandle.getUserId(Binder.getCallingUid());
6689 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006690 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006691 return mVpns.get(user).removeAddress(address, prefixLength);
6692 }
6693 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006694
6695 @Override
6696 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006697 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006698 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006699 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006700 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006701 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006702 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006703 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006704 mHandler.post(() -> {
6705 // Update VPN's capabilities based on updated underlying network set.
6706 updateAllVpnsCapabilities();
6707 notifyIfacesChangedForNetworkStats();
6708 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006709 }
6710 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006711 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006712
6713 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006714 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006715 enforceConnectivityInternalPermission();
Remi NGUYEN VAN0bd294c2019-03-20 14:22:49 +09006716 final String defaultUrl = mContext.getResources().getString(
6717 R.string.config_networkDefaultCaptivePortalServerUrl);
6718 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext, defaultUrl);
Udam Sainib7c24872016-01-04 12:16:14 -08006719 }
6720
6721 @Override
junyulai7c469172019-01-16 20:23:34 +08006722 public void startNattKeepalive(Network network, int intervalSeconds,
6723 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006724 enforceKeepalivePermission();
6725 mKeepaliveTracker.startNattKeepalive(
junyulai0c666972019-03-04 22:45:36 +08006726 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai7c469172019-01-16 20:23:34 +08006727 intervalSeconds, cb,
junyulai06835112019-01-03 18:50:15 +08006728 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006729 }
6730
6731 @Override
junyulai215b8772019-01-15 11:32:44 +08006732 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006733 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006734 String dstAddr) {
junyulai215b8772019-01-15 11:32:44 +08006735 mKeepaliveTracker.startNattKeepalive(
6736 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006737 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006738 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6739 }
6740
6741 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006742 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006743 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006744 enforceKeepalivePermission();
6745 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006746 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006747 }
6748
6749 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006750 public void stopKeepalive(Network network, int slot) {
6751 mHandler.sendMessage(mHandler.obtainMessage(
junyulai06835112019-01-03 18:50:15 +08006752 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006753 }
6754
6755 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006756 public void factoryReset() {
6757 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006758
6759 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6760 return;
6761 }
6762
Robin Lee3b3dd942015-05-12 18:14:58 +01006763 final int userId = UserHandle.getCallingUserId();
6764
Stuart Scottf1fb3972015-04-02 18:00:02 -07006765 // Turn airplane mode off
6766 setAirplaneMode(false);
6767
Stuart Scotte3e314d2015-04-20 14:07:45 -07006768 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6769 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006770 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006771 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006772 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006773 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006774 }
6775
Stuart Scotte3e314d2015-04-20 14:07:45 -07006776 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006777 // Remove always-on package
6778 synchronized (mVpns) {
6779 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6780 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006781 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006782 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6783 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006784
Hugo Benichi69744342017-11-27 10:57:16 +09006785 // Turn Always-on VPN off
6786 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6787 final long ident = Binder.clearCallingIdentity();
6788 try {
6789 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6790 mLockdownEnabled = false;
6791 setLockdownTracker(null);
6792 } finally {
6793 Binder.restoreCallingIdentity(ident);
6794 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006795 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006796
Hugo Benichi69744342017-11-27 10:57:16 +09006797 // Turn VPN off
6798 VpnConfig vpnConfig = getVpnConfig(userId);
6799 if (vpnConfig != null) {
6800 if (vpnConfig.legacy) {
6801 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6802 } else {
6803 // Prevent this app (packagename = vpnConfig.user) from initiating
6804 // VPN connections in the future without user intervention.
6805 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006806
Hugo Benichi69744342017-11-27 10:57:16 +09006807 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6808 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006809 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006810 }
6811 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006812
6813 Settings.Global.putString(mContext.getContentResolver(),
6814 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006815 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006816
Ricky Wai44dcbde2018-01-23 04:09:45 +00006817 @Override
6818 public byte[] getNetworkWatchlistConfigHash() {
6819 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6820 if (nwm == null) {
6821 loge("Unable to get NetworkWatchlistManager");
6822 return null;
6823 }
6824 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6825 return nwm.getWatchlistConfigHash();
6826 }
6827
Paul Jensencf4c2c62015-07-01 14:16:32 -04006828 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006829 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6830 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006831 }
6832
6833 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006834 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6835 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6836 }
6837
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006838 @VisibleForTesting
6839 public boolean hasService(String name) {
6840 return ServiceManager.checkService(name) != null;
6841 }
6842
Hugo Benichi64901e52017-10-19 14:42:40 +09006843 @VisibleForTesting
6844 protected IpConnectivityMetrics.Logger metricsLogger() {
6845 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6846 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006847 }
6848
6849 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006850 int[] transports = nai.networkCapabilities.getTransportTypes();
6851 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006852 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006853
6854 private static boolean toBool(int encodedBoolean) {
6855 return encodedBoolean != 0; // Only 0 means false.
6856 }
6857
6858 private static int encodeBool(boolean b) {
6859 return b ? 1 : 0;
6860 }
mswest46386886f2018-03-12 10:34:34 -07006861
6862 @Override
6863 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6864 FileDescriptor err, String[] args, ShellCallback callback,
6865 ResultReceiver resultReceiver) {
6866 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6867 }
6868
6869 private class ShellCmd extends ShellCommand {
6870
6871 @Override
6872 public int onCommand(String cmd) {
6873 if (cmd == null) {
6874 return handleDefaultCommands(cmd);
6875 }
6876 final PrintWriter pw = getOutPrintWriter();
6877 try {
6878 switch (cmd) {
6879 case "airplane-mode":
6880 final String action = getNextArg();
6881 if ("enable".equals(action)) {
6882 setAirplaneMode(true);
6883 return 0;
6884 } else if ("disable".equals(action)) {
6885 setAirplaneMode(false);
6886 return 0;
6887 } else if (action == null) {
6888 final ContentResolver cr = mContext.getContentResolver();
6889 final int enabled = Settings.Global.getInt(cr,
6890 Settings.Global.AIRPLANE_MODE_ON);
6891 pw.println(enabled == 0 ? "disabled" : "enabled");
6892 return 0;
6893 } else {
6894 onHelp();
6895 return -1;
6896 }
6897 default:
6898 return handleDefaultCommands(cmd);
6899 }
6900 } catch (Exception e) {
6901 pw.println(e);
6902 }
6903 return -1;
6904 }
6905
6906 @Override
6907 public void onHelp() {
6908 PrintWriter pw = getOutPrintWriter();
6909 pw.println("Connectivity service commands:");
6910 pw.println(" help");
6911 pw.println(" Print this help text.");
6912 pw.println(" airplane-mode [enable|disable]");
6913 pw.println(" Turn airplane mode on or off.");
6914 pw.println(" airplane-mode");
6915 pw.println(" Get airplane mode.");
6916 }
6917 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006918
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006919 @GuardedBy("mVpns")
6920 private Vpn getVpnIfOwner() {
6921 final int uid = Binder.getCallingUid();
6922 final int user = UserHandle.getUserId(uid);
6923
6924 final Vpn vpn = mVpns.get(user);
6925 if (vpn == null) {
6926 return null;
6927 } else {
6928 final VpnInfo info = vpn.getVpnInfo();
6929 return (info == null || info.ownerUid != uid) ? null : vpn;
6930 }
6931 }
6932
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006933 /**
6934 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6935 * for testing.
6936 */
6937 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6938 if (checkNetworkStackPermission()) {
6939 return null;
6940 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006941 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006942 Vpn vpn = getVpnIfOwner();
6943 if (vpn != null) {
6944 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006945 }
6946 }
6947 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6948 + "permission");
6949 }
6950
6951 /**
6952 * @param connectionInfo the connection to resolve.
6953 * @return {@code uid} if the connection is found and the app has permission to observe it
6954 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6955 * connection is not found.
6956 */
6957 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6958 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6959 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6960 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6961 }
6962
6963 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6964 connectionInfo.local, connectionInfo.remote);
6965
6966 /* Filter out Uids not associated with the VPN. */
6967 if (vpn != null && !vpn.appliesToUid(uid)) {
6968 return INVALID_UID;
6969 }
6970
6971 return uid;
6972 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006973
6974 @Override
6975 public boolean isCallerCurrentAlwaysOnVpnApp() {
6976 synchronized (mVpns) {
6977 Vpn vpn = getVpnIfOwner();
6978 return vpn != null && vpn.getAlwaysOn();
6979 }
6980 }
6981
6982 @Override
6983 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6984 synchronized (mVpns) {
6985 Vpn vpn = getVpnIfOwner();
6986 return vpn != null && vpn.getLockdown();
6987 }
6988 }
Benedict Wonga341fbc2018-11-09 14:45:34 -08006989
6990 /**
6991 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
6992 *
6993 * <p>The TestNetworkService must be run in the system server due to TUN creation.
6994 */
6995 @Override
6996 public IBinder startOrGetTestNetworkService() {
6997 synchronized (mTNSLock) {
6998 TestNetworkService.enforceTestNetworkPermissions(mContext);
6999
7000 if (mTNS == null) {
7001 mTNS = new TestNetworkService(mContext, mNMS);
7002 }
7003
7004 return mTNS;
7005 }
7006 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07007007}