blob: a2c5655bf122ec0b226bf2775bc59dca1e9b55bd [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
1885 private void enforceAnyPermissionOf(String... permissions) {
1886 if (!checkAnyPermissionOf(permissions)) {
1887 throw new SecurityException("Requires one of the following permissions: "
1888 + String.join(", ", permissions) + ".");
1889 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001890 }
1891
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001892 private void enforceInternetPermission() {
1893 mContext.enforceCallingOrSelfPermission(
1894 android.Manifest.permission.INTERNET,
1895 "ConnectivityService");
1896 }
1897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001899 mContext.enforceCallingOrSelfPermission(
1900 android.Manifest.permission.ACCESS_NETWORK_STATE,
1901 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
1904 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001905 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907
Charles He36738632017-05-15 17:07:18 +01001908 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001909 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001910 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001911 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001912 }
1913
Chalard Jeanb552c462018-02-21 18:43:54 +09001914 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001915 return checkAnyPermissionOf(
1916 android.Manifest.permission.NETWORK_SETTINGS,
1917 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001918 }
1919
1920 private boolean checkSettingsPermission(int pid, int uid) {
1921 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001922 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1923 || PERMISSION_GRANTED == mContext.checkPermission(
1924 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001925 }
1926
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001927 private void enforceTetherAccessPermission() {
1928 mContext.enforceCallingOrSelfPermission(
1929 android.Manifest.permission.ACCESS_NETWORK_STATE,
1930 "ConnectivityService");
1931 }
1932
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001933 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001934 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001935 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001936 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001937 }
1938
Pavel Grafova462bcb2019-01-25 08:50:06 +00001939 private void enforceControlAlwaysOnVpnPermission() {
1940 mContext.enforceCallingOrSelfPermission(
1941 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1942 "ConnectivityService");
1943 }
1944
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001945 private void enforceNetworkStackSettingsOrSetup() {
1946 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001947 android.Manifest.permission.NETWORK_SETTINGS,
1948 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001949 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001950 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001951 }
1952
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001953 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001954 return checkAnyPermissionOf(
1955 android.Manifest.permission.NETWORK_STACK,
1956 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001957 }
1958
Hugo Benichi514da602016-07-19 15:59:27 +09001959 private void enforceConnectivityRestrictedNetworksPermission() {
1960 try {
1961 mContext.enforceCallingOrSelfPermission(
1962 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1963 "ConnectivityService");
1964 return;
1965 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1966 enforceConnectivityInternalPermission();
1967 }
1968
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001969 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001970 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001971 }
1972
Lorenzo Colitti18660282016-07-04 12:55:44 +09001973 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001974 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001975 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001976 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001977 }
1978
1979 private void sendInetConditionBroadcast(NetworkInfo info) {
1980 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1981 }
1982
Wink Saville628b0852011-08-04 15:01:58 -07001983 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001984 synchronized (mVpns) {
1985 if (mLockdownTracker != null) {
1986 info = new NetworkInfo(info);
1987 mLockdownTracker.augmentNetworkInfo(info);
1988 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001989 }
1990
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001991 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001992 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001993 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 if (info.isFailover()) {
1995 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1996 info.setFailover(false);
1997 }
1998 if (info.getReason() != null) {
1999 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2000 }
2001 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002002 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2003 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002005 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002006 return intent;
2007 }
2008
2009 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2010 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2011 }
2012
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002013 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002014 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2015 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2016 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002017 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002018 final long ident = Binder.clearCallingIdentity();
2019 try {
2020 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2021 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002025 }
2026
Mike Lockwood0f79b542009-08-14 14:18:49 -04002027 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002028 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002029 if (!mSystemReady
2030 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002031 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002032 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002033 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002034 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002035 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002036 }
2037
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002038 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002039 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002040 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002041 final NetworkInfo ni = intent.getParcelableExtra(
2042 ConnectivityManager.EXTRA_NETWORK_INFO);
2043 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2044 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2045 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002046 } else {
2047 BroadcastOptions opts = BroadcastOptions.makeBasic();
2048 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2049 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002050 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002051 final IBatteryStats bs = BatteryStatsService.getService();
2052 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002053 bs.noteConnectivityChanged(intent.getIntExtra(
2054 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002055 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002056 } catch (RemoteException e) {
2057 }
Chad Brubakerac925012018-03-08 10:37:09 -08002058 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002059 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002060 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002061 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002062 } finally {
2063 Binder.restoreCallingIdentity(ident);
2064 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002065 }
2066 }
2067
2068 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002069 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002070 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002071 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002072
Hugo Benichi20035e02017-04-26 14:53:28 +09002073 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002074 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002075 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002076 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002077 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002078 }
2079 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002080
Robin Lee244ce8e2016-01-05 18:03:46 +00002081 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2082 // for user to unlock device too.
2083 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002084
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002085 // Create network requests for always-on networks.
2086 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002087
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002088 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002089
2090 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002094 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002095 *
2096 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002097 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002098 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2100 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002101
2102 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002104
Robert Greenwalt7b816022014-04-18 15:25:25 -07002105 if (networkAgent.networkCapabilities.hasTransport(
2106 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002107 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2108 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002109 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002110 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 } else if (networkAgent.networkCapabilities.hasTransport(
2112 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002113 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2114 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002115 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002117 } else {
2118 // do not track any other networks
2119 timeout = 0;
2120 }
2121
Robert Greenwalt7b816022014-04-18 15:25:25 -07002122 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002123 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002124 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002125 } catch (Exception e) {
2126 // You shall not crash!
2127 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002128 }
2129 }
2130 }
2131
2132 /**
2133 * Remove data activity tracking when network disconnects.
2134 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2136 final String iface = networkAgent.linkProperties.getInterfaceName();
2137 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002138
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2140 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002141 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002142 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002143 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002144 } catch (Exception e) {
2145 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002146 }
2147 }
2148 }
2149
2150 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002151 * Update data activity tracking when network state is updated.
2152 */
2153 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2154 NetworkAgentInfo oldNetwork) {
2155 if (newNetwork != null) {
2156 setupDataActivityTracking(newNetwork);
2157 }
2158 if (oldNetwork != null) {
2159 removeDataActivityTracking(oldNetwork);
2160 }
2161 }
2162 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002163 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002164 * and set it on it's iface.
2165 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2167 final String iface = newLp.getInterfaceName();
2168 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002169 if (oldLp == null && mtu == 0) {
2170 // Silently ignore unset MTU value.
2171 return;
2172 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2174 if (VDBG) log("identical MTU - not setting");
2175 return;
2176 }
paulhud9736de2019-03-08 16:35:20 +08002177 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002178 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 return;
2180 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002181
w1997615afd812014-08-05 15:18:11 -07002182 // Cannot set MTU without interface name
2183 if (TextUtils.isEmpty(iface)) {
2184 loge("Setting MTU size with null iface.");
2185 return;
2186 }
2187
Robert Greenwalt7b816022014-04-18 15:25:25 -07002188 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002189 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002190 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002191 } catch (Exception e) {
2192 Slog.e(TAG, "exception in setMtu()" + e);
2193 }
2194 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002195
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002196 @VisibleForTesting
2197 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002198 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2199
2200 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002201 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002202 protected MockableSystemProperties getSystemProperties() {
2203 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002204 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002205
lucaslin041a1af2018-11-28 19:27:52 +08002206 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002207 String[] values = null;
2208 if (tcpBufferSizes != null) {
2209 values = tcpBufferSizes.split(",");
2210 }
2211
2212 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002213 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002214 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2215 values = tcpBufferSizes.split(",");
2216 }
2217
2218 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2219
2220 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002221 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002222
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002223 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2224 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2225 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002226 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002227 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002228 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002229 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002230
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002231 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002232 Settings.Global.TCP_DEFAULT_INIT_RWND,
2233 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002234 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2235 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002236 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002237 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002238 }
2239
Robert Greenwalt562cc542014-05-15 18:07:26 -07002240 @Override
2241 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002242 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002243 NETWORK_RESTORE_DELAY_PROP_NAME);
2244 if(restoreDefaultNetworkDelayStr != null &&
2245 restoreDefaultNetworkDelayStr.length() != 0) {
2246 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002247 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002248 } catch (NumberFormatException e) {
2249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002251 // if the system property isn't set, use the value for the apn type
2252 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2253
2254 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2255 (mNetConfigs[networkType] != null)) {
2256 ret = mNetConfigs[networkType].restoreTime;
2257 }
2258 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 }
2260
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002261 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2262 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2263 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002264 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002265 // Start gathering diagnostic information.
2266 netDiags.add(new NetworkDiagnostics(
2267 nai.network,
2268 new LinkProperties(nai.linkProperties), // Must be a copy.
2269 DIAG_TIME_MS));
2270 }
2271
2272 for (NetworkDiagnostics netDiag : netDiags) {
2273 pw.println();
2274 netDiag.waitForMeasurements();
2275 netDiag.dump(pw);
2276 }
2277 }
2278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002280 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002281 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2282 }
2283
2284 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002285 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002286 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002287 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002288
Erik Kline3f8306b2018-05-01 16:51:44 +09002289 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002290 dumpNetworkDiagnostics(pw);
2291 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002292 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002293 mTethering.dump(fd, pw, args);
2294 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002295 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2296 dumpNetworks(pw);
2297 return;
2298 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2299 dumpNetworkRequests(pw);
2300 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002301 }
Erik Kline379747a2015-06-05 17:47:34 +09002302
Lorenzo Colittie3805462015-06-03 11:18:24 +09002303 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002304 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002305 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002306 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002307 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002308 pw.println();
2309
Paul Jensen85cf78e2015-06-25 13:25:07 -04002310 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002311 pw.print("Active default network: ");
2312 if (defaultNai == null) {
2313 pw.println("none");
2314 } else {
2315 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002317 pw.println();
2318
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002319 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002320 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002321 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002322 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002323 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002324
junyulai05986c62018-08-07 19:50:45 +08002325 pw.print("Restrict background: ");
2326 pw.println(mRestrictBackground);
2327 pw.println();
2328
2329 pw.println("Status for known UIDs:");
2330 pw.increaseIndent();
2331 final int size = mUidRules.size();
2332 for (int i = 0; i < size; i++) {
2333 // Don't crash if the array is modified while dumping in bugreports.
2334 try {
2335 final int uid = mUidRules.keyAt(i);
2336 final int uidRules = mUidRules.get(uid, RULE_NONE);
2337 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2338 } catch (ArrayIndexOutOfBoundsException e) {
2339 pw.println(" ArrayIndexOutOfBoundsException");
2340 } catch (ConcurrentModificationException e) {
2341 pw.println(" ConcurrentModificationException");
2342 }
2343 }
2344 pw.println();
2345 pw.decreaseIndent();
2346
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002347 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002348 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002349 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002350 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002351 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002352
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002353 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002354
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002355 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002356 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002357
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002358 pw.println();
2359 mKeepaliveTracker.dump(pw);
2360
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002361 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002362 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002363
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002364 pw.println();
2365 mMultipathPolicyTracker.dump(pw);
2366
Erik Kline3f8306b2018-05-01 16:51:44 +09002367 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002368 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002369 pw.println("mNetworkRequestInfoLogs (most recent first):");
2370 pw.increaseIndent();
2371 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2372 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002373
2374 pw.println();
2375 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2376 pw.increaseIndent();
2377 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2378 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002379
2380 pw.println();
2381 pw.println("NetTransition WakeLock activity (most recent first):");
2382 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002383 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2384 pw.println("total releases: " + mTotalWakelockReleases);
2385 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2386 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2387 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2388 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2389 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2390 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002391 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002392
2393 pw.println();
2394 pw.println("bandwidth update requests (by uid):");
2395 pw.increaseIndent();
2396 synchronized (mBandwidthRequests) {
2397 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2398 pw.println("[" + mBandwidthRequests.keyAt(i)
2399 + "]: " + mBandwidthRequests.valueAt(i));
2400 }
2401 }
2402 pw.decreaseIndent();
2403
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002404 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002405 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002406
2407 pw.println();
2408 pw.println("NetworkStackClient logs:");
2409 pw.increaseIndent();
2410 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 }
2412
Hugo Benichi14683812018-09-03 08:32:56 +09002413 private void dumpNetworks(IndentingPrintWriter pw) {
2414 for (NetworkAgentInfo nai : networksSortedById()) {
2415 pw.println(nai.toString());
2416 pw.increaseIndent();
2417 pw.println(String.format(
2418 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2419 nai.numForegroundNetworkRequests(),
2420 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2421 nai.numBackgroundNetworkRequests(),
2422 nai.numNetworkRequests()));
2423 pw.increaseIndent();
2424 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2425 pw.println(nai.requestAt(i).toString());
2426 }
2427 pw.decreaseIndent();
2428 pw.println("Lingered:");
2429 pw.increaseIndent();
2430 nai.dumpLingerTimers(pw);
2431 pw.decreaseIndent();
2432 pw.decreaseIndent();
2433 }
2434 }
2435
2436 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2437 for (NetworkRequestInfo nri : requestsSortedById()) {
2438 pw.println(nri.toString());
2439 }
2440 }
2441
Hugo Benichia2a917c2018-09-03 08:19:02 +09002442 /**
2443 * Return an array of all current NetworkAgentInfos sorted by network id.
2444 */
2445 private NetworkAgentInfo[] networksSortedById() {
2446 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2447 networks = mNetworkAgentInfos.values().toArray(networks);
2448 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2449 return networks;
2450 }
2451
2452 /**
2453 * Return an array of all current NetworkRequest sorted by request id.
2454 */
2455 private NetworkRequestInfo[] requestsSortedById() {
2456 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2457 requests = mNetworkRequests.values().toArray(requests);
2458 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2459 return requests;
2460 }
2461
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002462 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002463 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002464 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002465 if (officialNai != null && officialNai.equals(nai)) return true;
2466 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002467 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002468 " - " + nai);
2469 }
2470 return false;
2471 }
2472
Robert Greenwalt42acef32009-08-12 16:08:25 -07002473 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002474 private class NetworkStateTrackerHandler extends Handler {
2475 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002476 super(looper);
2477 }
2478
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002479 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002481 default:
2482 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002483 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002484 handleAsyncChannelHalfConnect(msg);
2485 break;
2486 }
2487 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2488 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2489 if (nai != null) nai.asyncChannel.disconnect();
2490 break;
2491 }
2492 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2493 handleAsyncChannelDisconnected(msg);
2494 break;
2495 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002496 }
2497 return true;
2498 }
2499
2500 private void maybeHandleNetworkAgentMessage(Message msg) {
2501 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2502 if (nai == null) {
2503 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002504 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002505 }
2506 return;
2507 }
2508
2509 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002510 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002511 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002512 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002513 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002514 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002515 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002516 break;
2517 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002518 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002519 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002520 break;
2521 }
2522 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002523 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002524 updateNetworkInfo(nai, info);
2525 break;
2526 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002527 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002528 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002529 break;
2530 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002531 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002532 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2533 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002534 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002535 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002536 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002537 // Mark the network as temporarily accepting partial connectivity so that it
2538 // will be validated (and possibly become default) even if it only provides
2539 // partial internet access. Note that if user connects to partial connectivity
2540 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2541 // out of wifi coverage) and if the same wifi is available again, the device
2542 // will auto connect to this wifi even though the wifi has "no internet".
2543 // TODO: Evaluate using a separate setting in IpMemoryStore.
2544 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002545 break;
2546 }
junyulai06835112019-01-03 18:50:15 +08002547 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2548 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002549 break;
2550 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002551 }
2552 }
2553
2554 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2555 switch (msg.what) {
2556 default:
2557 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002558 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002559 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002560 if (nai == null) break;
2561
lucasline252a742019-03-12 13:08:03 +08002562 final boolean partialConnectivity =
2563 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
lucasline252a742019-03-12 13:08:03 +08002564 || (nai.networkMisc.acceptPartialConnectivity
2565 && nai.partialConnectivity);
2566 // Once a network is determined to have partial connectivity, it cannot
lucaslin975b7d32019-03-21 11:59:22 +08002567 // go back to full connectivity without a disconnect. This is because
2568 // NetworkMonitor can only communicate either PARTIAL_CONNECTIVITY or VALID,
2569 // but not both.
2570 // TODO: Provide multi-testResult to improve the communication between
2571 // ConnectivityService and NetworkMonitor, so that ConnectivityService could
2572 // know the real status of network.
lucaslin43338992019-03-20 18:21:59 +08002573 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002574 (partialConnectivity && !nai.partialConnectivity);
2575
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002576 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002577 final boolean wasValidated = nai.lastValidated;
2578 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002579 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2580 && valid) {
2581 nai.captivePortalLoginNotified = true;
2582 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2583 }
Erik Klinea24d4592018-01-11 21:07:29 +09002584
Erik Klinea24d4592018-01-11 21:07:29 +09002585 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2586
Erik Klinea24d4592018-01-11 21:07:29 +09002587 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002588 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2589 ? " with redirect to " + redirectUrl
2590 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002591 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2592 }
Erik Klinea24d4592018-01-11 21:07:29 +09002593 if (valid != nai.lastValidated) {
2594 if (wasDefault) {
2595 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2596 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002597 }
Erik Klinea24d4592018-01-11 21:07:29 +09002598 final int oldScore = nai.getCurrentScore();
2599 nai.lastValidated = valid;
2600 nai.everValidated |= valid;
2601 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2602 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2603 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002604 if (valid) {
2605 handleFreshlyValidatedNetwork(nai);
2606 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2607 // valid.
2608 mNotifier.clearNotification(nai.network.netId,
2609 NotificationType.NO_INTERNET);
2610 mNotifier.clearNotification(nai.network.netId,
2611 NotificationType.LOST_INTERNET);
2612 }
lucaslin43338992019-03-20 18:21:59 +08002613 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002614 nai.partialConnectivity = partialConnectivity;
2615 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002616 }
2617 updateInetCondition(nai);
2618 // Let the NetworkAgent know the state of its network
2619 Bundle redirectUrlBundle = new Bundle();
2620 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2621 nai.asyncChannel.sendMessage(
2622 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2623 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2624 0, redirectUrlBundle);
2625 if (wasValidated && !nai.lastValidated) {
2626 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002627 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002628 break;
2629 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002630 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002631 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002632 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002633 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002634 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002635 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002636 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002637 nai.lastCaptivePortalDetected = visible;
2638 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002639 if (visible) {
2640 nai.captivePortalLoginNotified = false;
2641 }
Calvin Onbe96da12016-10-11 15:10:46 -07002642 if (nai.lastCaptivePortalDetected &&
2643 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2644 if (DBG) log("Avoiding captive portal network: " + nai.name());
2645 nai.asyncChannel.sendMessage(
2646 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2647 teardownUnneededNetwork(nai);
2648 break;
2649 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002650 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002651 }
2652 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002653 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002654 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002655 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2656 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002657 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002658 if (nai == null) {
2659 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2660 break;
2661 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002662 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002663 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002664 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002665 }
Paul Jensen869868be2014-05-15 10:33:05 -04002666 }
Paul Jensen869868be2014-05-15 10:33:05 -04002667 break;
2668 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002669 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002670 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002671 if (nai == null) break;
2672
Erik Kline736353a2018-03-21 07:18:33 -07002673 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002674 break;
2675 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002676 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002677 return true;
2678 }
2679
Calvin Onbe96da12016-10-11 15:10:46 -07002680 private int getCaptivePortalMode() {
2681 return Settings.Global.getInt(mContext.getContentResolver(),
2682 Settings.Global.CAPTIVE_PORTAL_MODE,
2683 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2684 }
2685
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002686 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2687 switch (msg.what) {
2688 default:
2689 return false;
2690 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2691 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2692 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2693 handleLingerComplete(nai);
2694 }
2695 break;
2696 }
2697 }
2698 return true;
2699 }
2700
Etan Cohenddb720a2019-01-08 12:09:18 -08002701 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2702 switch (msg.what) {
2703 default:
2704 return false;
2705 case android.net.NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2706 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2707 /* callOnUnavailable */ true);
2708 break;
2709 }
2710 }
2711 return true;
2712 }
2713
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002714 @Override
2715 public void handleMessage(Message msg) {
Etan Cohenddb720a2019-01-08 12:09:18 -08002716 if (!maybeHandleAsyncChannelMessage(msg)
2717 && !maybeHandleNetworkMonitorMessage(msg)
2718 && !maybeHandleNetworkAgentInfoMessage(msg)
2719 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002720 maybeHandleNetworkAgentMessage(msg);
2721 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002722 }
2723 }
2724
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002725 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2726 private final NetworkAgentInfo mNai;
2727
2728 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2729 mNai = nai;
2730 }
2731
2732 @Override
2733 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2735 new Pair<>(mNai, networkMonitor)));
2736 }
2737
2738 @Override
2739 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2740 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2741 testResult, mNai.network.netId, redirectUrl));
2742 }
2743
2744 @Override
2745 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2746 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2747 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2748 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2749 }
2750
2751 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002752 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002753 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002754 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002755
2756 final PendingIntent pendingIntent;
2757 // Only the system server can register notifications with package "android"
2758 final long token = Binder.clearCallingIdentity();
2759 try {
2760 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2761 } finally {
2762 Binder.restoreCallingIdentity(token);
2763 }
2764 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2765 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2766 mNai.network.netId,
2767 pendingIntent));
2768 }
2769
2770 @Override
2771 public void hideProvisioningNotification() {
2772 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2773 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2774 mNai.network.netId));
2775 }
2776 }
2777
Erik Kline736353a2018-03-21 07:18:33 -07002778 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002779 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002780 }
2781
Erik Klinec6d00222018-06-26 18:53:43 +09002782 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2783 if (nai == null) return;
2784 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2785 // in order to restart a validation pass from within netd.
2786 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2787 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2788 updateDnses(nai.linkProperties, null, nai.network.netId);
2789 }
2790 }
2791
Erik Klinea24d4592018-01-11 21:07:29 +09002792 private void handlePrivateDnsSettingsChanged() {
2793 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2794
2795 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002796 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002797 if (networkRequiresValidation(nai)) {
2798 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2799 }
Erik Klinea24d4592018-01-11 21:07:29 +09002800 }
2801 }
2802
Erik Kline736353a2018-03-21 07:18:33 -07002803 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2804 // Private DNS only ever applies to networks that might provide
2805 // Internet access and therefore also require validation.
2806 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002807
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002808 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002809 // schedule DNS resolutions. If a DNS resolution is required the
2810 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002811 try {
2812 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2813 } catch (RemoteException e) {
2814 e.rethrowFromSystemServer();
2815 }
Erik Kline736353a2018-03-21 07:18:33 -07002816
2817 // With Private DNS bypass support, we can proceed to update the
2818 // Private DNS config immediately, even if we're in strict mode
2819 // and have not yet resolved the provider name into a set of IPs.
2820 updatePrivateDns(nai, cfg);
2821 }
2822
2823 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2824 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002825 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002826 }
2827
dalyk7301aa42018-03-05 12:42:22 -05002828 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2829 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2830 if (nai == null) {
2831 return;
2832 }
2833 mDnsManager.updatePrivateDnsValidation(update);
2834 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2835 }
2836
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002837 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2838 int prefixLength) {
2839 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2840 if (nai == null) return;
2841
2842 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2843 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2844
2845 IpPrefix prefix = null;
2846 if (added) {
2847 try {
2848 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2849 prefixLength);
2850 } catch (IllegalArgumentException e) {
2851 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2852 return;
2853 }
2854 }
2855
2856 nai.clatd.setNat64Prefix(prefix);
2857 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2858 }
2859
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002860 private void updateLingerState(NetworkAgentInfo nai, long now) {
2861 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2862 // 2. If the network was lingering and there are now requests, unlinger it.
2863 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2864 // one lingered request, start lingering.
2865 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002866 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002867 if (DBG) log("Unlingering " + nai.name());
2868 nai.unlinger();
2869 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002870 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002871 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002872 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002873 nai.linger();
2874 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2875 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2876 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002877 }
2878
Robert Greenwalt7b816022014-04-18 15:25:25 -07002879 private void handleAsyncChannelHalfConnect(Message msg) {
2880 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002881 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002882 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2883 if (VDBG) log("NetworkFactory connected");
Etan Cohenddb720a2019-01-08 12:09:18 -08002884 // Finish setting up the full connection
2885 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2886 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002887 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002888 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002889 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002890 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09002891 final int score;
2892 final int serial;
2893 if (nai != null) {
2894 score = nai.getCurrentScore();
2895 serial = nai.factorySerialNumber;
2896 } else {
2897 score = 0;
2898 serial = NetworkFactory.SerialNumber.NONE;
2899 }
2900 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2901 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002902 }
2903 } else {
2904 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002905 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002906 }
2907 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2908 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2909 if (VDBG) log("NetworkAgent connected");
2910 // A network agent has requested a connection. Establish the connection.
2911 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2912 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2913 } else {
2914 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002915 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002916 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002917 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002918 synchronized (mNetworkForNetId) {
2919 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002920 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002921 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002922 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002923 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002924 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002925 }
2926 }
2927 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002928
Chalard Jean392971c2018-05-11 20:19:20 +09002929 // This is a no-op if it's called with a message designating a network that has
2930 // already been destroyed, because its reference will not be found in the relevant
2931 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002932 private void handleAsyncChannelDisconnected(Message msg) {
2933 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2934 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002935 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002936 } else {
2937 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2938 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002939 }
2940 }
2941
Chalard Jean392971c2018-05-11 20:19:20 +09002942 // Destroys a network, remove references to it from the internal state managed by
2943 // ConnectivityService, free its interfaces and clean up.
2944 // Must be called on the Handler thread.
2945 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2946 if (DBG) {
2947 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2948 }
lucaslinf80b83b2019-02-12 15:30:13 +08002949 // Clear all notifications of this network.
2950 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002951 // A network agent has disconnected.
2952 // TODO - if we move the logic to the network agent (have them disconnect
2953 // because they lost all their requests or because their score isn't good)
2954 // then they would disconnect organically, report their new state and then
2955 // disconnect the channel.
2956 if (nai.networkInfo.isConnected()) {
2957 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2958 null, null);
2959 }
2960 final boolean wasDefault = isDefaultNetwork(nai);
2961 if (wasDefault) {
2962 mDefaultInetConditionPublished = 0;
2963 // Log default network disconnection before required book-keeping.
2964 // Let rematchAllNetworksAndRequests() below record a new default network event
2965 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2966 // whose timestamps tell how long it takes to recover a default network.
2967 long now = SystemClock.elapsedRealtime();
2968 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2969 }
2970 notifyIfacesChangedForNetworkStats();
2971 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2972 // by other networks that are already connected. Perhaps that can be done by
2973 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2974 // of rematchAllNetworksAndRequests
2975 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai06835112019-01-03 18:50:15 +08002976 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002977 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2978 // Disable wakeup packet monitoring for each interface.
2979 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2980 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002981 try {
2982 nai.networkMonitor().notifyNetworkDisconnected();
2983 } catch (RemoteException e) {
2984 e.rethrowFromSystemServer();
2985 }
Chalard Jean392971c2018-05-11 20:19:20 +09002986 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09002987 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09002988 synchronized (mNetworkForNetId) {
2989 // Remove the NetworkAgent, but don't mark the netId as
2990 // available until we've told netd to delete it below.
2991 mNetworkForNetId.remove(nai.network.netId);
2992 }
2993 // Remove all previously satisfied requests.
2994 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2995 NetworkRequest request = nai.requestAt(i);
2996 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2997 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2998 clearNetworkForRequest(request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09002999 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09003000 }
3001 }
3002 nai.clearLingerState();
3003 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08003004 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003005 notifyLockdownVpn(nai);
3006 ensureNetworkTransitionWakelock(nai.name());
3007 }
3008 mLegacyTypeTracker.remove(nai, wasDefault);
3009 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3010 updateAllVpnsCapabilities();
3011 }
3012 rematchAllNetworksAndRequests(null, 0);
3013 mLingerMonitor.noteDisconnect(nai);
3014 if (nai.created) {
3015 // Tell netd to clean up the configuration for this network
3016 // (routing rules, DNS, etc).
3017 // This may be slow as it requires a lot of netd shelling out to ip and
3018 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3019 // after we've rematched networks with requests which should make a potential
3020 // fallback network the default or requested a new network from the
3021 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3022 // long time.
3023 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08003024 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003025 } catch (Exception e) {
3026 loge("Exception removing network: " + e);
3027 }
3028 mDnsManager.removeNetwork(nai.network);
3029 }
3030 synchronized (mNetworkForNetId) {
3031 mNetIdInUse.delete(nai.network.netId);
3032 }
3033 }
3034
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003035 // If this method proves to be too slow then we can maintain a separate
3036 // pendingIntent => NetworkRequestInfo map.
3037 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3038 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3039 Intent intent = pendingIntent.getIntent();
3040 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3041 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3042 if (existingPendingIntent != null &&
3043 existingPendingIntent.getIntent().filterEquals(intent)) {
3044 return entry.getValue();
3045 }
3046 }
3047 return null;
3048 }
3049
3050 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3051 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3052
3053 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3054 if (existingRequest != null) { // remove the existing request.
3055 if (DBG) log("Replacing " + existingRequest.request + " with "
3056 + nri.request + " because their intents matched.");
Etan Cohenddb720a2019-01-08 12:09:18 -08003057 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3058 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003059 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003060 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003061 }
3062
Erik Klineda4bfa82015-04-30 12:58:40 +09003063 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003064 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003065 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003066 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003067 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003068 if (nri.request.networkCapabilities.hasSignalStrength() &&
3069 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3070 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003071 }
3072 }
3073 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003074 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003075 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003076 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003077 }
3078 }
3079
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003080 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3081 int callingUid) {
3082 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3083 if (nri != null) {
Etan Cohenddb720a2019-01-08 12:09:18 -08003084 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003085 }
3086 }
3087
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003088 // Determines whether the network is the best (or could become the best, if it validated), for
3089 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3090 // on the value of reason:
3091 //
3092 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3093 // then it should be torn down.
3094 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3095 // then it should be lingered.
3096 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3097 final int numRequests;
3098 switch (reason) {
3099 case TEARDOWN:
3100 numRequests = nai.numRequestNetworkRequests();
3101 break;
3102 case LINGER:
3103 numRequests = nai.numForegroundNetworkRequests();
3104 break;
3105 default:
3106 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3107 return true;
3108 }
3109
3110 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003111 return false;
3112 }
Paul Jensene0988542015-06-25 15:30:08 -04003113 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003114 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3115 // Background requests don't affect lingering.
3116 continue;
3117 }
3118
Paul Jensene0988542015-06-25 15:30:08 -04003119 // If this Network is already the highest scoring Network for a request, or if
3120 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003121 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003122 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003123 // Note that this catches two important cases:
3124 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3125 // is currently satisfying the request. This is desirable when
3126 // cellular ends up validating but WiFi does not.
3127 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003128 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003129 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003130 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003131 nai.getCurrentScoreAsValidated())) {
3132 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003133 }
3134 }
Paul Jensene0988542015-06-25 15:30:08 -04003135 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003136 }
3137
Erik Klineacdd6392016-07-07 16:50:58 +09003138 private NetworkRequestInfo getNriForAppRequest(
3139 NetworkRequest request, int callingUid, String requestedOperation) {
3140 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3141
Robert Greenwalt9258c642014-03-26 16:47:06 -07003142 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003143 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003144 log(String.format("UID %d attempted to %s for unowned request %s",
3145 callingUid, requestedOperation, nri));
3146 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003147 }
Erik Klineacdd6392016-07-07 16:50:58 +09003148 }
3149
3150 return nri;
3151 }
3152
Erik Kline57faba92015-11-25 12:49:38 +09003153 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003154 if (mNetworkRequests.get(nri.request) == null) {
3155 return;
Erik Kline57faba92015-11-25 12:49:38 +09003156 }
Hugo Benichicd952782017-09-20 11:20:14 +09003157 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003158 return;
3159 }
3160 if (VDBG || (DBG && nri.request.isRequest())) {
3161 log("releasing " + nri.request + " (timeout)");
3162 }
3163 handleRemoveNetworkRequest(nri);
3164 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003165 }
3166
Etan Cohenddb720a2019-01-08 12:09:18 -08003167 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3168 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003169 final NetworkRequestInfo nri =
3170 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3171 if (nri == null) {
3172 return;
Erik Kline57faba92015-11-25 12:49:38 +09003173 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003174 if (VDBG || (DBG && nri.request.isRequest())) {
3175 log("releasing " + nri.request + " (release request)");
3176 }
3177 handleRemoveNetworkRequest(nri);
Etan Cohenddb720a2019-01-08 12:09:18 -08003178 if (callOnUnavailable) {
3179 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3180 }
Erik Kline57faba92015-11-25 12:49:38 +09003181 }
Erik Klineacdd6392016-07-07 16:50:58 +09003182
Hugo Benichidba33db2017-03-23 22:40:44 +09003183 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003184 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003185 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003186
Erik Klineacdd6392016-07-07 16:50:58 +09003187 synchronized (mUidToNetworkRequestCount) {
3188 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3189 if (requests < 1) {
3190 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3191 nri.mUid);
3192 } else if (requests == 1) {
3193 mUidToNetworkRequestCount.removeAt(
3194 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3195 } else {
3196 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3197 }
3198 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003199
Erik Klineacdd6392016-07-07 16:50:58 +09003200 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3201 if (nri.request.isRequest()) {
3202 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003203 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003204 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003205 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003206 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003207 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003208 log(" Removing from current network " + nai.name() +
3209 ", leaving " + nai.numNetworkRequests() + " requests.");
3210 }
3211 // If there are still lingered requests on this network, don't tear it down,
3212 // but resume lingering instead.
3213 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003214 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003215 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3216 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003217 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003218 wasKept = true;
3219 }
Hugo Benichicd952782017-09-20 11:20:14 +09003220 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003221 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3222 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003223 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003224 }
Erik Klineacdd6392016-07-07 16:50:58 +09003225 }
3226
Erik Klineacdd6392016-07-07 16:50:58 +09003227 // Maintain the illusion. When this request arrived, we might have pretended
3228 // that a network connected to serve it, even though the network was already
3229 // connected. Now that this request has gone away, we might have to pretend
3230 // that the network disconnected. LegacyTypeTracker will generate that
3231 // phantom disconnect for this type.
3232 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3233 boolean doRemove = true;
3234 if (wasKept) {
3235 // check if any of the remaining requests for this network are for the
3236 // same legacy type - if so, don't remove the nai
3237 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3238 NetworkRequest otherRequest = nai.requestAt(i);
3239 if (otherRequest.legacyType == nri.request.legacyType &&
3240 otherRequest.isRequest()) {
3241 if (DBG) log(" still have other legacy request - leaving");
3242 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003243 }
3244 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003245 }
3246
Erik Klineacdd6392016-07-07 16:50:58 +09003247 if (doRemove) {
3248 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003249 }
3250 }
Erik Klineacdd6392016-07-07 16:50:58 +09003251
3252 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3253 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3254 nri.request);
3255 }
3256 } else {
3257 // listens don't have a singular affectedNetwork. Check all networks to see
3258 // if this listen request applies and remove it.
3259 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3260 nai.removeRequest(nri.request.requestId);
3261 if (nri.request.networkCapabilities.hasSignalStrength() &&
3262 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3263 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3264 }
3265 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003266 }
3267 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003268
Lorenzo Colitti18660282016-07-04 12:55:44 +09003269 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003270 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003271 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003272 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003273 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003274 }
3275
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003276 @Override
lucasline252a742019-03-12 13:08:03 +08003277 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3278 enforceNetworkStackSettingsOrSetup();
3279 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3280 encodeBool(accept), encodeBool(always), network));
3281 }
3282
3283 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003284 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003285 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003286 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3287 }
3288
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003289 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3290 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3291 " accept=" + accept + " always=" + always);
3292
3293 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3294 if (nai == null) {
3295 // Nothing to do.
3296 return;
3297 }
3298
3299 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003300 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003301 return;
3302 }
3303
3304 if (!nai.networkMisc.explicitlySelected) {
3305 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3306 }
3307
3308 if (accept != nai.networkMisc.acceptUnvalidated) {
3309 int oldScore = nai.getCurrentScore();
3310 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003311 // If network becomes partial connectivity and user already accepted to use this
3312 // network, we should respect the user's option and don't need to popup the
3313 // PARTIAL_CONNECTIVITY notification to user again.
3314 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003315 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003316 sendUpdatedScoreToFactories(nai);
3317 }
3318
3319 if (always) {
3320 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003321 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003322 }
3323
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003324 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003325 // Tell the NetworkAgent to not automatically reconnect to the network.
3326 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003327 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003328 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003329 }
3330
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003331 }
3332
lucasline252a742019-03-12 13:08:03 +08003333 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3334 boolean always) {
3335 if (DBG) {
3336 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3337 + " always=" + always);
3338 }
3339
3340 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3341 if (nai == null) {
3342 // Nothing to do.
3343 return;
3344 }
3345
3346 if (nai.lastValidated) {
3347 // The network validated while the dialog box was up. Take no action.
3348 return;
3349 }
3350
3351 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3352 nai.networkMisc.acceptPartialConnectivity = accept;
3353 }
3354
3355 // TODO: Use the current design or save the user choice into IpMemoryStore.
3356 if (always) {
3357 nai.asyncChannel.sendMessage(
3358 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3359 }
3360
3361 if (!accept) {
3362 // Tell the NetworkAgent to not automatically reconnect to the network.
3363 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3364 // Tear down the network.
3365 teardownUnneededNetwork(nai);
3366 } else {
lucaslin43338992019-03-20 18:21:59 +08003367 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3368 // result in a partial connectivity result which will be processed by
3369 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003370 try {
lucaslin43338992019-03-20 18:21:59 +08003371 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003372 } catch (RemoteException e) {
3373 e.rethrowFromSystemServer();
3374 }
3375 }
3376 }
3377
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003378 private void handleSetAvoidUnvalidated(Network network) {
3379 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3380 if (nai == null || nai.lastValidated) {
3381 // Nothing to do. The network either disconnected or revalidated.
3382 return;
3383 }
3384 if (!nai.avoidUnvalidated) {
3385 int oldScore = nai.getCurrentScore();
3386 nai.avoidUnvalidated = true;
3387 rematchAllNetworksAndRequests(nai, oldScore);
3388 sendUpdatedScoreToFactories(nai);
3389 }
3390 }
3391
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003392 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003393 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003394 mHandler.sendMessageDelayed(
3395 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3396 PROMPT_UNVALIDATED_DELAY_MS);
3397 }
3398
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003399 @Override
3400 public void startCaptivePortalApp(Network network) {
3401 enforceConnectivityInternalPermission();
3402 mHandler.post(() -> {
3403 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3404 if (nai == null) return;
3405 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003406 try {
3407 nai.networkMonitor().launchCaptivePortalApp();
3408 } catch (RemoteException e) {
3409 e.rethrowFromSystemServer();
3410 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003411 });
3412 }
3413
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003414 /**
3415 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3416 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003417 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003418 * @param appExtras Bundle to use as intent extras for the captive portal application.
3419 * Must be treated as opaque to avoid preventing the captive portal app to
3420 * update its arguments.
3421 */
3422 @Override
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003423 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003424 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3425
3426 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3427 appIntent.putExtras(appExtras);
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003428 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3429 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003430 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3431
3432 Binder.withCleanCallingIdentity(() ->
3433 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3434 }
3435
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003436 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3437 private final Network mNetwork;
3438
3439 private CaptivePortalImpl(Network network) {
3440 mNetwork = network;
3441 }
3442
3443 @Override
3444 public void appResponse(final int response) throws RemoteException {
3445 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3446 enforceSettingsPermission();
3447 }
3448
3449 // getNetworkAgentInfoForNetwork is thread-safe
3450 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3451 if (nai == null) return;
3452
3453 // nai.networkMonitor() is thread-safe
3454 final INetworkMonitor nm = nai.networkMonitor();
3455 if (nm == null) return;
3456
3457 final long token = Binder.clearCallingIdentity();
3458 try {
3459 nm.notifyCaptivePortalAppFinished(response);
3460 } finally {
3461 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3462 Binder.restoreCallingIdentity(token);
3463 }
3464 }
3465
3466 @Override
3467 public void logEvent(int eventId, String packageName) {
3468 enforceSettingsPermission();
3469
3470 new MetricsLogger().action(eventId, packageName);
3471 }
3472 }
3473
Hugo Benichic8e9e122016-09-14 23:23:08 +00003474 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003475 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003476 }
3477
Remi NGUYEN VANe2365d62019-03-22 11:14:13 +09003478 /**
3479 * Return whether the device should maintain continuous, working connectivity by switching away
3480 * from WiFi networks having no connectivity.
3481 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3482 */
3483 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003484 if (!checkNetworkStackPermission()) {
3485 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3486 }
3487 return avoidBadWifi();
3488 }
3489
3490
Erik Kline065ab6e2016-10-02 18:02:14 +09003491 private void rematchForAvoidBadWifiUpdate() {
3492 rematchAllNetworksAndRequests(null, 0);
3493 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3494 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3495 sendUpdatedScoreToFactories(nai);
3496 }
3497 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003498 }
3499
Erik Kline065ab6e2016-10-02 18:02:14 +09003500 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003501 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003502 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003503 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003504 if (!configRestrict) {
3505 pw.println("Bad Wi-Fi avoidance: unrestricted");
3506 return;
3507 }
3508
3509 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3510 pw.increaseIndent();
3511 pw.println("Config restrict: " + configRestrict);
3512
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003513 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003514 String description;
3515 // Can't use a switch statement because strings are legal case labels, but null is not.
3516 if ("0".equals(value)) {
3517 description = "get stuck";
3518 } else if (value == null) {
3519 description = "prompt";
3520 } else if ("1".equals(value)) {
3521 description = "avoid";
3522 } else {
3523 description = value + " (?)";
3524 }
3525 pw.println("User setting: " + description);
3526 pw.println("Network overrides:");
3527 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003528 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003529 if (nai.avoidUnvalidated) {
3530 pw.println(nai.name());
3531 }
3532 }
3533 pw.decreaseIndent();
3534 pw.decreaseIndent();
3535 }
3536
lucaslind2e045e02019-01-24 15:55:30 +08003537 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003538 final String action;
3539 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003540 case LOGGED_IN:
3541 action = Settings.ACTION_WIFI_SETTINGS;
3542 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3543 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3544 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3545 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003546 case NO_INTERNET:
3547 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3548 break;
3549 case LOST_INTERNET:
3550 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3551 break;
lucasline252a742019-03-12 13:08:03 +08003552 case PARTIAL_CONNECTIVITY:
3553 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3554 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003555 default:
3556 Slog.wtf(TAG, "Unknown notification type " + type);
3557 return;
3558 }
3559
3560 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003561 if (type != NotificationType.LOGGED_IN) {
3562 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3563 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3564 intent.setClassName("com.android.settings",
3565 "com.android.settings.wifi.WifiNoInternetDialog");
3566 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003567
3568 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3569 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3570 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3571 }
3572
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003573 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003574 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003575 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3576
lucasline252a742019-03-12 13:08:03 +08003577 // Only prompt if the network is unvalidated or network has partial internet connectivity
3578 // and was explicitly selected by the user, and if we haven't already been told to switch
3579 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3580 // because we're already prompting the user to sign in.
3581 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3582 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003583 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3584 // we should reevaluate how to handle acceptPartialConnectivity when network just
3585 // connected.
lucasline252a742019-03-12 13:08:03 +08003586 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003587 return;
3588 }
lucasline252a742019-03-12 13:08:03 +08003589 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3590 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3591 // popup the notification immediately when the network is partial connectivity.
3592 if (nai.partialConnectivity) {
lucaslin975b7d32019-03-21 11:59:22 +08003593 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucasline252a742019-03-12 13:08:03 +08003594 } else {
3595 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3596 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003597 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003598
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003599 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3600 NetworkCapabilities nc = nai.networkCapabilities;
3601 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003602
lucasline252a742019-03-12 13:08:03 +08003603 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3604 return;
3605 }
3606
3607 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003608 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003609 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003610 }
3611
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003612 @Override
3613 public int getMultipathPreference(Network network) {
3614 enforceAccessPermission();
3615
3616 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003617 if (nai != null && nai.networkCapabilities
3618 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003619 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3620 }
3621
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003622 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3623 if (networkPreference != null) {
3624 return networkPreference;
3625 }
3626
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003627 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3628 }
3629
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003630 @Override
3631 public NetworkRequest getDefaultRequest() {
3632 return mDefaultRequest;
3633 }
3634
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003635 private class InternalHandler extends Handler {
3636 public InternalHandler(Looper looper) {
3637 super(looper);
3638 }
3639
3640 @Override
3641 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003642 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003643 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003644 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003645 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003646 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003647 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003648 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003649 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003650 break;
3651 }
Jason Monkdecd2952013-10-10 14:02:51 -04003652 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003653 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003654 break;
3655 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003656 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003657 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3658 break;
3659 }
3660 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3661 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003662 break;
3663 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003664 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003665 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3666 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3667 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003668 break;
3669 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003670 case EVENT_REGISTER_NETWORK_REQUEST:
3671 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003672 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003673 break;
3674 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003675 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3676 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003677 handleRegisterNetworkRequestWithIntent(msg);
3678 break;
3679 }
Erik Kline57faba92015-11-25 12:49:38 +09003680 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3681 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3682 handleTimedOutNetworkRequest(nri);
3683 break;
3684 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003685 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3686 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3687 break;
3688 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003689 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenddb720a2019-01-08 12:09:18 -08003690 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3691 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003692 break;
3693 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003694 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003695 Network network = (Network) msg.obj;
3696 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003697 break;
3698 }
lucasline252a742019-03-12 13:08:03 +08003699 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3700 Network network = (Network) msg.obj;
3701 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3702 toBool(msg.arg2));
3703 break;
3704 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003705 case EVENT_SET_AVOID_UNVALIDATED: {
3706 handleSetAvoidUnvalidated((Network) msg.obj);
3707 break;
3708 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003709 case EVENT_PROMPT_UNVALIDATED: {
3710 handlePromptUnvalidated((Network) msg.obj);
3711 break;
3712 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003713 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3714 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003715 break;
3716 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003717 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003718 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003719 mKeepaliveTracker.handleStartKeepalive(msg);
3720 break;
3721 }
3722 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003723 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003724 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3725 int slot = msg.arg1;
3726 int reason = msg.arg2;
3727 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3728 break;
3729 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003730 case EVENT_SYSTEM_READY: {
3731 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003732 // Might have been called already in handleRegisterNetworkAgent since
3733 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3734 // this several times is fine.
3735 try {
3736 nai.networkMonitor().notifySystemReady();
3737 } catch (RemoteException e) {
3738 e.rethrowFromSystemServer();
3739 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003740 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003741 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003742 break;
3743 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003744 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003745 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003746 break;
3747 }
Erik Klinea24d4592018-01-11 21:07:29 +09003748 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3749 handlePrivateDnsSettingsChanged();
3750 break;
dalyk7301aa42018-03-05 12:42:22 -05003751 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3752 handlePrivateDnsValidationUpdate(
3753 (PrivateDnsValidationUpdate) msg.obj);
3754 break;
junyulai05986c62018-08-07 19:50:45 +08003755 case EVENT_UID_RULES_CHANGED:
3756 handleUidRulesChanged(msg.arg1, msg.arg2);
3757 break;
3758 case EVENT_DATA_SAVER_CHANGED:
3759 handleRestrictBackgroundChanged(toBool(msg.arg1));
3760 break;
lucaslind2e045e02019-01-24 15:55:30 +08003761 case EVENT_TIMEOUT_NOTIFICATION:
3762 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3763 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 }
3765 }
3766 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003767
3768 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003769 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003770 public int tether(String iface, String callerPkg) {
3771 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003772 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003773 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003774 } else {
3775 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3776 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003777 }
3778
3779 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003780 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003781 public int untether(String iface, String callerPkg) {
3782 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003783
3784 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003785 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003786 } else {
3787 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3788 }
3789 }
3790
3791 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003792 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003793 public int getLastTetherError(String iface) {
3794 enforceTetherAccessPermission();
3795
3796 if (isTetheringSupported()) {
3797 return mTethering.getLastTetherError(iface);
3798 } else {
3799 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3800 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003801 }
3802
3803 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003804 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003805 public String[] getTetherableUsbRegexs() {
3806 enforceTetherAccessPermission();
3807 if (isTetheringSupported()) {
3808 return mTethering.getTetherableUsbRegexs();
3809 } else {
3810 return new String[0];
3811 }
3812 }
3813
Lorenzo Colitti18660282016-07-04 12:55:44 +09003814 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003815 public String[] getTetherableWifiRegexs() {
3816 enforceTetherAccessPermission();
3817 if (isTetheringSupported()) {
3818 return mTethering.getTetherableWifiRegexs();
3819 } else {
3820 return new String[0];
3821 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003822 }
3823
Lorenzo Colitti18660282016-07-04 12:55:44 +09003824 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003825 public String[] getTetherableBluetoothRegexs() {
3826 enforceTetherAccessPermission();
3827 if (isTetheringSupported()) {
3828 return mTethering.getTetherableBluetoothRegexs();
3829 } else {
3830 return new String[0];
3831 }
3832 }
3833
Lorenzo Colitti18660282016-07-04 12:55:44 +09003834 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003835 public int setUsbTethering(boolean enable, String callerPkg) {
3836 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003837 if (isTetheringSupported()) {
3838 return mTethering.setUsbTethering(enable);
3839 } else {
3840 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3841 }
3842 }
3843
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003844 // TODO - move iface listing, queries, etc to new module
3845 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003846 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003847 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003848 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003849 return mTethering.getTetherableIfaces();
3850 }
3851
Lorenzo Colitti18660282016-07-04 12:55:44 +09003852 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003853 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003854 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003855 return mTethering.getTetheredIfaces();
3856 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003857
Lorenzo Colitti18660282016-07-04 12:55:44 +09003858 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003859 public String[] getTetheringErroredIfaces() {
3860 enforceTetherAccessPermission();
3861 return mTethering.getErroredIfaces();
3862 }
3863
Lorenzo Colitti18660282016-07-04 12:55:44 +09003864 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003865 public String[] getTetheredDhcpRanges() {
3866 enforceConnectivityInternalPermission();
3867 return mTethering.getTetheredDhcpRanges();
3868 }
3869
Udam Saini0e94c362017-06-07 12:06:28 -07003870 @Override
3871 public boolean isTetheringSupported(String callerPkg) {
3872 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3873 return isTetheringSupported();
3874 }
3875
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003876 // if ro.tether.denied = true we default to no tethering
3877 // gservices could set the secure setting to 1 though to enable it on a build where it
3878 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003879 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003880 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3881 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3882 Settings.Global.TETHER_SUPPORTED, defaultVal));
3883 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003884 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003885
3886 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3887 boolean adminUser = false;
3888 final long token = Binder.clearCallingIdentity();
3889 try {
3890 adminUser = mUserManager.isAdminUser();
3891 } finally {
3892 Binder.restoreCallingIdentity(token);
3893 }
3894
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003895 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003896 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003897
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003898 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003899 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3900 String callerPkg) {
3901 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003902 if (!isTetheringSupported()) {
3903 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3904 return;
3905 }
3906 mTethering.startTethering(type, receiver, showProvisioningUi);
3907 }
3908
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003909 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003910 public void stopTethering(int type, String callerPkg) {
3911 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003912 mTethering.stopTethering(type);
3913 }
3914
markchienf2731272019-01-16 17:44:13 +08003915 /**
3916 * Get the latest value of the tethering entitlement check.
3917 *
3918 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3919 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3920 * if it's really needed.
3921 */
3922 @Override
markchien9554abf2019-03-06 16:25:00 +08003923 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003924 boolean showEntitlementUi, String callerPkg) {
3925 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003926 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003927 }
3928
markchien26299ed2019-02-27 14:56:11 +08003929 /** Register tethering event callback. */
3930 @Override
3931 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3932 String callerPkg) {
3933 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3934 mTethering.registerTetheringEventCallback(callback);
3935 }
3936
3937 /** Unregister tethering event callback. */
3938 @Override
3939 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3940 String callerPkg) {
3941 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3942 mTethering.unregisterTetheringEventCallback(callback);
3943 }
3944
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003945 // Called when we lose the default network and have no replacement yet.
3946 // This will automatically be cleared after X seconds or a new default network
3947 // becomes CONNECTED, whichever happens first. The timer is started by the
3948 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003949 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003950 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003951 if (mNetTransitionWakeLock.isHeld()) {
3952 return;
3953 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003954 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003955 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3956 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003957 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003958 mWakelockLogs.log("ACQUIRE for " + forWhom);
3959 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3960 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003961 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003962
Hugo Benichi4c31b342017-03-30 23:18:10 +09003963 // Called when we gain a new default network to release the network transition wakelock in a
3964 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3965 // message is cancelled.
3966 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003967 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003968 if (!mNetTransitionWakeLock.isHeld()) {
3969 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003970 }
3971 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003972 // Cancel self timeout on wakelock hold.
3973 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3974 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3975 mHandler.sendMessageDelayed(msg, 1000);
3976 }
3977
3978 // Called when either message of ensureNetworkTransitionWakelock or
3979 // scheduleReleaseNetworkTransitionWakelock is processed.
3980 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3981 String event = eventName(eventId);
3982 synchronized (this) {
3983 if (!mNetTransitionWakeLock.isHeld()) {
3984 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3985 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3986 return;
3987 }
3988 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003989 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3990 mTotalWakelockDurationMs += lockDuration;
3991 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3992 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003993 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003994 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003995 }
3996
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003997 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003998 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003999 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004000 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09004001 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004002 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004003 }
4004
Lorenzo Colitti18660282016-07-04 12:55:44 +09004005 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004006 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004007 enforceAccessPermission();
4008 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004009 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004010 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004011 mHandler.sendMessage(
4012 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4013 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004014
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004015 private void handleReportNetworkConnectivity(
4016 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004017 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004018 if (network == null) {
4019 nai = getDefaultNetwork();
4020 } else {
4021 nai = getNetworkAgentInfoForNetwork(network);
4022 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004023 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4024 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4025 return;
4026 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004027 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004028 if (hasConnectivity == nai.lastValidated) {
4029 return;
4030 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004031 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004032 int netid = nai.network.netId;
4033 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004034 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004035 // Validating a network that has not yet connected could result in a call to
4036 // rematchNetworkAndRequests() which is not meant to work on such networks.
4037 if (!nai.everConnected) {
4038 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004039 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004040 LinkProperties lp = getLinkProperties(nai);
4041 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4042 return;
4043 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004044 try {
4045 nai.networkMonitor().forceReevaluation(uid);
4046 } catch (RemoteException e) {
4047 e.rethrowFromSystemServer();
4048 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004049 }
4050
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004051 /**
4052 * Returns information about the proxy a certain network is using. If given a null network, it
4053 * it will return the proxy for the bound network for the caller app or the default proxy if
4054 * none.
4055 *
4056 * @param network the network we want to get the proxy information for.
4057 * @return Proxy information if a network has a proxy configured, or otherwise null.
4058 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004059 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004060 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004061 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004062 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004063 if (network == null) {
4064 // Get the network associated with the calling UID.
4065 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4066 true);
4067 if (activeNetwork == null) {
4068 return null;
4069 }
4070 return getLinkPropertiesProxyInfo(activeNetwork);
4071 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4072 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4073 // caller may not have.
4074 return getLinkPropertiesProxyInfo(network);
4075 }
4076 // No proxy info available if the calling UID does not have network access.
4077 return null;
4078 }
4079
4080 @VisibleForTesting
4081 protected boolean queryUserAccess(int uid, int netId) {
4082 return NetworkUtils.queryUserAccess(uid, netId);
4083 }
4084
4085 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004086 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4087 if (nai == null) return null;
4088 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004089 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4090 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004091 }
4092 }
4093
Chalard Jean3c443fc2018-06-07 18:37:59 +09004094 @Override
4095 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004096 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004097 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004098 }
4099
Chalard Jean5afbc832018-06-07 18:02:37 +09004100 @Override
4101 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004102 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004103 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004104 }
4105
Jason Monk207900c2014-04-25 15:00:09 -04004106 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004107 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004108 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004109 proxy = null;
4110 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004111 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004112 }
4113
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004114 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4115 // when any network changes proxy.
4116 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4117 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004118 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004119 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4120 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4121
Chalard Jean4949dd72018-06-07 17:41:29 +09004122 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004123 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004124 }
4125 }
4126
Robert Greenwalt434203a2010-10-11 16:00:27 -07004127 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004128 final private HashMap<Uri, Integer> mUriEventMap;
4129 final private Context mContext;
4130 final private Handler mHandler;
4131
4132 SettingsObserver(Context context, Handler handler) {
4133 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004134 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004135 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004136 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004137 }
4138
Erik Klineda4bfa82015-04-30 12:58:40 +09004139 void observe(Uri uri, int what) {
4140 mUriEventMap.put(uri, what);
4141 final ContentResolver resolver = mContext.getContentResolver();
4142 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004143 }
4144
4145 @Override
4146 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004147 Slog.wtf(TAG, "Should never be reached.");
4148 }
4149
4150 @Override
4151 public void onChange(boolean selfChange, Uri uri) {
4152 final Integer what = mUriEventMap.get(uri);
4153 if (what != null) {
4154 mHandler.obtainMessage(what.intValue()).sendToTarget();
4155 } else {
4156 loge("No matching event to send for URI=" + uri);
4157 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004158 }
4159 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004160
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004161 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004162 Slog.d(TAG, s);
4163 }
4164
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004165 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004166 Slog.e(TAG, s);
4167 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004168
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004169 private static void loge(String s, Throwable t) {
4170 Slog.e(TAG, s, t);
4171 }
4172
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004173 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004174 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004175 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4176 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4177 *
4178 * @param oldPackage Package name of the application which currently controls VPN, which will
4179 * be replaced. If there is no such application, this should should either be
4180 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4181 * @param newPackage Package name of the application which should gain control of VPN, or
4182 * {@code null} to disable.
4183 * @param userId User for whom to prepare the new VPN.
4184 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004185 * @hide
4186 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004187 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004188 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4189 int userId) {
4190 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004191
Hugo Benichi20035e02017-04-26 14:53:28 +09004192 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004193 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004194 Vpn vpn = mVpns.get(userId);
4195 if (vpn != null) {
4196 return vpn.prepare(oldPackage, newPackage);
4197 } else {
4198 return false;
4199 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004200 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004201 }
4202
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004203 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004204 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4205 * This method is used by system-privileged apps.
4206 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4207 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4208 *
4209 * @param packageName The package for which authorization state should change.
4210 * @param userId User for whom {@code packageName} is installed.
4211 * @param authorized {@code true} if this app should be able to start a VPN connection without
4212 * explicit user approval, {@code false} if not.
4213 *
Jeff Davidson05542602014-08-11 14:07:27 -07004214 * @hide
4215 */
4216 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004217 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4218 enforceCrossUserPermission(userId);
4219
Hugo Benichi20035e02017-04-26 14:53:28 +09004220 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004221 Vpn vpn = mVpns.get(userId);
4222 if (vpn != null) {
4223 vpn.setPackageAuthorization(packageName, authorized);
4224 }
Jeff Davidson05542602014-08-11 14:07:27 -07004225 }
4226 }
4227
4228 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004229 * Configure a TUN interface and return its file descriptor. Parameters
4230 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004231 * and not available in ConnectivityManager. Permissions are checked in
4232 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004233 * @hide
4234 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004235 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004236 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004237 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004238 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004239 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004240 return mVpns.get(user).establish(config);
4241 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004242 }
4243
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004244 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004245 * Start legacy VPN, controlling native daemons as needed. Creates a
4246 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004247 */
4248 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004249 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004250 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004251 final LinkProperties egress = getActiveLinkProperties();
4252 if (egress == null) {
4253 throw new IllegalStateException("Missing active network connection");
4254 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004255 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004256 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004257 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4258 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004259 }
4260
4261 /**
4262 * Return the information of the ongoing legacy VPN. This method is used
4263 * by VpnSettings and not available in ConnectivityManager. Permissions
4264 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004265 */
4266 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004267 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4268 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004269
Hugo Benichi20035e02017-04-26 14:53:28 +09004270 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004271 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004272 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004273 }
4274
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004275 /**
Varun Anandd33cbc62019-02-07 14:13:13 -08004276 * Return the information of all ongoing VPNs.
4277 *
4278 * <p>This method is used to update NetworkStatsService.
4279 *
4280 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004281 */
Varun Anandd33cbc62019-02-07 14:13:13 -08004282 private VpnInfo[] getAllVpnInfo() {
4283 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004284 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004285 if (mLockdownEnabled) {
4286 return new VpnInfo[0];
4287 }
4288
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004289 List<VpnInfo> infoList = new ArrayList<>();
4290 for (int i = 0; i < mVpns.size(); i++) {
4291 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4292 if (info != null) {
4293 infoList.add(info);
4294 }
4295 }
4296 return infoList.toArray(new VpnInfo[infoList.size()]);
4297 }
4298 }
4299
4300 /**
4301 * @return VPN information for accounting, or null if we can't retrieve all required
4302 * information, e.g primary underlying iface.
4303 */
4304 @Nullable
4305 private VpnInfo createVpnInfo(Vpn vpn) {
4306 VpnInfo info = vpn.getVpnInfo();
4307 if (info == null) {
4308 return null;
4309 }
4310 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4311 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4312 // the underlyingNetworks list.
4313 if (underlyingNetworks == null) {
4314 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4315 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4316 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4317 }
4318 } else if (underlyingNetworks.length > 0) {
4319 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4320 if (linkProperties != null) {
4321 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4322 }
4323 }
4324 return info.primaryUnderlyingIface == null ? null : info;
4325 }
4326
4327 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004328 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4329 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004330 * Permissions are checked in Vpn class.
4331 * @hide
4332 */
4333 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004334 public VpnConfig getVpnConfig(int userId) {
4335 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004336 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004337 Vpn vpn = mVpns.get(userId);
4338 if (vpn != null) {
4339 return vpn.getVpnConfig();
4340 } else {
4341 return null;
4342 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004343 }
4344 }
4345
Chalard Jean6b65ec72018-05-18 22:02:56 +09004346 /**
4347 * Ask all VPN objects to recompute and update their capabilities.
4348 *
4349 * When underlying networks change, VPNs may have to update capabilities to reflect things
4350 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4351 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4352 * handler thread through their agent, this is asynchronous. When the capabilities objects
4353 * are computed they will be up-to-date as they are computed synchronously from here and
4354 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004355 */
4356 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004357 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004358 synchronized (mVpns) {
4359 for (int i = 0; i < mVpns.size(); i++) {
4360 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004361 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4362 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004363 }
4364 }
4365 }
4366
Varun Anand4fa80e82019-02-06 10:13:38 -08004367 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4368 ensureRunningOnConnectivityServiceThread();
4369 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4370 if (vpnNai == null || nc == null) {
4371 return;
4372 }
4373 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4374 }
4375
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004376 @Override
4377 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004378 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4379 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4380 return false;
4381 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004382
Hugo Benichi69744342017-11-27 10:57:16 +09004383 synchronized (mVpns) {
4384 // Tear down existing lockdown if profile was removed
4385 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4386 if (mLockdownEnabled) {
4387 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4388 if (profileTag == null) {
4389 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4390 return false;
4391 }
4392 String profileName = new String(profileTag);
4393 final VpnProfile profile = VpnProfile.decode(
4394 profileName, mKeyStore.get(Credentials.VPN + profileName));
4395 if (profile == null) {
4396 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4397 setLockdownTracker(null);
4398 return true;
4399 }
4400 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004401 Vpn vpn = mVpns.get(user);
4402 if (vpn == null) {
4403 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4404 return false;
4405 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004406 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004407 } else {
4408 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004409 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004410 }
4411
4412 return true;
4413 }
4414
4415 /**
4416 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4417 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4418 */
Hugo Benichi69744342017-11-27 10:57:16 +09004419 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004420 private void setLockdownTracker(LockdownVpnTracker tracker) {
4421 // Shutdown any existing tracker
4422 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004423 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4424 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004425 mLockdownTracker = null;
4426 if (existing != null) {
4427 existing.shutdown();
4428 }
4429
Robin Leec3736bc2017-03-10 16:19:54 +00004430 if (tracker != null) {
4431 mLockdownTracker = tracker;
4432 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004433 }
4434 }
4435
Hugo Benichi69744342017-11-27 10:57:16 +09004436 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004437 private void throwIfLockdownEnabled() {
4438 if (mLockdownEnabled) {
4439 throw new IllegalStateException("Unavailable in lockdown mode");
4440 }
4441 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004442
Robin Lee244ce8e2016-01-05 18:03:46 +00004443 /**
Robin Lee17e61832016-05-09 13:46:28 +01004444 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4445 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004446 *
Robin Lee17e61832016-05-09 13:46:28 +01004447 * @return {@code true} if the service was started, the service was already connected, or there
4448 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004449 */
Robin Lee17e61832016-05-09 13:46:28 +01004450 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004451 synchronized (mVpns) {
4452 Vpn vpn = mVpns.get(userId);
4453 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004454 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004455 // exists already.
4456 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4457 return false;
4458 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004459
Robin Lee812800c2016-05-13 15:38:08 +01004460 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004461 }
4462 }
4463
4464 @Override
Charles He36738632017-05-15 17:07:18 +01004465 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4466 enforceSettingsPermission();
4467 enforceCrossUserPermission(userId);
4468
4469 synchronized (mVpns) {
4470 Vpn vpn = mVpns.get(userId);
4471 if (vpn == null) {
4472 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4473 return false;
4474 }
4475 return vpn.isAlwaysOnPackageSupported(packageName);
4476 }
4477 }
4478
4479 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004480 public boolean setAlwaysOnVpnPackage(
4481 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4482 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004483 enforceCrossUserPermission(userId);
4484
Robin Lee244ce8e2016-01-05 18:03:46 +00004485 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004486 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4487 if (LockdownVpnTracker.isEnabled()) {
4488 return false;
4489 }
4490
Robin Lee244ce8e2016-01-05 18:03:46 +00004491 Vpn vpn = mVpns.get(userId);
4492 if (vpn == null) {
4493 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4494 return false;
4495 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004496 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004497 return false;
4498 }
Robin Lee17e61832016-05-09 13:46:28 +01004499 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004500 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004501 return false;
4502 }
4503 }
4504 return true;
4505 }
4506
4507 @Override
4508 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004509 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004510 enforceCrossUserPermission(userId);
4511
4512 synchronized (mVpns) {
4513 Vpn vpn = mVpns.get(userId);
4514 if (vpn == null) {
4515 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4516 return null;
4517 }
4518 return vpn.getAlwaysOnPackage();
4519 }
4520 }
4521
Wink Savilleab9321d2013-06-29 21:10:57 -07004522 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004523 public boolean isVpnLockdownEnabled(int userId) {
4524 enforceControlAlwaysOnVpnPermission();
4525 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 false;
4532 }
4533 return vpn.getLockdown();
4534 }
4535 }
4536
4537 @Override
4538 public List<String> getVpnLockdownWhitelist(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 null;
4547 }
4548 return vpn.getLockdownWhitelist();
4549 }
4550 }
4551
4552 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004553 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004554 // TODO: Remove? Any reason to trigger a provisioning check?
4555 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004556 }
4557
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004558 /** Location to an updatable file listing carrier provisioning urls.
4559 * An example:
4560 *
4561 * <?xml version="1.0" encoding="utf-8"?>
4562 * <provisioningUrls>
4563 * <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 -07004564 * </provisioningUrls>
4565 */
4566 private static final String PROVISIONING_URL_PATH =
4567 "/data/misc/radio/provisioning_urls.xml";
4568 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004569
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004570 /** XML tag for root element. */
4571 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4572 /** XML tag for individual url */
4573 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004574 /** XML attribute for mcc */
4575 private static final String ATTR_MCC = "mcc";
4576 /** XML attribute for mnc */
4577 private static final String ATTR_MNC = "mnc";
4578
Paul Jensen434dde82015-06-11 09:43:30 -04004579 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004580 FileReader fileReader = null;
4581 XmlPullParser parser = null;
4582 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004583
4584 try {
4585 fileReader = new FileReader(mProvisioningUrlFile);
4586 parser = Xml.newPullParser();
4587 parser.setInput(fileReader);
4588 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4589
4590 while (true) {
4591 XmlUtils.nextElement(parser);
4592
4593 String element = parser.getName();
4594 if (element == null) break;
4595
Paul Jensen434dde82015-06-11 09:43:30 -04004596 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004597 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4598 try {
4599 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4600 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4601 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4602 parser.next();
4603 if (parser.getEventType() == XmlPullParser.TEXT) {
4604 return parser.getText();
4605 }
4606 }
4607 }
4608 } catch (NumberFormatException e) {
4609 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4610 }
4611 }
4612 }
4613 return null;
4614 } catch (FileNotFoundException e) {
4615 loge("Carrier Provisioning Urls file not found");
4616 } catch (XmlPullParserException e) {
4617 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4618 } catch (IOException e) {
4619 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4620 } finally {
4621 if (fileReader != null) {
4622 try {
4623 fileReader.close();
4624 } catch (IOException e) {}
4625 }
4626 }
4627 return null;
4628 }
4629
Wink Saville42d4f082013-07-20 20:31:59 -07004630 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004631 public String getMobileProvisioningUrl() {
4632 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004633 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004634 if (TextUtils.isEmpty(url)) {
4635 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004636 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004637 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004638 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004639 }
Wink Saville8cf35602013-07-10 23:00:07 -07004640 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004641 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004642 String phoneNumber = mTelephonyManager.getLine1Number();
4643 if (TextUtils.isEmpty(phoneNumber)) {
4644 phoneNumber = "0000000000";
4645 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004646 url = String.format(url,
4647 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4648 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004649 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004650 }
4651
Wink Savilleab9321d2013-06-29 21:10:57 -07004652 return url;
4653 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004654
Wink Saville948282b2013-08-29 08:55:16 -07004655 @Override
4656 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004657 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004658 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004659 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4660 return;
4661 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004662 final long ident = Binder.clearCallingIdentity();
4663 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004664 // Concatenate the range of types onto the range of NetIDs.
4665 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4666 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004667 } finally {
4668 Binder.restoreCallingIdentity(ident);
4669 }
Wink Saville948282b2013-08-29 08:55:16 -07004670 }
Wink Saville7788c612013-08-29 14:57:08 -07004671
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004672 @Override
4673 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004674 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004675 final long ident = Binder.clearCallingIdentity();
4676 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004677 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004678 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004679 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4680 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004681 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004682 } finally {
4683 Binder.restoreCallingIdentity(ident);
4684 }
4685 }
4686
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004687 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004688 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004689 Vpn userVpn = mVpns.get(userId);
4690 if (userVpn != null) {
4691 loge("Starting user already has a VPN");
4692 return;
4693 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004694 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004695 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004696 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4697 updateLockdownVpn();
4698 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004699 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004700 }
4701
4702 private void onUserStop(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) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004706 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004707 return;
4708 }
Robin Lee17e61832016-05-09 13:46:28 +01004709 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004710 mVpns.delete(userId);
4711 }
4712 }
4713
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004714 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004715 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004716 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004717 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004718 final int vpnsSize = mVpns.size();
4719 for (int i = 0; i < vpnsSize; i++) {
4720 Vpn vpn = mVpns.valueAt(i);
4721 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004722 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4723 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004724 }
4725 }
4726 }
4727
4728 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004729 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004730 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004731 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004732 final int vpnsSize = mVpns.size();
4733 for (int i = 0; i < vpnsSize; i++) {
4734 Vpn vpn = mVpns.valueAt(i);
4735 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004736 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4737 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004738 }
4739 }
4740 }
4741
junyulai2454b692018-11-01 17:16:31 +08004742 private void onPackageAdded(String packageName, int uid) {
4743 if (TextUtils.isEmpty(packageName) || uid < 0) {
4744 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4745 return;
4746 }
4747 mPermissionMonitor.onPackageAdded(packageName, uid);
4748 }
4749
junyulaiefb04d32018-11-12 22:39:30 +08004750 private void onPackageReplaced(String packageName, int uid) {
4751 if (TextUtils.isEmpty(packageName) || uid < 0) {
4752 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4753 return;
4754 }
4755 final int userId = UserHandle.getUserId(uid);
4756 synchronized (mVpns) {
4757 final Vpn vpn = mVpns.get(userId);
4758 if (vpn == null) {
4759 return;
4760 }
4761 // Legacy always-on VPN won't be affected since the package name is not set.
4762 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4763 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4764 + userId);
4765 vpn.startAlwaysOnVpn();
4766 }
4767 }
4768 }
4769
4770 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004771 if (TextUtils.isEmpty(packageName) || uid < 0) {
4772 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4773 return;
4774 }
4775 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004776
4777 final int userId = UserHandle.getUserId(uid);
4778 synchronized (mVpns) {
4779 final Vpn vpn = mVpns.get(userId);
4780 if (vpn == null) {
4781 return;
4782 }
4783 // Legacy always-on VPN won't be affected since the package name is not set.
4784 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4785 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4786 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004787 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004788 }
4789 }
junyulai2454b692018-11-01 17:16:31 +08004790 }
4791
Robin Lee89e7a692016-02-29 14:38:17 +00004792 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004793 synchronized (mVpns) {
4794 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4795 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4796 updateLockdownVpn();
4797 } else {
4798 startAlwaysOnVpn(userId);
4799 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004800 }
4801 }
4802
junyulai2454b692018-11-01 17:16:31 +08004803 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004804 @Override
4805 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004806 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004807 final String action = intent.getAction();
4808 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004809 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4810 final Uri packageData = intent.getData();
4811 final String packageName =
4812 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004813 if (userId == UserHandle.USER_NULL) return;
4814
Robin Lee323f29d2016-05-04 16:38:06 +01004815 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004816 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004817 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004818 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004819 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4820 onUserAdded(userId);
4821 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4822 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004823 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4824 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004825 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4826 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004827 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4828 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004829 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004830 final boolean isReplacing = intent.getBooleanExtra(
4831 Intent.EXTRA_REPLACING, false);
4832 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004833 }
4834 }
4835 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004836
Robin Lee95204e02017-01-27 11:59:22 +00004837 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4838 @Override
4839 public void onReceive(Context context, Intent intent) {
4840 // Try creating lockdown tracker, since user present usually means
4841 // unlocked keystore.
4842 updateLockdownVpn();
4843 mContext.unregisterReceiver(this);
4844 }
4845 };
4846
Chalard Jean4133a122018-06-04 13:33:12 +09004847 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4848 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004849
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004850 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4851 // Map from UID to number of NetworkRequests that UID has filed.
4852 @GuardedBy("mUidToNetworkRequestCount")
4853 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4854
Robert Greenwalta67be032014-05-16 15:49:14 -07004855 private static class NetworkFactoryInfo {
4856 public final String name;
4857 public final Messenger messenger;
4858 public final AsyncChannel asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004859 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004860
Chalard Jean05ab6812018-05-02 21:14:54 +09004861 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4862 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004863 this.name = name;
4864 this.messenger = messenger;
4865 this.asyncChannel = asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004866 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004867 }
4868 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004869
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004870 private void ensureNetworkRequestHasType(NetworkRequest request) {
4871 if (request.type == NetworkRequest.Type.NONE) {
4872 throw new IllegalArgumentException(
4873 "All NetworkRequests in ConnectivityService must have a type");
4874 }
4875 }
4876
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004877 /**
4878 * Tracks info about the requester.
4879 * Also used to notice when the calling process dies so we can self-expire
4880 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004881 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004882 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004883 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004884 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004885 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004886 final int mPid;
4887 final int mUid;
4888 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004889
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004890 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004891 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004892 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004893 mPendingIntent = pi;
4894 messenger = null;
4895 mBinder = null;
4896 mPid = getCallingPid();
4897 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004898 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004899 }
4900
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004901 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004902 super();
4903 messenger = m;
4904 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004905 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004906 mBinder = binder;
4907 mPid = getCallingPid();
4908 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004909 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004910 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004911
4912 try {
4913 mBinder.linkToDeath(this, 0);
4914 } catch (RemoteException e) {
4915 binderDied();
4916 }
4917 }
4918
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004919 private void enforceRequestCountLimit() {
4920 synchronized (mUidToNetworkRequestCount) {
4921 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4922 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004923 throw new ServiceSpecificException(
4924 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004925 }
4926 mUidToNetworkRequestCount.put(mUid, networkRequests);
4927 }
4928 }
4929
Robert Greenwalt9258c642014-03-26 16:47:06 -07004930 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004931 if (mBinder != null) {
4932 mBinder.unlinkToDeath(this, 0);
4933 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004934 }
4935
4936 public void binderDied() {
4937 log("ConnectivityService NetworkRequestInfo binderDied(" +
4938 request + ", " + mBinder + ")");
4939 releaseNetworkRequest(request);
4940 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004941
4942 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004943 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004944 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004945 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004946 }
4947
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004948 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4949 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4950 if (badCapability != null) {
4951 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004952 }
4953 }
4954
Chalard Jeanb03a6222018-04-11 21:09:10 +09004955 // This checks that the passed capabilities either do not request a specific SSID, or the
4956 // calling app has permission to do so.
4957 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4958 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004959 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004960 throw new SecurityException("Insufficient permissions to request a specific SSID");
4961 }
4962 }
4963
Erik Kline9d598e12015-07-13 16:37:51 +09004964 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004965 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004966 synchronized (nai) {
4967 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4968 if (nri.request.networkCapabilities.hasSignalStrength() &&
4969 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4970 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4971 }
4972 }
4973 }
Chalard Jean4133a122018-06-04 13:33:12 +09004974 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004975 }
4976
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004977 private void updateSignalStrengthThresholds(
4978 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4979 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004980 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004981 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4982
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004983 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004984 String detail;
4985 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4986 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4987 } else {
4988 detail = reason;
4989 }
4990 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4991 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4992 }
4993
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004994 nai.asyncChannel.sendMessage(
4995 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004996 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004997 }
4998
Etan Cohen859748f2017-04-03 17:42:34 -07004999 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5000 if (nc == null) {
5001 return;
5002 }
5003 NetworkSpecifier ns = nc.getNetworkSpecifier();
5004 if (ns == null) {
5005 return;
5006 }
5007 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5008 ns.assertValidFromUid(Binder.getCallingUid());
5009 }
5010
Robert Greenwalt9258c642014-03-26 16:47:06 -07005011 @Override
5012 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005013 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005014 final NetworkRequest.Type type = (networkCapabilities == null)
5015 ? NetworkRequest.Type.TRACK_DEFAULT
5016 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005017 // If the requested networkCapabilities is null, take them instead from
5018 // the default network request. This allows callers to keep track of
5019 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005020 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005021 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005022 enforceAccessPermission();
5023 } else {
5024 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5025 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005026 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5027 // of the app when the request is filed, but we never change the request if the app
5028 // changes network state. http://b/29964605
5029 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005030 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005031 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005032 ensureSufficientPermissionsForRequest(networkCapabilities,
5033 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005034 // Set the UID range for this request to the single UID of the requester, or to an empty
5035 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005036 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5037 // are no visible methods to set the UIDs, an app could use reflection to try and get
5038 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005039 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005040
Etan Cohenba07c8c2017-02-05 10:42:27 -08005041 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005042 throw new IllegalArgumentException("Bad timeout specified");
5043 }
Etan Cohen859748f2017-04-03 17:42:34 -07005044 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005045
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005046 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005047 nextNetworkRequestId(), type);
5048 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005049 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005050
5051 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005052 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005053 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005054 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005055 }
5056 return networkRequest;
5057 }
5058
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005059 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005060 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005061 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005062 } else {
5063 enforceChangePermission();
5064 }
5065 }
5066
fenglub15e72b2015-03-20 11:29:56 -07005067 @Override
fengludb571472015-04-21 17:12:05 -07005068 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005069 enforceAccessPermission();
5070 NetworkAgentInfo nai = null;
5071 if (network == null) {
5072 return false;
5073 }
5074 synchronized (mNetworkForNetId) {
5075 nai = mNetworkForNetId.get(network.netId);
5076 }
5077 if (nai != null) {
5078 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005079 synchronized (mBandwidthRequests) {
5080 final int uid = Binder.getCallingUid();
5081 Integer uidReqs = mBandwidthRequests.get(uid);
5082 if (uidReqs == null) {
5083 uidReqs = new Integer(0);
5084 }
5085 mBandwidthRequests.put(uid, ++uidReqs);
5086 }
fenglub15e72b2015-03-20 11:29:56 -07005087 return true;
5088 }
5089 return false;
5090 }
5091
Felipe Lemeee27cab2016-06-20 16:36:29 -07005092 private boolean isSystem(int uid) {
5093 return uid < Process.FIRST_APPLICATION_UID;
5094 }
fenglub15e72b2015-03-20 11:29:56 -07005095
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005096 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005097 final int uid = Binder.getCallingUid();
5098 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005099 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005100 return;
5101 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005102 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5103 // Policy already enforced.
5104 return;
5105 }
5106 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5107 // If UID is restricted, don't allow them to bring up metered APNs.
5108 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005109 }
5110 }
5111
Robert Greenwalt9258c642014-03-26 16:47:06 -07005112 @Override
5113 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5114 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005115 checkNotNull(operation, "PendingIntent cannot be null.");
5116 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5117 enforceNetworkRequestPermissions(networkCapabilities);
5118 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005119 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005120 ensureSufficientPermissionsForRequest(networkCapabilities,
5121 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005122 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005123 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005124
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005125 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005126 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5127 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005128 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005129 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5130 nri));
5131 return networkRequest;
5132 }
5133
Jeremy Joslin79294842014-12-03 17:15:28 -08005134 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5135 mHandler.sendMessageDelayed(
5136 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5137 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5138 }
5139
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005140 @Override
5141 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005142 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005143 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5144 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005145 }
5146
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005147 // In order to implement the compatibility measure for pre-M apps that call
5148 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5149 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5150 // This ensures it has permission to do so.
5151 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5152 if (nc == null) {
5153 return false;
5154 }
5155 int[] transportTypes = nc.getTransportTypes();
5156 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5157 return false;
5158 }
5159 try {
5160 mContext.enforceCallingOrSelfPermission(
5161 android.Manifest.permission.ACCESS_WIFI_STATE,
5162 "ConnectivityService");
5163 } catch (SecurityException e) {
5164 return false;
5165 }
5166 return true;
5167 }
5168
Robert Greenwalt9258c642014-03-26 16:47:06 -07005169 @Override
5170 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5171 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005172 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5173 enforceAccessPermission();
5174 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005175
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005176 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005177 ensureSufficientPermissionsForRequest(networkCapabilities,
5178 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005179 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005180 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5181 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5182 // onLost and onAvailable callbacks when networks move in and out of the background.
5183 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5184 // can't request networks.
5185 restrictBackgroundRequestForCaller(nc);
5186 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005187
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005188 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005189 NetworkRequest.Type.LISTEN);
5190 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005191 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005192
5193 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5194 return networkRequest;
5195 }
5196
5197 @Override
5198 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5199 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005200 checkNotNull(operation, "PendingIntent cannot be null.");
5201 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5202 enforceAccessPermission();
5203 }
Etan Cohen859748f2017-04-03 17:42:34 -07005204 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005205 ensureSufficientPermissionsForRequest(networkCapabilities,
5206 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005207
Chalard Jeandda156a2018-01-10 21:19:32 +09005208 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005209 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005210
5211 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005212 NetworkRequest.Type.LISTEN);
5213 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005214 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005215
5216 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005217 }
5218
Erik Klineacdd6392016-07-07 16:50:58 +09005219 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005220 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005221 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005222 mHandler.sendMessage(mHandler.obtainMessage(
5223 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005224 }
5225
5226 @Override
Chalard Jean05ab6812018-05-02 21:14:54 +09005227 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005228 enforceConnectivityInternalPermission();
Chalard Jean05ab6812018-05-02 21:14:54 +09005229 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5230 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005231 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean05ab6812018-05-02 21:14:54 +09005232 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005233 }
5234
Robert Greenwalta67be032014-05-16 15:49:14 -07005235 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005236 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005237 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5238 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5239 }
5240
5241 @Override
5242 public void unregisterNetworkFactory(Messenger messenger) {
5243 enforceConnectivityInternalPermission();
5244 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5245 }
5246
5247 private void handleUnregisterNetworkFactory(Messenger messenger) {
5248 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5249 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005250 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005251 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005252 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005253 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005254 }
5255
Robert Greenwalt7b816022014-04-18 15:25:25 -07005256 /**
5257 * NetworkAgentInfo supporting a request by requestId.
5258 * These have already been vetted (their Capabilities satisfy the request)
5259 * and the are the highest scored network available.
5260 * the are keyed off the Requests requestId.
5261 */
Hugo Benichicd952782017-09-20 11:20:14 +09005262 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5263 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005264 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005265
Paul Jensen31a94f42015-02-13 14:18:39 -05005266 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5267 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005268 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005269 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5270 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5271 // there may not be a strict 1:1 correlation between the two.
5272 @GuardedBy("mNetworkForNetId")
5273 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005274
Robert Greenwalt7b816022014-04-18 15:25:25 -07005275 // NetworkAgentInfo keyed off its connecting messenger
5276 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005277 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005278 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005279
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005280 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005281 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005282
Paul Jensen2c311d62014-11-17 12:34:51 -05005283 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005284 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005285
Erik Klineda4bfa82015-04-30 12:58:40 +09005286 // Request used to optionally keep mobile data active even when higher
5287 // priority networks like Wi-Fi are active.
5288 private final NetworkRequest mDefaultMobileDataRequest;
5289
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005290 // Request used to optionally keep wifi data active even when higher
5291 // priority networks like ethernet are active.
5292 private final NetworkRequest mDefaultWifiRequest;
5293
Hugo Benichicd952782017-09-20 11:20:14 +09005294 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5295 synchronized (mNetworkForRequestId) {
5296 return mNetworkForRequestId.get(requestId);
5297 }
5298 }
5299
5300 private void clearNetworkForRequest(int requestId) {
5301 synchronized (mNetworkForRequestId) {
5302 mNetworkForRequestId.remove(requestId);
5303 }
5304 }
5305
5306 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5307 synchronized (mNetworkForRequestId) {
5308 mNetworkForRequestId.put(requestId, nai);
5309 }
5310 }
5311
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005312 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005313 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005314 }
5315
Varun Anand4fa80e82019-02-06 10:13:38 -08005316 @Nullable
5317 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5318 return nai != null ? nai.network : null;
5319 }
5320
5321 private void ensureRunningOnConnectivityServiceThread() {
5322 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5323 throw new IllegalStateException(
5324 "Not running on ConnectivityService thread: "
5325 + Thread.currentThread().getName());
5326 }
5327 }
5328
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005329 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005330 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005331 }
5332
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005333 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5334 return nri.request.requestId == mDefaultRequest.requestId;
5335 }
5336
Chalard Jean05ab6812018-05-02 21:14:54 +09005337 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5338 // changes that would conflict throughout the automerger graph. Having this method temporarily
5339 // helps with the process of going through with all these dependent changes across the entire
5340 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005341 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005342 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005343 int currentScore, NetworkMisc networkMisc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005344 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5345 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5346 }
5347
5348 /**
5349 * Register a new agent with ConnectivityService to handle a network.
5350 *
5351 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5352 * @param networkInfo the initial info associated with this network. It can be updated later :
5353 * see {@link #updateNetworkInfo}.
5354 * @param linkProperties the initial link properties of this network. They can be updated
5355 * later : see {@link #updateLinkProperties}.
5356 * @param networkCapabilities the initial capabilites of this network. They can be updated
5357 * later : see {@link #updateNetworkCapabilities}.
5358 * @param currentScore the initial score of the network. See
5359 * {@link NetworkAgentInfo#getCurrentScore}.
5360 * @param networkMisc metadata about the network. This is never updated.
5361 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5362 */
5363 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5364 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5365 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005366 enforceConnectivityInternalPermission();
5367
Rubin Xu1bb5c082017-09-05 18:40:49 +01005368 LinkProperties lp = new LinkProperties(linkProperties);
5369 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005370 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5371 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005372 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005373 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005374 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean05ab6812018-05-02 21:14:54 +09005375 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5376 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005377 // Make sure the network capabilities reflect what the agent info says.
5378 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005379 final String extraInfo = networkInfo.getExtraInfo();
5380 final String name = TextUtils.isEmpty(extraInfo)
5381 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005382 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005383 final long token = Binder.clearCallingIdentity();
5384 try {
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005385 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005386 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005387 } finally {
5388 Binder.restoreCallingIdentity(token);
5389 }
5390 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5391 // If the network disconnects or sends any other event before that, messages are deferred by
5392 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5393 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005394 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005395 }
5396
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005397 @VisibleForTesting
5398 protected NetworkStackClient getNetworkStack() {
5399 return NetworkStackClient.getInstance();
5400 }
5401
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005402 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5403 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005404 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005405 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005406 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005407 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005408 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005409 synchronized (this) {
5410 if (mSystemReady) {
5411 try {
5412 networkMonitor.notifySystemReady();
5413 } catch (RemoteException e) {
5414 e.rethrowFromSystemServer();
5415 }
5416 }
5417 }
5418
5419 try {
5420 networkMonitor.start();
5421 } catch (RemoteException e) {
5422 e.rethrowFromSystemServer();
5423 }
Erik Klinee5dac902018-03-04 21:01:01 +09005424 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5425 NetworkInfo networkInfo = nai.networkInfo;
5426 nai.networkInfo = null;
5427 updateNetworkInfo(nai, networkInfo);
5428 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005429 }
5430
lucaslin25a4ec32018-11-28 12:51:55 +08005431 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5432 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005433 int netId = networkAgent.network.netId;
5434
Lorenzo Colittidf595632019-01-08 14:43:37 +09005435 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5436 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5437 // are accurate.
5438 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005439
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005440 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005441 updateMtu(newLp, oldLp);
5442 // TODO - figure out what to do for clat
5443// for (LinkProperties lp : newLp.getStackedLinks()) {
5444// updateMtu(lp, null);
5445// }
lucaslin041a1af2018-11-28 19:27:52 +08005446 if (isDefaultNetwork(networkAgent)) {
5447 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5448 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005449
Erik Kline94887872016-04-05 13:30:49 +09005450 updateRoutes(newLp, oldLp, netId);
5451 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005452 // Make sure LinkProperties represents the latest private DNS status.
5453 // This does not need to be done before updateDnses because the
5454 // LinkProperties are not the source of the private DNS configuration.
5455 // updateDnses will fetch the private DNS configuration from DnsManager.
5456 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005457
Paul Jensene0bef712014-12-10 15:12:18 -05005458 if (isDefaultNetwork(networkAgent)) {
5459 handleApplyDefaultProxy(newLp.getHttpProxy());
5460 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005461 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005462 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005463 // TODO - move this check to cover the whole function
5464 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005465 synchronized (networkAgent) {
5466 networkAgent.linkProperties = newLp;
5467 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005468 // Start or stop DNS64 detection and 464xlat according to network state.
5469 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005470 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005471 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005472 try {
5473 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5474 } catch (RemoteException e) {
5475 e.rethrowFromSystemServer();
5476 }
lucaslin25a4ec32018-11-28 12:51:55 +08005477 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5478 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005479 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005480
5481 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005482 }
5483
Joel Scherpelz668370b2017-06-08 15:35:21 +09005484 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005485 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005486 // marks on unsupported interfaces is harmless.
5487 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5488 return;
5489 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005490
Joel Scherpelz668370b2017-06-08 15:35:21 +09005491 int mark = mContext.getResources().getInteger(
5492 com.android.internal.R.integer.config_networkWakeupPacketMark);
5493 int mask = mContext.getResources().getInteger(
5494 com.android.internal.R.integer.config_networkWakeupPacketMask);
5495
5496 // Mask/mark of zero will not detect anything interesting.
5497 // Don't install rules unless both values are nonzero.
5498 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005499 return;
5500 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005501
5502 final String prefix = "iface:" + iface;
5503 try {
5504 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005505 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005506 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005507 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005508 }
5509 } catch (Exception e) {
5510 loge("Exception modifying wakeup packet monitoring: " + e);
5511 }
5512
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005513 }
5514
5515 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5516 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005517 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005518 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5519 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005520 for (String iface : interfaceDiff.added) {
5521 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005522 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005523 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005524 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005525 } catch (Exception e) {
5526 loge("Exception adding interface: " + e);
5527 }
5528 }
5529 for (String iface : interfaceDiff.removed) {
5530 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005531 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005532 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005533 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005534 } catch (Exception e) {
5535 loge("Exception removing interface: " + e);
5536 }
5537 }
5538 }
5539
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005540 /**
5541 * Have netd update routes from oldLp to newLp.
5542 * @return true if routes changed between oldLp and newLp
5543 */
5544 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005545 // Compare the route diff to determine which routes should be added and removed.
5546 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5547 oldLp != null ? oldLp.getAllRoutes() : null,
5548 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005549
5550 // add routes before removing old in case it helps with continuous connectivity
5551
Chalard Jean4d660112018-06-04 16:52:49 +09005552 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005553 for (RouteInfo route : routeDiff.added) {
5554 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005555 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005556 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005557 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005558 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005559 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5560 loge("Exception in addRoute for non-gateway: " + e);
5561 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005562 }
5563 }
5564 for (RouteInfo route : routeDiff.added) {
5565 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005566 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005567 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005568 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005569 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005570 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5571 loge("Exception in addRoute for gateway: " + e);
5572 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005573 }
5574 }
5575
5576 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005577 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005578 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005579 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005580 } catch (Exception e) {
5581 loge("Exception in removeRoute: " + e);
5582 }
5583 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005584 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005585 }
Erik Kline41368502015-06-17 13:19:54 +09005586
Erik Kline94887872016-04-05 13:30:49 +09005587 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5588 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5589 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005590 }
Erik Kline94887872016-04-05 13:30:49 +09005591
Erik Kline1742fe12017-12-13 19:40:49 +09005592 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5593 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5594
Erik Klinea24d4592018-01-11 21:07:29 +09005595 if (DBG) {
5596 final Collection<InetAddress> dnses = newLp.getDnsServers();
5597 log("Setting DNS servers for network " + netId + " to " + dnses);
5598 }
Erik Kline94887872016-04-05 13:30:49 +09005599 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005600 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005601 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005602 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005603 }
Erik Kline4edba012017-04-07 15:29:29 +09005604 }
5605
Luke Huang8a462ec2018-08-24 20:33:16 +08005606 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005607 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005608 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005609 }
5610 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005611 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005612 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005613 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005614 }
5615
Paul Jensen3d194ea2015-06-16 14:27:36 -04005616 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005617 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5618 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5619 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005620 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005621 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005622 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005623 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5624 // causing a connect/teardown loop.
5625 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5626 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005627 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005628 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005629 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5630 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005631 // does not cause any request (that is not a listen) currently matching that agent to
5632 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005633 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005634 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005635 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005636 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005637 }
5638
Paul Jensen3d194ea2015-06-16 14:27:36 -04005639 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005640 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005641 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005642 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005643 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005644 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005645 }
Paul Jensene0988542015-06-25 15:30:08 -04005646 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005647 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005648 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005649 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005650 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005651 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005652 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005653 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005654 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005655 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005656 if (nai.isSuspended()) {
5657 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5658 } else {
5659 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5660 }
lucasline252a742019-03-12 13:08:03 +08005661 if (nai.partialConnectivity) {
5662 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5663 } else {
5664 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5665 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005666
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005667 return newNc;
5668 }
5669
5670 /**
5671 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5672 *
5673 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5674 * capabilities we manage and store in {@code nai}, such as validated status and captive
5675 * portal status)
5676 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5677 * potentially triggers rematches.
5678 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5679 * change.)
5680 *
5681 * @param oldScore score of the network before any of the changes that prompted us
5682 * to call this function.
5683 * @param nai the network having its capabilities updated.
5684 * @param nc the new network capabilities.
5685 */
5686 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5687 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5688
5689 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005690
Luke Huang8a462ec2018-08-24 20:33:16 +08005691 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5692 final int newPermission = getNetworkPermission(newNc);
5693 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005694 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005695 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005696 } catch (RemoteException e) {
5697 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005698 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005699 }
5700
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005701 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005702 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005703 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005704 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005705 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005706
Chalard Jeanf213ca12018-01-16 18:43:05 +09005707 updateUids(nai, prevNc, newNc);
5708
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005709 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005710 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5711 // the change we're processing can't affect any requests, it can only affect the listens
5712 // on this network. We might have been called by rematchNetworkAndRequests when a
5713 // network changed foreground state.
5714 processListenRequests(nai, true);
5715 } else {
5716 // If the requestable capabilities have changed or the score changed, we can't have been
5717 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005718 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005719 try {
5720 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5721 } catch (RemoteException e) {
5722 e.rethrowFromSystemServer();
5723 }
Paul Jensene0988542015-06-25 15:30:08 -04005724 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005725 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005726
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005727 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005728 final boolean oldMetered = prevNc.isMetered();
5729 final boolean newMetered = newNc.isMetered();
5730 final boolean meteredChanged = oldMetered != newMetered;
5731
5732 if (meteredChanged) {
5733 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5734 mRestrictBackground);
5735 }
5736
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005737 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005738 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005739
5740 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005741 if (meteredChanged || roamingChanged) {
5742 notifyIfacesChangedForNetworkStats();
5743 }
5744 }
5745
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005746 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005747 // Tell VPNs about updated capabilities, since they may need to
5748 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005749 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005750 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005751 }
5752
Chalard Jeanf213ca12018-01-16 18:43:05 +09005753 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5754 NetworkCapabilities newNc) {
5755 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5756 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5757 if (null == prevRanges) prevRanges = new ArraySet<>();
5758 if (null == newRanges) newRanges = new ArraySet<>();
5759 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5760
5761 prevRanges.removeAll(newRanges);
5762 newRanges.removeAll(prevRangesCopy);
5763
5764 try {
5765 if (!newRanges.isEmpty()) {
5766 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5767 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005768 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005769 }
5770 if (!prevRanges.isEmpty()) {
5771 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5772 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005773 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005774 }
5775 } catch (Exception e) {
5776 // Never crash!
5777 loge("Exception in updateUids: " + e);
5778 }
5779 }
5780
Hugo Benichief502882017-09-01 01:23:32 +00005781 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005782 ensureRunningOnConnectivityServiceThread();
5783
Erik Kline736353a2018-03-21 07:18:33 -07005784 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005785 // Ignore updates for disconnected networks
5786 return;
5787 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005788 // newLp is already a defensive copy.
5789 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005790 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005791 log("Update of LinkProperties for " + nai.name() +
5792 "; created=" + nai.created +
5793 "; everConnected=" + nai.everConnected);
5794 }
lucaslin25a4ec32018-11-28 12:51:55 +08005795 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005796 }
5797
Paul Jensenc8b9a742014-09-30 15:37:41 -04005798 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005799 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5800 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005801 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005802 if (nr.isListen()) continue;
Chalard Jean05ab6812018-05-02 21:14:54 +09005803 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005804 }
5805 }
5806
Chalard Jean05ab6812018-05-02 21:14:54 +09005807 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5808 int score = 0;
5809 int serial = 0;
5810 if (nai != null) {
5811 score = nai.getCurrentScore();
5812 serial = nai.factorySerialNumber;
5813 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005814 if (VDBG || DDBG){
5815 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5816 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005817 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005818 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5819 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005820 }
5821 }
5822
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005823 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5824 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005825 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005826 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005827 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5828 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005829 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005830 sendIntent(nri.mPendingIntent, intent);
5831 }
5832 // else not handled
5833 }
5834
5835 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5836 mPendingIntentWakeLock.acquire();
5837 try {
5838 if (DBG) log("Sending " + pendingIntent);
5839 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5840 } catch (PendingIntent.CanceledException e) {
5841 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5842 mPendingIntentWakeLock.release();
5843 releasePendingNetworkRequest(pendingIntent);
5844 }
5845 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5846 }
5847
5848 @Override
5849 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5850 String resultData, Bundle resultExtras) {
5851 if (DBG) log("Finished sending " + pendingIntent);
5852 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005853 // Release with a delay so the receiving client has an opportunity to put in its
5854 // own request.
5855 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005856 }
5857
Chalard Jeanf19db372018-01-26 19:24:40 +09005858 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005859 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005860 if (nri.messenger == null) {
5861 return; // Default request has no msgr
5862 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005863 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005864 // TODO: check if defensive copies of data is needed.
5865 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005866 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005867 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5868 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005869 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005870 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005871 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005872 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5873 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005874 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005875 // For this notification, arg1 contains the blocked status.
5876 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005877 break;
5878 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005879 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005880 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005881 break;
5882 }
5883 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005884 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005885 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005886 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005887 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005888 break;
5889 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005890 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005891 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005892 break;
5893 }
junyulai05986c62018-08-07 19:50:45 +08005894 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005895 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005896 msg.arg1 = arg1;
5897 break;
5898 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005899 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005900 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005901 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005902 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005903 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005904 String notification = ConnectivityManager.getCallbackName(notificationType);
5905 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005906 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005907 nri.messenger.send(msg);
5908 } catch (RemoteException e) {
5909 // may occur naturally in the race of binder death.
5910 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5911 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005912 }
5913
Hugo Benichidba33db2017-03-23 22:40:44 +09005914 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5915 bundle.putParcelable(t.getClass().getSimpleName(), t);
5916 }
5917
Paul Jensenc8b9a742014-09-30 15:37:41 -04005918 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005919 if (nai.numRequestNetworkRequests() != 0) {
5920 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5921 NetworkRequest nr = nai.requestAt(i);
5922 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005923 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005924 loge("Dead network still had at least " + nr);
5925 break;
5926 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005927 }
5928 nai.asyncChannel.disconnect();
5929 }
5930
Robert Greenwalt7b816022014-04-18 15:25:25 -07005931 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5932 if (oldNetwork == null) {
5933 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5934 return;
5935 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005936 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005937
5938 // If we get here it means that the last linger timeout for this network expired. So there
5939 // must be no other active linger timers, and we must stop lingering.
5940 oldNetwork.clearLingerState();
5941
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005942 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005943 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005944 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005945 } else {
5946 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005947 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5948 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005949 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005950 }
5951
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005952 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005953 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005954
Paul Jensen27b02b72014-07-14 12:03:33 -04005955 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005956 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005957 } catch (Exception e) {
5958 loge("Exception setting default network :" + e);
5959 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005960
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005961 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005962 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005963 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005964 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005965 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005966 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5967 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005968 }
5969
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005970 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005971 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5972 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5973 NetworkRequest nr = nri.request;
5974 if (!nr.isListen()) continue;
5975 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5976 nai.removeRequest(nri.request.requestId);
5977 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5978 }
5979 }
5980
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005981 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005982 try {
5983 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5984 } catch (RemoteException e) {
5985 e.rethrowFromSystemServer();
5986 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005987 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5988 }
5989
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005990 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5991 NetworkRequest nr = nri.request;
5992 if (!nr.isListen()) continue;
5993 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5994 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005995 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005996 }
5997 }
5998 }
5999
Paul Jensen2161a8e2014-09-11 11:00:39 -04006000 // Handles a network appearing or improving its score.
6001 //
6002 // - Evaluates all current NetworkRequests that can be
6003 // satisfied by newNetwork, and reassigns to newNetwork
6004 // any such requests for which newNetwork is the best.
6005 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006006 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006007 // needed. A network is needed if it is the best network for
6008 // one or more NetworkRequests, or if it is a VPN.
6009 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006010 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006011 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006012 //
6013 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6014 // networks that have no chance (i.e. even if validated)
6015 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006016 //
6017 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6018 // it does not remove NetworkRequests that other Networks could better satisfy.
6019 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6020 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6021 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006022 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006023 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006024 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6025 // performed to tear down unvalidated networks that have no chance (i.e. even if
6026 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006027 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006028 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006029 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006030 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006031 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006032 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006033
6034 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6035 final int score = newNetwork.getCurrentScore();
6036
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006037 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006038
Paul Jensen2161a8e2014-09-11 11:00:39 -04006039 // Find and migrate to this Network any NetworkRequests for
6040 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006041 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6042 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006043 NetworkCapabilities nc = newNetwork.networkCapabilities;
6044 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006045 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006046 // Process requests in the first pass and listens in the second pass. This allows us to
6047 // change a network's capabilities depending on which requests it has. This is only
6048 // correct if the change in capabilities doesn't affect whether the network satisfies
6049 // requests or not, and doesn't affect the network's score.
6050 if (nri.request.isListen()) continue;
6051
Hugo Benichicd952782017-09-20 11:20:14 +09006052 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006053 final boolean satisfies = newNetwork.satisfies(nri.request);
6054 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006055 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006056 log("Network " + newNetwork.name() + " was already satisfying" +
6057 " request " + nri.request.requestId + ". No change.");
6058 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006059 keep = true;
6060 continue;
6061 }
6062
6063 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006064 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006065 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006066 // next check if it's better than any current network we're using for
6067 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006068 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006069 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006070 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006071 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006072 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006073 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006074 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006075 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006076 if (VDBG || DDBG){
6077 log(" accepting network in place of " + currentNetwork.name());
6078 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006079 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006080 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006081 affectedNetworks.add(currentNetwork);
6082 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006083 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006084 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006085 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006086 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006087 if (!newNetwork.addRequest(nri.request)) {
6088 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6089 }
6090 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006091 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006092 // Tell NetworkFactories about the new score, so they can stop
6093 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006094 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006095 // network. Think about if there is a way to reduce this. Push
6096 // netid->request mapping to each factory?
Chalard Jean05ab6812018-05-02 21:14:54 +09006097 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006098 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006099 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006100 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006101 if (currentNetwork != null) {
6102 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6103 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006104 }
6105 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006106 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006107 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6108 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006109 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006110 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6111 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6112 // This means this code doesn't have to handle the case where "currentNetwork" no
6113 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6114 if (DBG) {
6115 log("Network " + newNetwork.name() + " stopped satisfying" +
6116 " request " + nri.request.requestId);
6117 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006118 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006119 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006120 clearNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09006121 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006122 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006123 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6124 newNetwork.name() +
6125 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006126 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006127 // TODO: Technically, sending CALLBACK_LOST here is
6128 // incorrect if there is a replacement network currently
6129 // connected that can satisfy nri, which is a request
6130 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006131 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6132 // so this code is only incorrect for a network that loses
6133 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006134 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006135 }
6136 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006137 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006138 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006139 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006140 makeDefault(newNetwork);
6141 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006142 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006143 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006144 // Have a new default network, release the transition wakelock in
6145 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006146 }
6147
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006148 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6149 Slog.wtf(TAG, String.format(
6150 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006151 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006152 }
6153 if (newNetwork.getCurrentScore() != score) {
6154 Slog.wtf(TAG, String.format(
6155 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006156 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006157 }
6158
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006159 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006160 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6161 // If the network went from background to foreground or vice versa, we need to update
6162 // its foreground state. It is safe to do this after rematching the requests because
6163 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6164 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006165 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006166 } else {
6167 processListenRequests(newNetwork, false);
6168 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006169
Paul Jensencf4c2c62015-07-01 14:16:32 -04006170 // do this after the default net is switched, but
6171 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006172 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006173
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006174 // Linger any networks that are no longer needed. This should be done after sending the
6175 // available callback for newNetwork.
6176 for (NetworkAgentInfo nai : affectedNetworks) {
6177 updateLingerState(nai, now);
6178 }
6179 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6180 // does not need to be done in any particular order.
6181 updateLingerState(newNetwork, now);
6182
Paul Jensencf4c2c62015-07-01 14:16:32 -04006183 if (isNewDefault) {
6184 // Maintain the illusion: since the legacy API only
6185 // understands one network at a time, we must pretend
6186 // that the current default network disconnected before
6187 // the new one connected.
6188 if (oldDefaultNetwork != null) {
6189 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6190 oldDefaultNetwork, true);
6191 }
6192 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6193 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6194 notifyLockdownVpn(newNetwork);
6195 }
6196
Robert Greenwalt7b816022014-04-18 15:25:25 -07006197 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006198 // Notify battery stats service about this network, both the normal
6199 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006200 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006201 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006202 final IBatteryStats bs = BatteryStatsService.getService();
6203 final int type = newNetwork.networkInfo.getType();
6204
6205 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6206 bs.noteNetworkInterfaceType(baseIface, type);
6207 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6208 final String stackedIface = stacked.getInterfaceName();
6209 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006210 }
6211 } catch (RemoteException ignored) {
6212 }
6213
Robert Greenwalt152ed372014-12-17 17:19:53 -08006214 // This has to happen after the notifyNetworkCallbacks as that tickles each
6215 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006216 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006217 // and will generally do a dns request so they can ensureRouteToHost and if
6218 // they do that before the callbacks happen they'll use the default network.
6219 //
6220 // TODO: Is there still a race here? We send the broadcast
6221 // after sending the callback, but if the app can receive the
6222 // broadcast before the callback, it might still break.
6223 //
6224 // This *does* introduce a race where if the user uses the new api
6225 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6226 // they may get old info. Reverse this after the old startUsing api is removed.
6227 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006228 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6229 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006230 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006231 // legacy type tracker filters out repeat adds
6232 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6233 }
6234 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006235
6236 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6237 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6238 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6239 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6240 if (newNetwork.isVPN()) {
6241 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6242 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006243 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006244 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6245 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006246 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006247 if (nai.getLingerExpiry() > 0) {
6248 // This network has active linger timers and no requests, but is not
6249 // lingering. Linger it.
6250 //
6251 // One way (the only way?) this can happen if this network is unvalidated
6252 // and became unneeded due to another network improving its score to the
6253 // point where this network will no longer be able to satisfy any requests
6254 // even if it validates.
6255 updateLingerState(nai, now);
6256 } else {
6257 if (DBG) log("Reaping " + nai.name());
6258 teardownUnneededNetwork(nai);
6259 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006260 }
6261 }
6262 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006263 }
6264
Paul Jensen1c7ba022015-06-16 14:27:36 -04006265 /**
6266 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6267 * being disconnected.
6268 * @param changed If only one Network's score or capabilities have been modified since the last
6269 * time this function was called, pass this Network in this argument, otherwise pass
6270 * null.
6271 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6272 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6273 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6274 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6275 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006276 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006277 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006278 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6279 // to avoid the slowness. It is not simply enough to process just "changed", for
6280 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006281 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006282
6283 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6284 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6285 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006286 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006287 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006288 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006289 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006290 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6291 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6292 // Rematch higher scoring networks first to prevent requests first matching a lower
6293 // scoring network and then a higher scoring network, which could produce multiple
6294 // callbacks and inadvertently unlinger networks.
6295 Arrays.sort(nais);
6296 for (NetworkAgentInfo nai : nais) {
6297 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006298 // Only reap the last time through the loop. Reaping before all rematching
6299 // is complete could incorrectly teardown a network that hasn't yet been
6300 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006301 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006302 : ReapUnvalidatedNetworks.REAP,
6303 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006304 }
6305 }
6306 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006307
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006308 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006309 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006310 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006311 // For now only update icons for default connection.
6312 // TODO: Update WiFi and cellular icons separately. b/17237507
6313 if (!isDefaultNetwork(nai)) return;
6314
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006315 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006316 // Don't repeat publish.
6317 if (newInetCondition == mDefaultInetConditionPublished) return;
6318
6319 mDefaultInetConditionPublished = newInetCondition;
6320 sendInetConditionBroadcast(nai.networkInfo);
6321 }
6322
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006323 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006324 synchronized (mVpns) {
6325 if (mLockdownTracker != null) {
6326 if (nai != null && nai.isVPN()) {
6327 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6328 } else {
6329 mLockdownTracker.onNetworkInfoChanged();
6330 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006331 }
6332 }
6333 }
6334
Robert Greenwalt7b816022014-04-18 15:25:25 -07006335 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006336 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006337 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006338 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006339 synchronized (networkAgent) {
6340 oldInfo = networkAgent.networkInfo;
6341 networkAgent.networkInfo = newInfo;
6342 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006343 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006344
Robert Greenwalt7b816022014-04-18 15:25:25 -07006345 if (DBG) {
6346 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6347 (oldInfo == null ? "null" : oldInfo.getState()) +
6348 " to " + state);
6349 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006350
Robin Lee585e2482016-05-01 23:00:00 +01006351 if (!networkAgent.created
6352 && (state == NetworkInfo.State.CONNECTED
6353 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006354
6355 // A network that has just connected has zero requests and is thus a foreground network.
6356 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6357
Robert Greenwalt7b816022014-04-18 15:25:25 -07006358 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006359 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006360 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006361 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006362 (networkAgent.networkMisc == null ||
6363 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006364 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006365 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006366 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006367 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006368 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006369 loge("Error creating network " + networkAgent.network.netId + ": "
6370 + e.getMessage());
6371 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006372 }
Paul Jenseneec75412014-08-04 12:21:19 -04006373 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006374 }
6375
6376 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6377 networkAgent.everConnected = true;
6378
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006379 if (networkAgent.linkProperties == null) {
6380 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6381 }
6382
Erik Kline736353a2018-03-21 07:18:33 -07006383 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006384 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6385 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006386
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006387 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6388 // command must be sent after updating LinkProperties to maximize chances of
6389 // NetworkMonitor seeing the correct LinkProperties when starting.
6390 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6391 try {
lucaslin43338992019-03-20 18:21:59 +08006392 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6393 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6394 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006395 networkAgent.networkMonitor().notifyNetworkConnected();
6396 } catch (RemoteException e) {
6397 e.rethrowFromSystemServer();
6398 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006399 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006400
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006401 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6402 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6403 // capabilities, so it only needs to be done once on initial connect, not every time the
6404 // network's capabilities change. Note that we do this before rematching the network,
6405 // so we could decide to tear it down immediately afterwards. That's fine though - on
6406 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6407 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006408 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006409
Varun Anand4fa80e82019-02-06 10:13:38 -08006410 if (networkAgent.isVPN()) {
6411 updateAllVpnsCapabilities();
6412 }
6413
Paul Jensen2161a8e2014-09-11 11:00:39 -04006414 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006415 final long now = SystemClock.elapsedRealtime();
6416 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006417
6418 // This has to happen after matching the requests, because callbacks are just requests.
6419 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006420 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006421 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006422 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006423 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006424 }
Chalard Jean392971c2018-05-11 20:19:20 +09006425 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006426 if (networkAgent.isVPN()) {
6427 // As the active or bound network changes for apps, broadcast the default proxy, as
6428 // apps may need to update their proxy data. This is called after disconnecting from
6429 // VPN to make sure we do not broadcast the old proxy data.
6430 // TODO(b/122649188): send the broadcast only to VPN users.
6431 mProxyTracker.sendProxyBroadcast();
6432 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006433 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6434 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006435 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006436 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006437 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006438 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006439 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6440 networkAgent.networkCapabilities);
6441 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6442 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006443 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6444 ConnectivityManager.CALLBACK_SUSPENDED :
6445 ConnectivityManager.CALLBACK_RESUMED));
6446 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006447 }
6448 }
6449
Robert Greenwaltac96c522014-06-03 16:43:57 -07006450 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006451 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006452 if (score < 0) {
6453 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6454 "). Bumping score to min of 0");
6455 score = 0;
6456 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006457
Paul Jensen2161a8e2014-09-11 11:00:39 -04006458 final int oldScore = nai.getCurrentScore();
6459 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006460
Paul Jensen85cf78e2015-06-25 13:25:07 -04006461 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006462
Paul Jensenc8b9a742014-09-30 15:37:41 -04006463 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006464 }
6465
Erik Klinec75d4fa2017-02-15 19:59:17 +09006466 // Notify only this one new request of the current state. Transfer all the
6467 // current state by calling NetworkCapabilities and LinkProperties callbacks
6468 // so that callers can be guaranteed to have as close to atomicity in state
6469 // transfer as can be supported by this current API.
6470 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006471 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006472 if (nri.mPendingIntent != null) {
6473 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6474 // Attempt no subsequent state pushes where intents are involved.
6475 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006476 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006477
junyulai05986c62018-08-07 19:50:45 +08006478 final boolean metered = nai.networkCapabilities.isMetered();
6479 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6480 metered, mRestrictBackground);
6481 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6482 }
6483
6484 /**
6485 * Notify of the blocked state apps with a registered callback matching a given NAI.
6486 *
6487 * Unlike other callbacks, blocked status is different between each individual uid. So for
6488 * any given nai, all requests need to be considered according to the uid who filed it.
6489 *
6490 * @param nai The target NetworkAgentInfo.
6491 * @param oldMetered True if the previous network capabilities is metered.
6492 * @param newRestrictBackground True if data saver is enabled.
6493 */
6494 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6495 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6496
6497 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6498 NetworkRequest nr = nai.requestAt(i);
6499 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6500 final int uidRules = mUidRules.get(nri.mUid);
6501 final boolean oldBlocked, newBlocked;
6502 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6503 // between these two calls.
6504 synchronized (mVpns) {
6505 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6506 oldRestrictBackground);
6507 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6508 newRestrictBackground);
6509 }
6510 if (oldBlocked != newBlocked) {
6511 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6512 encodeBool(newBlocked));
6513 }
6514 }
6515 }
6516
6517 /**
6518 * Notify apps with a given UID of the new blocked state according to new uid rules.
6519 * @param uid The uid for which the rules changed.
6520 * @param newRules The new rules to apply.
6521 */
6522 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6523 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6524 final boolean metered = nai.networkCapabilities.isMetered();
6525 final boolean oldBlocked, newBlocked;
6526 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6527 // rules changed event. And this function actually loop through all connected nai and
6528 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6529 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6530 synchronized (mVpns) {
6531 oldBlocked = isUidNetworkingWithVpnBlocked(
6532 uid, mUidRules.get(uid), metered, mRestrictBackground);
6533 newBlocked = isUidNetworkingWithVpnBlocked(
6534 uid, newRules, metered, mRestrictBackground);
6535 }
6536 if (oldBlocked == newBlocked) {
6537 return;
6538 }
6539 final int arg = encodeBool(newBlocked);
6540 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6541 NetworkRequest nr = nai.requestAt(i);
6542 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6543 if (nri != null && nri.mUid == uid) {
6544 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6545 }
6546 }
6547 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006548 }
6549
Robert Greenwalt8d482522015-06-24 13:23:42 -07006550 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006551 // The NetworkInfo we actually send out has no bearing on the real
6552 // state of affairs. For example, if the default connection is mobile,
6553 // and a request for HIPRI has just gone away, we need to pretend that
6554 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6555 // the state to DISCONNECTED, even though the network is of type MOBILE
6556 // and is still connected.
6557 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6558 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006559 if (state != DetailedState.DISCONNECTED) {
6560 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006561 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006562 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006563 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006564 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6565 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6566 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6567 if (info.isFailover()) {
6568 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6569 nai.networkInfo.setFailover(false);
6570 }
6571 if (info.getReason() != null) {
6572 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6573 }
6574 if (info.getExtraInfo() != null) {
6575 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6576 }
6577 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006578 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006579 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006580 if (newDefaultAgent != null) {
6581 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6582 newDefaultAgent.networkInfo);
6583 } else {
6584 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6585 }
6586 }
6587 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6588 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006589 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006590 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006591 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006592 }
6593 }
6594 }
6595
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006596 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006597 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006598 String notification = ConnectivityManager.getCallbackName(notifyType);
6599 log("notifyType " + notification + " for " + networkAgent.name());
6600 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006601 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6602 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006603 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6604 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006605 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6606 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006607 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006608 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006609 } else {
6610 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6611 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006612 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006613 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006614
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006615 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6616 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6617 }
6618
Jeff Sharkey69736342014-12-08 14:50:12 -08006619 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006620 * Returns the list of all interfaces that could be used by network traffic that does not
6621 * explicitly specify a network. This includes the default network, but also all VPNs that are
6622 * currently connected.
6623 *
6624 * Must be called on the handler thread.
6625 */
6626 private Network[] getDefaultNetworks() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006627 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006628 ArrayList<Network> defaultNetworks = new ArrayList<>();
6629 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6630 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6631 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6632 defaultNetworks.add(nai.network);
6633 }
6634 }
6635 return defaultNetworks.toArray(new Network[0]);
6636 }
6637
6638 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006639 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6640 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006641 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006642 private void notifyIfacesChangedForNetworkStats() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006643 ensureRunningOnConnectivityServiceThread();
6644 String activeIface = null;
6645 LinkProperties activeLinkProperties = getActiveLinkProperties();
6646 if (activeLinkProperties != null) {
6647 activeIface = activeLinkProperties.getInterfaceName();
6648 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006649 try {
Varun Anandd33cbc62019-02-07 14:13:13 -08006650 mStatsService.forceUpdateIfaces(
6651 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006652 } catch (Exception ignored) {
6653 }
6654 }
6655
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006656 @Override
6657 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006658 int user = UserHandle.getUserId(Binder.getCallingUid());
6659 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006660 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006661 return mVpns.get(user).addAddress(address, prefixLength);
6662 }
6663 }
6664
6665 @Override
6666 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006667 int user = UserHandle.getUserId(Binder.getCallingUid());
6668 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006669 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006670 return mVpns.get(user).removeAddress(address, prefixLength);
6671 }
6672 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006673
6674 @Override
6675 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006676 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006677 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006678 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006679 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006680 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006681 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006682 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006683 mHandler.post(() -> {
6684 // Update VPN's capabilities based on updated underlying network set.
6685 updateAllVpnsCapabilities();
6686 notifyIfacesChangedForNetworkStats();
6687 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006688 }
6689 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006690 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006691
6692 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006693 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006694 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006695 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006696 }
6697
6698 @Override
junyulai7c469172019-01-16 20:23:34 +08006699 public void startNattKeepalive(Network network, int intervalSeconds,
6700 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006701 enforceKeepalivePermission();
6702 mKeepaliveTracker.startNattKeepalive(
junyulai0c666972019-03-04 22:45:36 +08006703 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai7c469172019-01-16 20:23:34 +08006704 intervalSeconds, cb,
junyulai06835112019-01-03 18:50:15 +08006705 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006706 }
6707
6708 @Override
junyulai215b8772019-01-15 11:32:44 +08006709 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006710 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006711 String dstAddr) {
junyulai215b8772019-01-15 11:32:44 +08006712 mKeepaliveTracker.startNattKeepalive(
6713 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006714 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006715 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6716 }
6717
6718 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006719 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006720 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006721 enforceKeepalivePermission();
6722 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006723 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006724 }
6725
6726 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006727 public void stopKeepalive(Network network, int slot) {
6728 mHandler.sendMessage(mHandler.obtainMessage(
junyulai06835112019-01-03 18:50:15 +08006729 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006730 }
6731
6732 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006733 public void factoryReset() {
6734 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006735
6736 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6737 return;
6738 }
6739
Robin Lee3b3dd942015-05-12 18:14:58 +01006740 final int userId = UserHandle.getCallingUserId();
6741
Stuart Scottf1fb3972015-04-02 18:00:02 -07006742 // Turn airplane mode off
6743 setAirplaneMode(false);
6744
Stuart Scotte3e314d2015-04-20 14:07:45 -07006745 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6746 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006747 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006748 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006749 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006750 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006751 }
6752
Stuart Scotte3e314d2015-04-20 14:07:45 -07006753 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006754 // Remove always-on package
6755 synchronized (mVpns) {
6756 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6757 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006758 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006759 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6760 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006761
Hugo Benichi69744342017-11-27 10:57:16 +09006762 // Turn Always-on VPN off
6763 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6764 final long ident = Binder.clearCallingIdentity();
6765 try {
6766 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6767 mLockdownEnabled = false;
6768 setLockdownTracker(null);
6769 } finally {
6770 Binder.restoreCallingIdentity(ident);
6771 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006772 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006773
Hugo Benichi69744342017-11-27 10:57:16 +09006774 // Turn VPN off
6775 VpnConfig vpnConfig = getVpnConfig(userId);
6776 if (vpnConfig != null) {
6777 if (vpnConfig.legacy) {
6778 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6779 } else {
6780 // Prevent this app (packagename = vpnConfig.user) from initiating
6781 // VPN connections in the future without user intervention.
6782 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006783
Hugo Benichi69744342017-11-27 10:57:16 +09006784 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6785 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006786 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006787 }
6788 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006789
6790 Settings.Global.putString(mContext.getContentResolver(),
6791 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006792 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006793
Ricky Wai44dcbde2018-01-23 04:09:45 +00006794 @Override
6795 public byte[] getNetworkWatchlistConfigHash() {
6796 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6797 if (nwm == null) {
6798 loge("Unable to get NetworkWatchlistManager");
6799 return null;
6800 }
6801 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6802 return nwm.getWatchlistConfigHash();
6803 }
6804
Paul Jensencf4c2c62015-07-01 14:16:32 -04006805 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006806 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6807 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006808 }
6809
6810 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006811 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6812 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6813 }
6814
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006815 @VisibleForTesting
6816 public boolean hasService(String name) {
6817 return ServiceManager.checkService(name) != null;
6818 }
6819
Hugo Benichi64901e52017-10-19 14:42:40 +09006820 @VisibleForTesting
6821 protected IpConnectivityMetrics.Logger metricsLogger() {
6822 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6823 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006824 }
6825
6826 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006827 int[] transports = nai.networkCapabilities.getTransportTypes();
6828 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006829 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006830
6831 private static boolean toBool(int encodedBoolean) {
6832 return encodedBoolean != 0; // Only 0 means false.
6833 }
6834
6835 private static int encodeBool(boolean b) {
6836 return b ? 1 : 0;
6837 }
mswest46386886f2018-03-12 10:34:34 -07006838
6839 @Override
6840 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6841 FileDescriptor err, String[] args, ShellCallback callback,
6842 ResultReceiver resultReceiver) {
6843 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6844 }
6845
6846 private class ShellCmd extends ShellCommand {
6847
6848 @Override
6849 public int onCommand(String cmd) {
6850 if (cmd == null) {
6851 return handleDefaultCommands(cmd);
6852 }
6853 final PrintWriter pw = getOutPrintWriter();
6854 try {
6855 switch (cmd) {
6856 case "airplane-mode":
6857 final String action = getNextArg();
6858 if ("enable".equals(action)) {
6859 setAirplaneMode(true);
6860 return 0;
6861 } else if ("disable".equals(action)) {
6862 setAirplaneMode(false);
6863 return 0;
6864 } else if (action == null) {
6865 final ContentResolver cr = mContext.getContentResolver();
6866 final int enabled = Settings.Global.getInt(cr,
6867 Settings.Global.AIRPLANE_MODE_ON);
6868 pw.println(enabled == 0 ? "disabled" : "enabled");
6869 return 0;
6870 } else {
6871 onHelp();
6872 return -1;
6873 }
6874 default:
6875 return handleDefaultCommands(cmd);
6876 }
6877 } catch (Exception e) {
6878 pw.println(e);
6879 }
6880 return -1;
6881 }
6882
6883 @Override
6884 public void onHelp() {
6885 PrintWriter pw = getOutPrintWriter();
6886 pw.println("Connectivity service commands:");
6887 pw.println(" help");
6888 pw.println(" Print this help text.");
6889 pw.println(" airplane-mode [enable|disable]");
6890 pw.println(" Turn airplane mode on or off.");
6891 pw.println(" airplane-mode");
6892 pw.println(" Get airplane mode.");
6893 }
6894 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006895
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006896 @GuardedBy("mVpns")
6897 private Vpn getVpnIfOwner() {
6898 final int uid = Binder.getCallingUid();
6899 final int user = UserHandle.getUserId(uid);
6900
6901 final Vpn vpn = mVpns.get(user);
6902 if (vpn == null) {
6903 return null;
6904 } else {
6905 final VpnInfo info = vpn.getVpnInfo();
6906 return (info == null || info.ownerUid != uid) ? null : vpn;
6907 }
6908 }
6909
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006910 /**
6911 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6912 * for testing.
6913 */
6914 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6915 if (checkNetworkStackPermission()) {
6916 return null;
6917 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006918 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006919 Vpn vpn = getVpnIfOwner();
6920 if (vpn != null) {
6921 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006922 }
6923 }
6924 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6925 + "permission");
6926 }
6927
6928 /**
6929 * @param connectionInfo the connection to resolve.
6930 * @return {@code uid} if the connection is found and the app has permission to observe it
6931 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6932 * connection is not found.
6933 */
6934 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6935 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6936 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6937 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6938 }
6939
6940 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6941 connectionInfo.local, connectionInfo.remote);
6942
6943 /* Filter out Uids not associated with the VPN. */
6944 if (vpn != null && !vpn.appliesToUid(uid)) {
6945 return INVALID_UID;
6946 }
6947
6948 return uid;
6949 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006950
6951 @Override
6952 public boolean isCallerCurrentAlwaysOnVpnApp() {
6953 synchronized (mVpns) {
6954 Vpn vpn = getVpnIfOwner();
6955 return vpn != null && vpn.getAlwaysOn();
6956 }
6957 }
6958
6959 @Override
6960 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6961 synchronized (mVpns) {
6962 Vpn vpn = getVpnIfOwner();
6963 return vpn != null && vpn.getLockdown();
6964 }
6965 }
Benedict Wonga341fbc2018-11-09 14:45:34 -08006966
6967 /**
6968 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
6969 *
6970 * <p>The TestNetworkService must be run in the system server due to TUN creation.
6971 */
6972 @Override
6973 public IBinder startOrGetTestNetworkService() {
6974 synchronized (mTNSLock) {
6975 TestNetworkService.enforceTestNetworkPermissions(mContext);
6976
6977 if (mTNS == null) {
6978 mTNS = new TestNetworkService(mContext, mNMS);
6979 }
6980
6981 return mTNS;
6982 }
6983 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006984}