blob: cab969791e998b92bf486862a825808d83c68798 [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 VAN5a1b74b2019-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 VAN5a1b74b2019-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;
markchien6ea34542019-02-27 14:56:11 +080076import android.net.ITetheringEventCallback;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090077import android.net.InetAddresses;
78import android.net.IpPrefix;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080079import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070080import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010081import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080082import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070083import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070084import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070085import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070086import android.net.NetworkConfig;
Chalard Jean08577fc2018-05-02 21:14:54 +090087import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070089import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070090import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090091import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070092import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070093import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070094import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090095import android.net.NetworkStack;
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +090096import android.net.NetworkStackClient;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070097import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070098import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000099import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900100import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -0400101import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -0700102import android.net.RouteInfo;
junyulaie4135282019-01-03 18:50:15 +0800103import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -0400105import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600106import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900107import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900108import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700109import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900110import android.net.shared.NetworkMonitorUtils;
111import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900112import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900113import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800115import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700116import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700118import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700120import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.os.Looper;
122import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700123import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700124import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900125import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700126import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700127import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700128import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800129import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900130import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900131import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700132import android.os.ShellCallback;
133import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900134import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700135import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400136import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700138import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700139import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700140import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900142import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700143import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600144import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900145import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800146import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700147import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500148import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700149import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Wink Savilleab9321d2013-06-29 21:10:57 -0700152import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400153import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400154import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700155import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANd4a9de202019-01-30 22:01:20 +0900156import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700157import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700158import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800159import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700160import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900161import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700162import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600163import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700164import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900165import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900166import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700167import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700168import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400169import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900170import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500171import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900172import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900173import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100174import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700175import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900176import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700177import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600178import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900179import com.android.server.connectivity.NetworkNotificationManager;
180import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700181import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900182import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800183import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700184import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100185import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500186import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700187import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700188import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900189import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700190import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600191
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700192import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700193
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700194import org.xmlpull.v1.XmlPullParser;
195import org.xmlpull.v1.XmlPullParserException;
196
197import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700199import java.io.FileNotFoundException;
200import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700201import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700203import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700204import java.net.InetAddress;
205import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700206import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700207import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700208import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900209import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800210import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700211import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700212import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700214import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700215import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900216import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600217import java.util.SortedSet;
218import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
220/**
221 * @hide
222 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800223public class ConnectivityService extends IConnectivityManager.Stub
224 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900225 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Chalard Jean4133a122018-06-04 13:33:12 +0900227 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900228 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900229 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900230 private static final String NETWORK_ARG = "networks";
231 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900232
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900233 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900234 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
235 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900237 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700238
Jeff Sharkey899223b2012-08-04 15:24:58 -0700239 // TODO: create better separation between radio types and network types
240
Robert Greenwalt42acef32009-08-12 16:08:25 -0700241 // how long to wait before switching back to a radio's default network
242 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
243 // system property that can override the above value
244 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
245 "android.telephony.apn-restore";
246
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900247 // How long to wait before putting up a "This network doesn't have an Internet connection,
248 // connect anyway?" dialog after the user selects a network that doesn't validate.
249 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
250
lucaslind2e045e02019-01-24 15:55:30 +0800251 // How long to dismiss network notification.
252 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
253
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900254 // Default to 30s linger time-out. Modifiable only for testing.
255 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
256 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
257 @VisibleForTesting
258 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
259
Jeremy Joslin79294842014-12-03 17:15:28 -0800260 // How long to delay to removal of a pending intent based request.
261 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
262 private final int mReleasePendingIntentDelayMs;
263
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900264 private MockableSystemProperties mSystemProperties;
265
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800266 private Tethering mTethering;
267
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700268 private final PermissionMonitor mPermissionMonitor;
269
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700270 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700271
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900272 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700273 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900274 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700275
Hugo Benichi69744342017-11-27 10:57:16 +0900276 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
277 // a direct call to LockdownVpnTracker.isEnabled().
278 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700279 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900280 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700281 private LockdownVpnTracker mLockdownTracker;
282
junyulai05986c62018-08-07 19:50:45 +0800283 /**
284 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
285 * handler thread, they don't need a lock.
286 */
287 private SparseIntArray mUidRules = new SparseIntArray();
288 /** Flag indicating if background data is restricted. */
289 private boolean mRestrictBackground;
290
Erik Klineda4bfa82015-04-30 12:58:40 +0900291 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700292 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700293 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Luke Huang4e25ec62018-09-27 16:58:23 +0800295 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800296 @VisibleForTesting
297 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800298 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700299 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900300 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700301
Benedict Wong99a48412018-11-09 14:45:34 -0800302 /**
303 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
304 * instances.
305 */
306 @GuardedBy("mTNSLock")
307 private TestNetworkService mTNS;
308
309 private final Object mTNSLock = new Object();
310
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700311 private String mCurrentTcpBufferSizes;
312
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900313 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900314 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
315 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900316
Paul Jensenb10e37f2014-11-25 12:33:08 -0500317 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400318 // Tear down networks that have no chance (e.g. even if validated) of becoming
319 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500320 // all networks have been rematched against all NetworkRequests.
321 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400322 // Don't reap networks. This should be passed when some networks have not yet been
323 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500324 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900325 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500326
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900327 private enum UnneededFor {
328 LINGER, // Determine whether this network is unneeded and should be lingered.
329 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
330 }
331
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700332 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700333 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700334 * from one net to another. Clear happens when we get a new
335 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
336 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700337 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700338 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700339
Robert Greenwalt434203a2010-10-11 16:00:27 -0700340 /**
341 * used internally to reload global proxy settings
342 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700343 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700344
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700345 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400346 * PAC manager has received new port.
347 */
348 private static final int EVENT_PROXY_HAS_CHANGED = 16;
349
Robert Greenwalte049c232014-04-11 15:53:27 -0700350 /**
351 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700352 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700353 */
354 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
355
Robert Greenwalt7b816022014-04-18 15:25:25 -0700356 /**
357 * used internally when registering NetworkAgents
358 * obj = Messenger
359 */
360 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
361
Robert Greenwalt9258c642014-03-26 16:47:06 -0700362 /**
363 * used to add a network request
364 * includes a NetworkRequestInfo
365 */
366 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
367
368 /**
369 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900370 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700371 * cancel it.
372 * includes a NetworkRequestInfo
373 */
374 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
375
376 /**
377 * used to add a network listener - no request
378 * includes a NetworkRequestInfo
379 */
380 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
381
382 /**
383 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400384 * arg1 = UID of caller
385 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700386 */
387 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
388
Robert Greenwalta67be032014-05-16 15:49:14 -0700389 /**
390 * used internally when registering NetworkFactories
391 * obj = Messenger
392 */
393 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
394
Robert Greenwalt27711812014-06-25 16:45:57 -0700395 /**
396 * used internally to expire a wakelock when transitioning
397 * from one net to another. Expire happens when we fail to find
398 * a new network (typically after 1 minute) -
399 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
400 * a replacement network.
401 */
402 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
403
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700404 /**
405 * Used internally to indicate the system is ready.
406 */
407 private static final int EVENT_SYSTEM_READY = 25;
408
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800409 /**
410 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400411 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800412 */
413 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
414
415 /**
416 * used to remove a pending intent and its associated network request.
417 * arg1 = UID of caller
418 * obj = PendingIntent
419 */
420 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
421
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900422 /**
423 * used to specify whether a network should be used even if unvalidated.
424 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
425 * arg2 = whether to remember this choice in the future (1 or 0)
426 * obj = network
427 */
428 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
429
430 /**
431 * used to ask the user to confirm a connection to an unvalidated network.
432 * obj = network
433 */
434 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700435
Erik Klineda4bfa82015-04-30 12:58:40 +0900436 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700437 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900438 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700439 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900440
Paul Jensen694f2b82015-06-17 14:15:39 -0400441 /**
442 * used to add a network listener with a pending intent
443 * obj = NetworkRequestInfo
444 */
445 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
446
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900447 /**
448 * used to specify whether a network should not be penalized when it becomes unvalidated.
449 */
450 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
451
452 /**
453 * used to trigger revalidation of a network.
454 */
455 private static final int EVENT_REVALIDATE_NETWORK = 36;
456
Erik Klinea24d4592018-01-11 21:07:29 +0900457 // Handle changes in Private DNS settings.
458 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
459
dalyk7301aa42018-03-05 12:42:22 -0500460 // Handle private DNS validation status updates.
461 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
462
junyulai05986c62018-08-07 19:50:45 +0800463 /**
464 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
465 */
466 private static final int EVENT_UID_RULES_CHANGED = 39;
467
468 /**
469 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
470 */
471 private static final int EVENT_DATA_SAVER_CHANGED = 40;
472
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900473 /**
474 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
475 * been tested.
476 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
477 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
478 * arg2 = NetID.
479 */
480 public static final int EVENT_NETWORK_TESTED = 41;
481
482 /**
483 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
484 * config was resolved.
485 * obj = PrivateDnsConfig
486 * arg2 = netid
487 */
488 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
489
490 /**
491 * Request ConnectivityService display provisioning notification.
492 * arg1 = Whether to make the notification visible.
493 * arg2 = NetID.
494 * obj = Intent to be launched when notification selected by user, null if !arg1.
495 */
496 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
497
498 /**
lucaslind2e045e02019-01-24 15:55:30 +0800499 * This event can handle dismissing notification by given network id.
500 */
501 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
502
503 /**
lucasline252a742019-03-12 13:08:03 +0800504 * Used to specify whether a network should be used even if connectivity is partial.
505 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
506 * false)
507 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
508 * obj = network
509 */
510 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
511
512 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900513 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
514 * should be shown.
515 */
516 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
517
518 /**
519 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
520 * should be hidden.
521 */
522 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
523
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900524 private static String eventName(int what) {
525 return sMagicDecoderRing.get(what, Integer.toString(what));
526 }
527
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900528 /** Handler thread used for both of the handlers below. */
529 @VisibleForTesting
530 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700531 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700532 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700533 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700534 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900535 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700536
Mike Lockwood0f79b542009-08-14 14:18:49 -0400537 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800538 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400539
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700540 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700541 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800542 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700543
Chalard Jean52c2aa72018-06-07 16:44:04 +0900544 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
545 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000546 @VisibleForTesting
547 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400548
Erik Klineda4bfa82015-04-30 12:58:40 +0900549 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700550
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400551 private UserManager mUserManager;
552
Chalard Jean4133a122018-06-04 13:33:12 +0900553 private NetworkConfig[] mNetConfigs;
554 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700555
Robert Greenwalt50393202011-06-21 17:26:14 -0700556 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900557 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700558
Chalard Jean4133a122018-06-04 13:33:12 +0900559 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400560
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900561 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900562 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900563 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900564
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700565 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800566 private static final int MIN_NET_ID = 100; // some reserved marks
567 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700568 private int mNextNetId = MIN_NET_ID;
569
Robert Greenwalt34524f02014-05-18 16:22:10 -0700570 // sequence number of NetworkRequests
571 private int mNextNetworkRequestId = 1;
572
Erik Kline7523eb32015-07-09 18:24:03 +0900573 // NetworkRequest activity String log entries.
574 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
575 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
576
Hugo Benichic2ae2872016-07-11 11:05:12 +0900577 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900578 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900579 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
580
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900581 private static final int MAX_WAKELOCK_LOGS = 20;
582 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900583 private int mTotalWakelockAcquisitions = 0;
584 private int mTotalWakelockReleases = 0;
585 private long mTotalWakelockDurationMs = 0;
586 private long mMaxWakelockDurationMs = 0;
587 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900588
Hugo Benichif9fdf872016-07-28 17:53:06 +0900589 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900590
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700591 @GuardedBy("mBandwidthRequests")
592 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
593
Erik Kline065ab6e2016-10-02 18:02:14 +0900594 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900595 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900596
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900597 @VisibleForTesting
598 final MultipathPolicyTracker mMultipathPolicyTracker;
599
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700600 /**
601 * Implements support for the legacy "one network per network type" model.
602 *
603 * We used to have a static array of NetworkStateTrackers, one for each
604 * network type, but that doesn't work any more now that we can have,
605 * for example, more that one wifi network. This class stores all the
606 * NetworkAgentInfo objects that support a given type, but the legacy
607 * API will only see the first one.
608 *
609 * It serves two main purposes:
610 *
611 * 1. Provide information about "the network for a given type" (since this
612 * API only supports one).
613 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
614 * the first network for a given type changes, or if the default network
615 * changes.
616 */
617 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900619 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900620 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900621
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700622 /**
623 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
624 * Each list holds references to all NetworkAgentInfos that are used to
625 * satisfy requests for that network type.
626 *
627 * This array is built out at startup such that an unsupported network
628 * doesn't get an ArrayList instance, making this a tristate:
629 * unsupported, supported but not active and active.
630 *
631 * The actual lists are populated when we scan the network types that
632 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900633 *
634 * Threading model:
635 * - addSupportedType() is only called in the constructor
636 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
637 * They are therefore not thread-safe with respect to each other.
638 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
639 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
640 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900642 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700643
644 public LegacyTypeTracker() {
645 mTypeLists = (ArrayList<NetworkAgentInfo>[])
646 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
647 }
648
649 public void addSupportedType(int type) {
650 if (mTypeLists[type] != null) {
651 throw new IllegalStateException(
652 "legacy list for type " + type + "already initialized");
653 }
Chalard Jean4133a122018-06-04 13:33:12 +0900654 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 }
656
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700657 public boolean isTypeSupported(int type) {
658 return isNetworkTypeValid(type) && mTypeLists[type] != null;
659 }
660
661 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900662 synchronized (mTypeLists) {
663 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
664 return mTypeLists[type].get(0);
665 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700666 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900667 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700668 }
669
Robert Greenwalt8d482522015-06-24 13:23:42 -0700670 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900671 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900672 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700673 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900674 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900675 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 }
677 }
678
679 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700680 public void add(int type, NetworkAgentInfo nai) {
681 if (!isTypeSupported(type)) {
682 return; // Invalid network type.
683 }
684 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
685
686 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
687 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700688 return;
689 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900690 synchronized (mTypeLists) {
691 list.add(nai);
692 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900693
694 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900695 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900696 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700697 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
698 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700699 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700700 }
701
Lorenzo Colittia793a672014-07-31 23:20:17 +0900702 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900703 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900704 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
705 if (list == null || list.isEmpty()) {
706 return;
707 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900708 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900709
Hugo Benichi78caa2582016-06-21 09:48:07 +0900710 synchronized (mTypeLists) {
711 if (!list.remove(nai)) {
712 return;
713 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900714 }
715
Robert Greenwalt8d482522015-06-24 13:23:42 -0700716 final DetailedState state = DetailedState.DISCONNECTED;
717
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900718 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700719 maybeLogBroadcast(nai, state, type, wasDefault);
720 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900721 }
722
723 if (!list.isEmpty() && wasFirstNetwork) {
724 if (DBG) log("Other network available for type " + type +
725 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900726 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700727 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
728 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900729 }
730 }
731
732 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900733 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
734 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700735 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900736 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700737 }
738 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700739
Robert Greenwalt8d482522015-06-24 13:23:42 -0700740 // send out another legacy broadcast - currently only used for suspend/unsuspend
741 // toggle
742 public void update(NetworkAgentInfo nai) {
743 final boolean isDefault = isDefaultNetwork(nai);
744 final DetailedState state = nai.networkInfo.getDetailedState();
745 for (int type = 0; type < mTypeLists.length; type++) {
746 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700747 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900748 final boolean isFirst = contains && (nai == list.get(0));
749 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700750 maybeLogBroadcast(nai, state, type, isDefault);
751 sendLegacyNetworkBroadcast(nai, state, type);
752 }
753 }
754 }
755
Lorenzo Colittia793a672014-07-31 23:20:17 +0900756 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900757 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900758 String state = (nai.networkInfo != null) ?
759 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
760 "???/???";
761 return name + " " + state;
762 }
763
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700764 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900765 pw.println("mLegacyTypeTracker:");
766 pw.increaseIndent();
767 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700768 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900769 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700770 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900771 pw.println();
772 pw.println("Current state:");
773 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900774 synchronized (mTypeLists) {
775 for (int type = 0; type < mTypeLists.length; type++) {
776 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
777 for (NetworkAgentInfo nai : mTypeLists[type]) {
778 pw.println(type + " " + naiToString(nai));
779 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900780 }
781 }
782 pw.decreaseIndent();
783 pw.decreaseIndent();
784 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700785 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700786 }
787 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
788
Vishnu Nair5c010902017-10-26 10:08:50 -0700789 /**
790 * Helper class which parses out priority arguments and dumps sections according to their
791 * priority. If priority arguments are omitted, function calls the legacy dump command.
792 */
793 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
794 @Override
795 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
796 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
797 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
798 }
799
800 @Override
801 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
802 doDump(fd, pw, args, asProto);
803 }
804
805 @Override
806 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
807 doDump(fd, pw, args, asProto);
808 }
809 };
810
Jeff Sharkey899223b2012-08-04 15:24:58 -0700811 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700812 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900813 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
814 }
815
816 @VisibleForTesting
817 protected ConnectivityService(Context context, INetworkManagementService netManager,
818 INetworkStatsService statsService, INetworkPolicyManager policyManager,
819 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800820 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800821
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900822 mSystemProperties = getSystemProperties();
823
Hugo Benichif9fdf872016-07-28 17:53:06 +0900824 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900825 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900826 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900827 mNetworkRequests.put(mDefaultRequest, defaultNRI);
828 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900829
Chalard Jeandda156a2018-01-10 21:19:32 +0900830 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900831 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700832
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700833 // The default WiFi request is a background request so that apps using WiFi are
834 // migrated to a better network (typically ethernet) when one comes up, instead
835 // of staying on WiFi forever.
836 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
837 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
838
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900839 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900840 mHandlerThread.start();
841 mHandler = new InternalHandler(mHandlerThread.getLooper());
842 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700843
Jeremy Joslin79294842014-12-03 17:15:28 -0800844 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
845 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
846
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900847 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900848
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700849 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800850 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800851 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700852 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900853 mPolicyManagerInternal = checkNotNull(
854 LocalServices.getService(NetworkPolicyManagerInternal.class),
855 "missing NetworkPolicyManagerInternal");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000856 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900857
Luke Huang674660f2018-09-27 19:33:11 +0800858 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700859 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700860 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700861
junyulai05986c62018-08-07 19:50:45 +0800862 // To ensure uid rules are synchronized with Network Policy, register for
863 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
864 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700865 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900866 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700867 } catch (RemoteException e) {
868 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700869 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700870 }
871
872 final PowerManager powerManager = (PowerManager) context.getSystemService(
873 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700874 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
875 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
876 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800877 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700878
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700879 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700880
Wink Saville51f456f2013-04-23 14:26:51 -0700881 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900882 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700883 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700884 String[] naStrings = context.getResources().getStringArray(
885 com.android.internal.R.array.networkAttributes);
886 for (String naString : naStrings) {
887 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700888 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700889 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700890 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800891 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700892 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700893 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700894 }
Wink Saville51f456f2013-04-23 14:26:51 -0700895 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
896 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
897 n.type);
898 continue;
899 }
Wink Saville975c8482011-04-07 14:23:45 -0700900 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800901 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700902 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700903 continue;
904 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700905 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700906
Wink Saville975c8482011-04-07 14:23:45 -0700907 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700908 mNetworksDefined++;
909 } catch(Exception e) {
910 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700911 }
912 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700913
914 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
915 if (mNetConfigs[TYPE_VPN] == null) {
916 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
917 // don't need to add TYPE_VPN to mNetConfigs.
918 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
919 mNetworksDefined++; // used only in the log() statement below.
920 }
921
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900922 // Do the same for Ethernet, since it's often not specified in the configs, although many
923 // devices can use it via USB host adapters.
924 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
925 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
926 mNetworksDefined++;
927 }
928
Wink Saville5e56bc52013-07-29 15:00:57 -0700929 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700930
Robert Greenwalt50393202011-06-21 17:26:14 -0700931 mProtectedNetworks = new ArrayList<Integer>();
932 int[] protectedNetworks = context.getResources().getIntArray(
933 com.android.internal.R.array.config_protectedNetworks);
934 for (int p : protectedNetworks) {
935 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
936 mProtectedNetworks.add(p);
937 } else {
938 if (DBG) loge("Ignoring protectedNetwork " + p);
939 }
940 }
941
Erik Kline47222fc2017-04-30 19:36:15 +0900942 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800943
Luke Huang4e25ec62018-09-27 16:58:23 +0800944 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700945
Varun Anand4fa80e82019-02-06 10:13:38 -0800946 // Set up the listener for user state for creating user VPNs.
947 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700948 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100949 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700950 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700951 intentFilter.addAction(Intent.ACTION_USER_ADDED);
952 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000953 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700954 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800955 mIntentReceiver,
956 UserHandle.ALL,
957 intentFilter,
958 null /* broadcastPermission */,
959 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000960 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
961 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900962
junyulai2454b692018-11-01 17:16:31 +0800963 // Listen to package add and removal events for all users.
964 intentFilter = new IntentFilter();
965 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800966 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800967 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
968 intentFilter.addDataScheme("package");
969 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800970 mIntentReceiver,
971 UserHandle.ALL,
972 intentFilter,
973 null /* broadcastPermission */,
974 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800975
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700976 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800977 mNMS.registerObserver(mTethering);
978 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700979 } catch (RemoteException e) {
980 loge("Error registering observer :" + e);
981 }
982
Erik Klineda4bfa82015-04-30 12:58:40 +0900983 mSettingsObserver = new SettingsObserver(mContext, mHandler);
984 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800985
Chalard Jean4133a122018-06-04 13:33:12 +0900986 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
987 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400988
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400989 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900990
991 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900992 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
993 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900994
995 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
996 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
997 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
998 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
999 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1000 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1001 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09001002
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001003 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +09001004 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09001005 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +09001006
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001007 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
1008
Luke Huang4e25ec62018-09-27 16:58:23 +08001009 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001010 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001012
Mike Yuf9729752018-08-17 15:22:05 +08001013 @VisibleForTesting
1014 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001015 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001016 final TetheringDependencies deps = new TetheringDependencies() {
1017 @Override
1018 public boolean isTetheringSupported() {
1019 return ConnectivityService.this.isTetheringSupported();
1020 }
Erik Kline72302902018-06-14 17:36:40 +09001021 @Override
1022 public NetworkRequest getDefaultNetworkRequest() {
1023 return mDefaultRequest;
1024 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001025 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001026 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001027 IoThread.get().getLooper(), new MockableSystemProperties(),
1028 deps);
1029 }
1030
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001031 @VisibleForTesting
1032 protected ProxyTracker makeProxyTracker() {
1033 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1034 }
1035
Chalard Jean26400492018-04-18 20:18:38 +09001036 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1037 final NetworkCapabilities netCap = new NetworkCapabilities();
1038 netCap.addCapability(NET_CAPABILITY_INTERNET);
1039 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1040 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1041 netCap.setSingleUid(uid);
1042 return netCap;
1043 }
1044
Chalard Jeandda156a2018-01-10 21:19:32 +09001045 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001046 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001047 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001048 netCap.addCapability(NET_CAPABILITY_INTERNET);
1049 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001050 if (transportType > -1) {
1051 netCap.addTransportType(transportType);
1052 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001053 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001054 }
1055
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001056 // Used only for testing.
1057 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001058 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001059 // changing ContentResolver to make registerContentObserver non-final).
1060 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1061 // by subclassing SettingsObserver.
1062 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001063 void updateAlwaysOnNetworks() {
1064 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001065 }
1066
Erik Kline736353a2018-03-21 07:18:33 -07001067 // See FakeSettingsProvider comment above.
1068 @VisibleForTesting
1069 void updatePrivateDnsSettings() {
1070 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1071 }
1072
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001073 private void handleAlwaysOnNetworkRequest(
1074 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001075 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001076 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1077 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001078 if (enable == isEnabled) {
1079 return; // Nothing to do.
1080 }
1081
1082 if (enable) {
1083 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001084 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001085 } else {
Etan Cohenae574a82019-01-08 12:09:18 -08001086 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1087 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001088 }
1089 }
1090
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001091 private void handleConfigureAlwaysOnNetworks() {
1092 handleAlwaysOnNetworkRequest(
1093 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1094 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1095 false);
1096 }
1097
Erik Klineda4bfa82015-04-30 12:58:40 +09001098 private void registerSettingsCallbacks() {
1099 // Watch for global HTTP proxy changes.
1100 mSettingsObserver.observe(
1101 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1102 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1103
1104 // Watch for whether or not to keep mobile data always on.
1105 mSettingsObserver.observe(
1106 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001107 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1108
1109 // Watch for whether or not to keep wifi always on.
1110 mSettingsObserver.observe(
1111 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1112 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001113 }
1114
Erik Klinea24d4592018-01-11 21:07:29 +09001115 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001116 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1117 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001118 }
1119 }
1120
Robert Greenwalt34524f02014-05-18 16:22:10 -07001121 private synchronized int nextNetworkRequestId() {
1122 return mNextNetworkRequestId++;
1123 }
1124
Paul Jensen67b0b072015-06-10 11:22:17 -04001125 @VisibleForTesting
1126 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001127 synchronized (mNetworkForNetId) {
1128 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1129 int netId = mNextNetId;
1130 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1131 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001132 if (!mNetIdInUse.get(netId)) {
1133 mNetIdInUse.put(netId, true);
1134 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001135 }
1136 }
1137 }
1138 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001139 }
1140
Chalard Jeanc0982912018-06-07 16:11:34 +09001141 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001142 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001143 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1144 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001145 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001146 state = nai.getNetworkState();
1147 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001148 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001149 final NetworkInfo info = new NetworkInfo(networkType, 0,
1150 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001151 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1152 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001153 final NetworkCapabilities capabilities = new NetworkCapabilities();
1154 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1155 !info.isRoaming());
1156 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001157 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001159 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 return state;
1161 } else {
1162 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001163 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001164 }
1165
junyulai4a192e22018-06-13 15:00:37 +08001166 @VisibleForTesting
1167 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 if (network == null) {
1169 return null;
1170 }
Erik Kline736353a2018-03-21 07:18:33 -07001171 return getNetworkAgentInfoForNetId(network.netId);
1172 }
1173
1174 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001176 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001180 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001181 synchronized (mVpns) {
1182 if (!mLockdownEnabled) {
1183 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001184 Vpn vpn = mVpns.get(user);
1185 if (vpn != null && vpn.appliesToUid(uid)) {
1186 return vpn.getUnderlyingNetworks();
1187 }
1188 }
1189 }
1190 return null;
1191 }
1192
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001194 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001195
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001196 final Network[] networks = getVpnUnderlyingNetworks(uid);
1197 if (networks != null) {
1198 // getUnderlyingNetworks() returns:
1199 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1200 // empty array => the VPN explicitly said "no default network".
1201 // non-empty array => the VPN specified one or more default networks; we use the
1202 // first one.
1203 if (networks.length > 0) {
1204 nai = getNetworkAgentInfoForNetwork(networks[0]);
1205 } else {
1206 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001207 }
1208 }
1209
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001211 return nai.getNetworkState();
1212 } else {
1213 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001215 }
1216
1217 /**
1218 * Check if UID should be blocked from using the network with the given LinkProperties.
1219 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001220 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1221 boolean ignoreBlocked) {
1222 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001223 if (ignoreBlocked) {
1224 return false;
1225 }
Robin Lee17e61832016-05-09 13:46:28 +01001226 synchronized (mVpns) {
1227 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001228 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001229 return true;
1230 }
1231 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001232 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001233 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001234 }
1235
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001236 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001237 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1238 return;
1239 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001240 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001241 synchronized (mBlockedAppUids) {
1242 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001243 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001244 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001245 blocked = false;
1246 } else {
1247 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001248 }
1249 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001250 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1251 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1252 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001253 }
1254
junyulai05986c62018-08-07 19:50:45 +08001255 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1256 boolean blocked) {
1257 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1258 return;
1259 }
1260 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1261 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1262 nri.mUid, nri.request.requestId, net.netId));
1263 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1264 }
1265
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001266 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001267 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1268 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001269 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001270 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001271 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001272 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1273
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001274 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001275 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001276 }
Hugo Benichi69744342017-11-27 10:57:16 +09001277 synchronized (mVpns) {
1278 if (mLockdownTracker != null) {
1279 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1280 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001281 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001282 }
1283
1284 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 * Return NetworkInfo for the active (i.e., connected) network interface.
1286 * It is assumed that at most one network is active at a time. If more
1287 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001288 * @return the info for the active network, or {@code null} if none is
1289 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001291 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001293 enforceAccessPermission();
1294 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001295 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001296 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001297 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1298 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300
Paul Jensen31a94f42015-02-13 14:18:39 -05001301 @Override
1302 public Network getActiveNetwork() {
1303 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001304 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001305 }
1306
1307 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001308 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001309 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001310 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001311 }
1312
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001313 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001314 final int user = UserHandle.getUserId(uid);
1315 int vpnNetId = NETID_UNSET;
1316 synchronized (mVpns) {
1317 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001318 // TODO : now that capabilities contain the UID, the appliesToUid test should
1319 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001320 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1321 }
1322 NetworkAgentInfo nai;
1323 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001324 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001325 if (nai != null) {
1326 final NetworkCapabilities requiredCaps =
1327 createDefaultNetworkCapabilitiesForUid(uid);
1328 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1329 return nai.network;
1330 }
1331 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001332 }
1333 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001334 if (nai != null
1335 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1336 nai = null;
1337 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001338 return nai != null ? nai.network : null;
1339 }
1340
Lorenzo Colitti18660282016-07-04 12:55:44 +09001341 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001342 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1343 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001344 final int uid = Binder.getCallingUid();
1345 NetworkState state = getUnfilteredActiveNetworkState(uid);
1346 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001347 }
1348
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001349 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001350 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001351 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001352 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001353 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001354 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 }
1356
1357 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 public NetworkInfo getNetworkInfo(int networkType) {
1359 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001361 if (getVpnUnderlyingNetworks(uid) != null) {
1362 // A VPN is active, so we may need to return one of its underlying networks. This
1363 // information is not available in LegacyTypeTracker, so we have to get it from
1364 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001365 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001366 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001367 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001368 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001369 }
1370 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001371 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001372 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001375 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001376 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001377 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001378 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001379 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001380 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001381 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001382 return state.networkInfo;
1383 } else {
1384 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001385 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001386 }
1387
1388 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 public NetworkInfo[] getAllNetworkInfo() {
1390 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001391 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001392 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1393 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001394 NetworkInfo info = getNetworkInfo(networkType);
1395 if (info != null) {
1396 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001399 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001402 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001403 public Network getNetworkForType(int networkType) {
1404 enforceAccessPermission();
1405 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001406 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001407 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001408 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001409 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001410 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001411 }
1412
1413 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001414 public Network[] getAllNetworks() {
1415 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001416 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001417 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001418 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001419 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001420 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001421 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001422 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001423 }
1424
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001425 @Override
1426 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1427 // The basic principle is: if an app's traffic could possibly go over a
1428 // network, without the app doing anything multinetwork-specific,
1429 // (hence, by "default"), then include that network's capabilities in
1430 // the array.
1431 //
1432 // In the normal case, app traffic only goes over the system's default
1433 // network connection, so that's the only network returned.
1434 //
1435 // With a VPN in force, some app traffic may go into the VPN, and thus
1436 // over whatever underlying networks the VPN specifies, while other app
1437 // traffic may go over the system default network (e.g.: a split-tunnel
1438 // VPN, or an app disallowed by the VPN), so the set of networks
1439 // returned includes the VPN's underlying networks and the system
1440 // default.
1441 enforceAccessPermission();
1442
Chalard Jean4133a122018-06-04 13:33:12 +09001443 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001444
1445 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001446 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001447 if (nc != null) {
1448 result.put(nai.network, nc);
1449 }
1450
Hugo Benichi69744342017-11-27 10:57:16 +09001451 synchronized (mVpns) {
1452 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001453 Vpn vpn = mVpns.get(userId);
1454 if (vpn != null) {
1455 Network[] networks = vpn.getUnderlyingNetworks();
1456 if (networks != null) {
1457 for (Network network : networks) {
1458 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001459 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001460 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001461 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001462 }
1463 }
1464 }
1465 }
1466 }
1467 }
1468
1469 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1470 out = result.values().toArray(out);
1471 return out;
1472 }
1473
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001474 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001475 public boolean isNetworkSupported(int networkType) {
1476 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001477 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001478 }
1479
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001480 /**
1481 * Return LinkProperties for the active (i.e., connected) default
1482 * network interface. It is assumed that at most one default network
1483 * is active at a time. If more than one is active, it is indeterminate
1484 * which will be returned.
1485 * @return the ip properties for the active network, or {@code null} if
1486 * none is active
1487 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001488 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001489 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001490 enforceAccessPermission();
1491 final int uid = Binder.getCallingUid();
1492 NetworkState state = getUnfilteredActiveNetworkState(uid);
1493 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001494 }
1495
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001497 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001498 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001499 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1500 if (nai != null) {
1501 synchronized (nai) {
1502 return new LinkProperties(nai.linkProperties);
1503 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001504 }
1505 return null;
1506 }
1507
Robert Greenwalt12e67352014-05-13 21:41:06 -07001508 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001509 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001510 public LinkProperties getLinkProperties(Network network) {
1511 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001512 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1513 }
1514
1515 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1516 if (nai == null) {
1517 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001518 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001519 synchronized (nai) {
1520 return new LinkProperties(nai.linkProperties);
1521 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001522 }
1523
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001524 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001525 if (nai != null) {
1526 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001527 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001528 return networkCapabilitiesRestrictedForCallerPermissions(
1529 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001530 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001531 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001532 }
1533 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001534 return null;
1535 }
1536
1537 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001538 public NetworkCapabilities getNetworkCapabilities(Network network) {
1539 enforceAccessPermission();
1540 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1541 }
1542
Chalard Jeanb03a6222018-04-11 21:09:10 +09001543 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001544 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001545 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001546 if (!checkSettingsPermission(callerPid, callerUid)) {
1547 newNc.setUids(null);
1548 newNc.setSSID(null);
1549 }
Etan Cohen836ad572018-12-30 17:59:59 -08001550 if (newNc.getNetworkSpecifier() != null) {
1551 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1552 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001553 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001554 }
1555
Chalard Jeanb552c462018-02-21 18:43:54 +09001556 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1557 if (!checkSettingsPermission()) {
1558 nc.setSingleUid(Binder.getCallingUid());
1559 }
1560 }
1561
Chalard Jean26aa91a2018-03-20 19:13:57 +09001562 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1563 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1564 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1565 }
1566 }
1567
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001568 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001569 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001570 // Require internal since we're handing out IMSI details
1571 enforceConnectivityInternalPermission();
1572
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001573 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001574 for (Network network : getAllNetworks()) {
1575 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1576 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001577 // TODO (b/73321673) : NetworkState contains a copy of the
1578 // NetworkCapabilities, which may contain UIDs of apps to which the
1579 // network applies. Should the UIDs be cleared so as not to leak or
1580 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001581 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001582 }
1583 }
1584 return result.toArray(new NetworkState[result.size()]);
1585 }
1586
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001587 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001588 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001589 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001590 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1591 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1592 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001593 }
1594
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001595 @Override
1596 public boolean isActiveNetworkMetered() {
1597 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001598
Varun Anandc51b06d2019-02-25 17:22:02 -08001599 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001600 if (caps != null) {
1601 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1602 } else {
1603 // Always return the most conservative value
1604 return true;
1605 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001606 }
1607
Jeff Sharkey216c1812012-08-05 14:29:23 -07001608 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1609 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001610 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001611 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001612 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001613 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001614 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001615
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001616 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001617 * Ensures that the system cannot call a particular method.
1618 */
1619 private boolean disallowedBecauseSystemCaller() {
1620 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1621 // requestRouteToHost.
1622 if (isSystem(Binder.getCallingUid())) {
1623 log("This method exists only for app backwards compatibility"
1624 + " and must not be called by system services.");
1625 return true;
1626 }
1627 return false;
1628 }
1629
1630 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 * Ensure that a network route exists to deliver traffic to the specified
1632 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001633 * @param networkType the type of the network over which traffic to the
1634 * specified host is to be routed
1635 * @param hostAddress the IP address of the host to which the route is
1636 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 * @return {@code true} on success, {@code false} on failure
1638 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001639 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001640 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001641 if (disallowedBecauseSystemCaller()) {
1642 return false;
1643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001645 if (mProtectedNetworks.contains(networkType)) {
1646 enforceConnectivityInternalPermission();
1647 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001648
Chad Brubakerc0234532014-02-14 13:24:29 -08001649 InetAddress addr;
1650 try {
1651 addr = InetAddress.getByAddress(hostAddress);
1652 } catch (UnknownHostException e) {
1653 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1654 return false;
1655 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001658 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 return false;
1660 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001661
1662 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1663 if (nai == null) {
1664 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1665 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1666 } else {
1667 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1668 }
1669 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001670 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001671
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001672 DetailedState netState;
1673 synchronized (nai) {
1674 netState = nai.networkInfo.getDetailedState();
1675 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001676
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001677 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001678 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001679 log("requestRouteToHostAddress on down network "
1680 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001681 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001682 }
1683 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001685
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001686 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001687 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001688 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001689 LinkProperties lp;
1690 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001691 synchronized (nai) {
1692 lp = nai.linkProperties;
1693 netId = nai.network.netId;
1694 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001695 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001696 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1697 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001698 } finally {
1699 Binder.restoreCallingIdentity(token);
1700 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001701 }
1702
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001703 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001704 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001705 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001706 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001707 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001708 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001709 if (bestRoute.getGateway().equals(addr)) {
1710 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001711 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001712 } else {
1713 // if we will connect to this through another route, add a direct route
1714 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001715 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001716 }
1717 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001718 if (DBG) log("Adding legacy route " + bestRoute +
1719 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001720 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001721 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001722 } catch (Exception e) {
1723 // never crash - catch them all
1724 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001725 return false;
1726 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001727 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729
dalyk7301aa42018-03-05 12:42:22 -05001730 @VisibleForTesting
1731 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1732 @Override
1733 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1734 String hostname, boolean validated) {
1735 try {
1736 mHandler.sendMessage(mHandler.obtainMessage(
1737 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1738 new PrivateDnsValidationUpdate(netId,
1739 InetAddress.parseNumericAddress(ipAddress),
1740 hostname, validated)));
1741 } catch (IllegalArgumentException e) {
1742 loge("Error parsing ip address in validation event");
1743 }
1744 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001745
1746 @Override
1747 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1748 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1749 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1750 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1751 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1752 // event callback for certain nai. e.g. cellular. Register here to pass to
1753 // NetworkMonitor instead.
1754 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1755 // registerNetworkAgent to have NetworkMonitor created with system process as design
1756 // expectation. Also, NetdEventListenerService only allow one callback from each
1757 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1758 // NetworkMonitor registrants.
1759 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001760 try {
1761 nai.networkMonitor().notifyDnsResponse(returnCode);
1762 } catch (RemoteException e) {
1763 e.rethrowFromSystemServer();
1764 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001765 }
1766 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001767
1768 @Override
1769 public void onNat64PrefixEvent(int netId, boolean added,
1770 String prefixString, int prefixLength) {
1771 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1772 }
dalyk7301aa42018-03-05 12:42:22 -05001773 };
1774
1775 @VisibleForTesting
1776 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001777 final IIpConnectivityMetrics ipConnectivityMetrics =
1778 IIpConnectivityMetrics.Stub.asInterface(
1779 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1780 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001781 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001782 return;
dalyk7301aa42018-03-05 12:42:22 -05001783 }
1784
1785 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001786 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001787 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1788 mNetdEventCallback);
1789 } catch (Exception e) {
1790 loge("Error registering netd callback: " + e);
1791 }
1792 }
1793
Jeff Sharkey75d31892018-01-18 22:01:59 +09001794 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001795 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001796 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001797 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001798 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001799 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001800 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001801 // caller is NPMS, since we only register with them
1802 if (LOGD_BLOCKED_NETWORKINFO) {
1803 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1804 }
1805 mHandler.sendMessage(mHandler.obtainMessage(
1806 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1807
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001808 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001809 if (restrictBackground) {
1810 log("onRestrictBackgroundChanged(true): disabling tethering");
1811 mTethering.untetherAll();
1812 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001813 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001814 };
1815
junyulai05986c62018-08-07 19:50:45 +08001816 void handleUidRulesChanged(int uid, int newRules) {
1817 // skip update when we've already applied rules
1818 final int oldRules = mUidRules.get(uid, RULE_NONE);
1819 if (oldRules == newRules) return;
1820
1821 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1822
1823 if (newRules == RULE_NONE) {
1824 mUidRules.delete(uid);
1825 } else {
1826 mUidRules.put(uid, newRules);
1827 }
1828 }
1829
1830 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1831 if (mRestrictBackground == restrictBackground) return;
1832
1833 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1834 final boolean curMetered = nai.networkCapabilities.isMetered();
1835 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1836 restrictBackground);
1837 }
1838
1839 mRestrictBackground = restrictBackground;
1840 }
1841
1842 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1843 boolean isBackgroundRestricted) {
1844 synchronized (mVpns) {
1845 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1846 // Because the return value of this function depends on the list of UIDs the
1847 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1848 // list all state depending on the return value of this function has to be recomputed.
1849 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1850 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001851 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001852 return true;
1853 }
1854 }
1855
1856 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1857 isNetworkMetered, isBackgroundRestricted);
1858 }
1859
Robin Lee3b3dd942015-05-12 18:14:58 +01001860 /**
1861 * Require that the caller is either in the same user or has appropriate permission to interact
1862 * across users.
1863 *
1864 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1865 */
1866 private void enforceCrossUserPermission(int userId) {
1867 if (userId == UserHandle.getCallingUserId()) {
1868 // Not a cross-user call.
1869 return;
1870 }
1871 mContext.enforceCallingOrSelfPermission(
1872 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1873 "ConnectivityService");
1874 }
1875
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001876 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001877 for (String permission : permissions) {
1878 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001879 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001880 }
1881 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001882 return false;
1883 }
1884
1885 private void enforceAnyPermissionOf(String... permissions) {
1886 if (!checkAnyPermissionOf(permissions)) {
1887 throw new SecurityException("Requires one of the following permissions: "
1888 + String.join(", ", permissions) + ".");
1889 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001890 }
1891
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001892 private void enforceInternetPermission() {
1893 mContext.enforceCallingOrSelfPermission(
1894 android.Manifest.permission.INTERNET,
1895 "ConnectivityService");
1896 }
1897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001899 mContext.enforceCallingOrSelfPermission(
1900 android.Manifest.permission.ACCESS_NETWORK_STATE,
1901 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
1904 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001905 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907
Charles He36738632017-05-15 17:07:18 +01001908 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001909 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001910 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001911 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001912 }
1913
Chalard Jeanb552c462018-02-21 18:43:54 +09001914 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001915 return checkAnyPermissionOf(
1916 android.Manifest.permission.NETWORK_SETTINGS,
1917 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001918 }
1919
1920 private boolean checkSettingsPermission(int pid, int uid) {
1921 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001922 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1923 || PERMISSION_GRANTED == mContext.checkPermission(
1924 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001925 }
1926
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001927 private void enforceTetherAccessPermission() {
1928 mContext.enforceCallingOrSelfPermission(
1929 android.Manifest.permission.ACCESS_NETWORK_STATE,
1930 "ConnectivityService");
1931 }
1932
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001933 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001934 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001935 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001936 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001937 }
1938
Pavel Grafova462bcb2019-01-25 08:50:06 +00001939 private void enforceControlAlwaysOnVpnPermission() {
1940 mContext.enforceCallingOrSelfPermission(
1941 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1942 "ConnectivityService");
1943 }
1944
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001945 private void enforceNetworkStackSettingsOrSetup() {
1946 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001947 android.Manifest.permission.NETWORK_SETTINGS,
1948 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001949 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001950 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001951 }
1952
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001953 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001954 return checkAnyPermissionOf(
1955 android.Manifest.permission.NETWORK_STACK,
1956 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001957 }
1958
Hugo Benichi514da602016-07-19 15:59:27 +09001959 private void enforceConnectivityRestrictedNetworksPermission() {
1960 try {
1961 mContext.enforceCallingOrSelfPermission(
1962 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1963 "ConnectivityService");
1964 return;
1965 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1966 enforceConnectivityInternalPermission();
1967 }
1968
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001969 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001970 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001971 }
1972
Lorenzo Colitti18660282016-07-04 12:55:44 +09001973 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001974 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001975 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001976 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001977 }
1978
1979 private void sendInetConditionBroadcast(NetworkInfo info) {
1980 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1981 }
1982
Wink Saville628b0852011-08-04 15:01:58 -07001983 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001984 synchronized (mVpns) {
1985 if (mLockdownTracker != null) {
1986 info = new NetworkInfo(info);
1987 mLockdownTracker.augmentNetworkInfo(info);
1988 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001989 }
1990
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001991 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001992 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001993 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 if (info.isFailover()) {
1995 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1996 info.setFailover(false);
1997 }
1998 if (info.getReason() != null) {
1999 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2000 }
2001 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002002 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2003 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002005 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07002006 return intent;
2007 }
2008
2009 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2010 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2011 }
2012
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002013 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002014 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2015 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2016 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002017 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002018 final long ident = Binder.clearCallingIdentity();
2019 try {
2020 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2021 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002025 }
2026
Mike Lockwood0f79b542009-08-14 14:18:49 -04002027 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002028 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002029 if (!mSystemReady
2030 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002031 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002032 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002033 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002034 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002035 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002036 }
2037
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002038 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002039 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002040 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002041 final NetworkInfo ni = intent.getParcelableExtra(
2042 ConnectivityManager.EXTRA_NETWORK_INFO);
2043 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2044 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2045 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002046 } else {
2047 BroadcastOptions opts = BroadcastOptions.makeBasic();
2048 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2049 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002050 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002051 final IBatteryStats bs = BatteryStatsService.getService();
2052 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002053 bs.noteConnectivityChanged(intent.getIntExtra(
2054 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002055 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002056 } catch (RemoteException e) {
2057 }
Chad Brubakerac925012018-03-08 10:37:09 -08002058 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002059 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002060 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002061 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002062 } finally {
2063 Binder.restoreCallingIdentity(ident);
2064 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002065 }
2066 }
2067
2068 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002069 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002070 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002071 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002072
Hugo Benichi20035e02017-04-26 14:53:28 +09002073 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002074 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002075 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002076 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002077 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002078 }
2079 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002080
Robin Lee244ce8e2016-01-05 18:03:46 +00002081 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2082 // for user to unlock device too.
2083 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002084
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002085 // Create network requests for always-on networks.
2086 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002087
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002088 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002089
2090 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002094 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002095 *
2096 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002097 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002098 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2100 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002101
2102 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002104
Robert Greenwalt7b816022014-04-18 15:25:25 -07002105 if (networkAgent.networkCapabilities.hasTransport(
2106 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002107 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2108 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002109 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002110 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 } else if (networkAgent.networkCapabilities.hasTransport(
2112 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002113 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2114 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002115 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002117 } else {
2118 // do not track any other networks
2119 timeout = 0;
2120 }
2121
Robert Greenwalt7b816022014-04-18 15:25:25 -07002122 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002123 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002124 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002125 } catch (Exception e) {
2126 // You shall not crash!
2127 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002128 }
2129 }
2130 }
2131
2132 /**
2133 * Remove data activity tracking when network disconnects.
2134 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2136 final String iface = networkAgent.linkProperties.getInterfaceName();
2137 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002138
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2140 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002141 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002142 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002143 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002144 } catch (Exception e) {
2145 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002146 }
2147 }
2148 }
2149
2150 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002151 * Update data activity tracking when network state is updated.
2152 */
2153 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2154 NetworkAgentInfo oldNetwork) {
2155 if (newNetwork != null) {
2156 setupDataActivityTracking(newNetwork);
2157 }
2158 if (oldNetwork != null) {
2159 removeDataActivityTracking(oldNetwork);
2160 }
2161 }
2162 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002163 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002164 * and set it on it's iface.
2165 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2167 final String iface = newLp.getInterfaceName();
2168 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002169 if (oldLp == null && mtu == 0) {
2170 // Silently ignore unset MTU value.
2171 return;
2172 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2174 if (VDBG) log("identical MTU - not setting");
2175 return;
2176 }
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 }
junyulaie4135282019-01-03 18:50:15 +08002547 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2548 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002549 break;
2550 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002551 }
2552 }
2553
2554 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2555 switch (msg.what) {
2556 default:
2557 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002558 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002559 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002560 if (nai == null) break;
2561
lucasline252a742019-03-12 13:08:03 +08002562 final boolean partialConnectivity =
2563 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
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
2567 // go back to full connectivity without a disconnect.
lucaslin43338992019-03-20 18:21:59 +08002568 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002569 (partialConnectivity && !nai.partialConnectivity);
2570
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002571 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002572 final boolean wasValidated = nai.lastValidated;
2573 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002574 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2575 && valid) {
2576 nai.captivePortalLoginNotified = true;
2577 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2578 }
Erik Klinea24d4592018-01-11 21:07:29 +09002579
Erik Klinea24d4592018-01-11 21:07:29 +09002580 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2581
Erik Klinea24d4592018-01-11 21:07:29 +09002582 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002583 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2584 ? " with redirect to " + redirectUrl
2585 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002586 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2587 }
Erik Klinea24d4592018-01-11 21:07:29 +09002588 if (valid != nai.lastValidated) {
2589 if (wasDefault) {
2590 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2591 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002592 }
Erik Klinea24d4592018-01-11 21:07:29 +09002593 final int oldScore = nai.getCurrentScore();
2594 nai.lastValidated = valid;
2595 nai.everValidated |= valid;
2596 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2597 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2598 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002599 if (valid) {
2600 handleFreshlyValidatedNetwork(nai);
2601 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2602 // valid.
2603 mNotifier.clearNotification(nai.network.netId,
2604 NotificationType.NO_INTERNET);
2605 mNotifier.clearNotification(nai.network.netId,
2606 NotificationType.LOST_INTERNET);
2607 }
lucaslin43338992019-03-20 18:21:59 +08002608 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002609 nai.partialConnectivity = partialConnectivity;
2610 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002611 }
2612 updateInetCondition(nai);
2613 // Let the NetworkAgent know the state of its network
2614 Bundle redirectUrlBundle = new Bundle();
2615 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2616 nai.asyncChannel.sendMessage(
2617 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2618 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2619 0, redirectUrlBundle);
2620 if (wasValidated && !nai.lastValidated) {
2621 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002622 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002623 break;
2624 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002625 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002626 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002627 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002628 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002629 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002630 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002631 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002632 nai.lastCaptivePortalDetected = visible;
2633 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002634 if (visible) {
2635 nai.captivePortalLoginNotified = false;
2636 }
Calvin Onbe96da12016-10-11 15:10:46 -07002637 if (nai.lastCaptivePortalDetected &&
2638 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2639 if (DBG) log("Avoiding captive portal network: " + nai.name());
2640 nai.asyncChannel.sendMessage(
2641 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2642 teardownUnneededNetwork(nai);
2643 break;
2644 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002645 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002646 }
2647 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002648 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002649 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002650 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2651 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002652 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002653 if (nai == null) {
2654 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2655 break;
2656 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002657 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002658 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002659 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002660 }
Paul Jensen869868be2014-05-15 10:33:05 -04002661 }
Paul Jensen869868be2014-05-15 10:33:05 -04002662 break;
2663 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002664 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002665 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002666 if (nai == null) break;
2667
Erik Kline736353a2018-03-21 07:18:33 -07002668 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002669 break;
2670 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002671 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002672 return true;
2673 }
2674
Calvin Onbe96da12016-10-11 15:10:46 -07002675 private int getCaptivePortalMode() {
2676 return Settings.Global.getInt(mContext.getContentResolver(),
2677 Settings.Global.CAPTIVE_PORTAL_MODE,
2678 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2679 }
2680
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002681 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2682 switch (msg.what) {
2683 default:
2684 return false;
2685 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2686 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2687 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2688 handleLingerComplete(nai);
2689 }
2690 break;
2691 }
2692 }
2693 return true;
2694 }
2695
Etan Cohenae574a82019-01-08 12:09:18 -08002696 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2697 switch (msg.what) {
2698 default:
2699 return false;
2700 case NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2701 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2702 /* callOnUnavailable */ true);
2703 break;
2704 }
2705 }
2706 return true;
2707 }
2708
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002709 @Override
2710 public void handleMessage(Message msg) {
Etan Cohenae574a82019-01-08 12:09:18 -08002711 if (!maybeHandleAsyncChannelMessage(msg)
2712 && !maybeHandleNetworkMonitorMessage(msg)
2713 && !maybeHandleNetworkAgentInfoMessage(msg)
2714 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002715 maybeHandleNetworkAgentMessage(msg);
2716 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002717 }
2718 }
2719
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002720 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2721 private final NetworkAgentInfo mNai;
2722
2723 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2724 mNai = nai;
2725 }
2726
2727 @Override
2728 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2730 new Pair<>(mNai, networkMonitor)));
2731 }
2732
2733 @Override
2734 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2735 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2736 testResult, mNai.network.netId, redirectUrl));
2737 }
2738
2739 @Override
2740 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2741 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2742 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2743 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2744 }
2745
2746 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002747 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002748 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002749 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002750
2751 final PendingIntent pendingIntent;
2752 // Only the system server can register notifications with package "android"
2753 final long token = Binder.clearCallingIdentity();
2754 try {
2755 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2756 } finally {
2757 Binder.restoreCallingIdentity(token);
2758 }
2759 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2760 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2761 mNai.network.netId,
2762 pendingIntent));
2763 }
2764
2765 @Override
2766 public void hideProvisioningNotification() {
2767 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2768 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2769 mNai.network.netId));
2770 }
2771 }
2772
Erik Kline736353a2018-03-21 07:18:33 -07002773 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002774 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002775 }
2776
Erik Klinec6d00222018-06-26 18:53:43 +09002777 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2778 if (nai == null) return;
2779 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2780 // in order to restart a validation pass from within netd.
2781 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2782 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2783 updateDnses(nai.linkProperties, null, nai.network.netId);
2784 }
2785 }
2786
Erik Klinea24d4592018-01-11 21:07:29 +09002787 private void handlePrivateDnsSettingsChanged() {
2788 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2789
2790 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002791 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002792 if (networkRequiresValidation(nai)) {
2793 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2794 }
Erik Klinea24d4592018-01-11 21:07:29 +09002795 }
2796 }
2797
Erik Kline736353a2018-03-21 07:18:33 -07002798 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2799 // Private DNS only ever applies to networks that might provide
2800 // Internet access and therefore also require validation.
2801 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002802
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002803 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002804 // schedule DNS resolutions. If a DNS resolution is required the
2805 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002806 try {
2807 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2808 } catch (RemoteException e) {
2809 e.rethrowFromSystemServer();
2810 }
Erik Kline736353a2018-03-21 07:18:33 -07002811
2812 // With Private DNS bypass support, we can proceed to update the
2813 // Private DNS config immediately, even if we're in strict mode
2814 // and have not yet resolved the provider name into a set of IPs.
2815 updatePrivateDns(nai, cfg);
2816 }
2817
2818 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2819 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002820 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002821 }
2822
dalyk7301aa42018-03-05 12:42:22 -05002823 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2824 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2825 if (nai == null) {
2826 return;
2827 }
2828 mDnsManager.updatePrivateDnsValidation(update);
2829 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2830 }
2831
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002832 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2833 int prefixLength) {
2834 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2835 if (nai == null) return;
2836
2837 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2838 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2839
2840 IpPrefix prefix = null;
2841 if (added) {
2842 try {
2843 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2844 prefixLength);
2845 } catch (IllegalArgumentException e) {
2846 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2847 return;
2848 }
2849 }
2850
2851 nai.clatd.setNat64Prefix(prefix);
2852 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2853 }
2854
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002855 private void updateLingerState(NetworkAgentInfo nai, long now) {
2856 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2857 // 2. If the network was lingering and there are now requests, unlinger it.
2858 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2859 // one lingered request, start lingering.
2860 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002861 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002862 if (DBG) log("Unlingering " + nai.name());
2863 nai.unlinger();
2864 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002865 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002866 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002867 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002868 nai.linger();
2869 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2870 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2871 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002872 }
2873
Robert Greenwalt7b816022014-04-18 15:25:25 -07002874 private void handleAsyncChannelHalfConnect(Message msg) {
2875 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002876 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002877 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2878 if (VDBG) log("NetworkFactory connected");
Etan Cohenae574a82019-01-08 12:09:18 -08002879 // Finish setting up the full connection
2880 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2881 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002882 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002883 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002884 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002885 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002886 final int score;
2887 final int serial;
2888 if (nai != null) {
2889 score = nai.getCurrentScore();
2890 serial = nai.factorySerialNumber;
2891 } else {
2892 score = 0;
2893 serial = NetworkFactory.SerialNumber.NONE;
2894 }
2895 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2896 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002897 }
2898 } else {
2899 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002900 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002901 }
2902 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2903 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2904 if (VDBG) log("NetworkAgent connected");
2905 // A network agent has requested a connection. Establish the connection.
2906 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2907 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2908 } else {
2909 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002910 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002911 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002912 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002913 synchronized (mNetworkForNetId) {
2914 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002915 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002916 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002917 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002918 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002919 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002920 }
2921 }
2922 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002923
Chalard Jean392971c2018-05-11 20:19:20 +09002924 // This is a no-op if it's called with a message designating a network that has
2925 // already been destroyed, because its reference will not be found in the relevant
2926 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002927 private void handleAsyncChannelDisconnected(Message msg) {
2928 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2929 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002930 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002931 } else {
2932 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2933 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002934 }
2935 }
2936
Chalard Jean392971c2018-05-11 20:19:20 +09002937 // Destroys a network, remove references to it from the internal state managed by
2938 // ConnectivityService, free its interfaces and clean up.
2939 // Must be called on the Handler thread.
2940 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2941 if (DBG) {
2942 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2943 }
lucaslinf80b83b2019-02-12 15:30:13 +08002944 // Clear all notifications of this network.
2945 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002946 // A network agent has disconnected.
2947 // TODO - if we move the logic to the network agent (have them disconnect
2948 // because they lost all their requests or because their score isn't good)
2949 // then they would disconnect organically, report their new state and then
2950 // disconnect the channel.
2951 if (nai.networkInfo.isConnected()) {
2952 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2953 null, null);
2954 }
2955 final boolean wasDefault = isDefaultNetwork(nai);
2956 if (wasDefault) {
2957 mDefaultInetConditionPublished = 0;
2958 // Log default network disconnection before required book-keeping.
2959 // Let rematchAllNetworksAndRequests() below record a new default network event
2960 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2961 // whose timestamps tell how long it takes to recover a default network.
2962 long now = SystemClock.elapsedRealtime();
2963 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2964 }
2965 notifyIfacesChangedForNetworkStats();
2966 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2967 // by other networks that are already connected. Perhaps that can be done by
2968 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2969 // of rematchAllNetworksAndRequests
2970 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulaie4135282019-01-03 18:50:15 +08002971 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002972 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2973 // Disable wakeup packet monitoring for each interface.
2974 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2975 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002976 try {
2977 nai.networkMonitor().notifyNetworkDisconnected();
2978 } catch (RemoteException e) {
2979 e.rethrowFromSystemServer();
2980 }
Chalard Jean392971c2018-05-11 20:19:20 +09002981 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09002982 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09002983 synchronized (mNetworkForNetId) {
2984 // Remove the NetworkAgent, but don't mark the netId as
2985 // available until we've told netd to delete it below.
2986 mNetworkForNetId.remove(nai.network.netId);
2987 }
2988 // Remove all previously satisfied requests.
2989 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2990 NetworkRequest request = nai.requestAt(i);
2991 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2992 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2993 clearNetworkForRequest(request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09002994 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09002995 }
2996 }
2997 nai.clearLingerState();
2998 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002999 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09003000 notifyLockdownVpn(nai);
3001 ensureNetworkTransitionWakelock(nai.name());
3002 }
3003 mLegacyTypeTracker.remove(nai, wasDefault);
3004 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
3005 updateAllVpnsCapabilities();
3006 }
3007 rematchAllNetworksAndRequests(null, 0);
3008 mLingerMonitor.noteDisconnect(nai);
3009 if (nai.created) {
3010 // Tell netd to clean up the configuration for this network
3011 // (routing rules, DNS, etc).
3012 // This may be slow as it requires a lot of netd shelling out to ip and
3013 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3014 // after we've rematched networks with requests which should make a potential
3015 // fallback network the default or requested a new network from the
3016 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3017 // long time.
3018 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08003019 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003020 } catch (Exception e) {
3021 loge("Exception removing network: " + e);
3022 }
3023 mDnsManager.removeNetwork(nai.network);
3024 }
3025 synchronized (mNetworkForNetId) {
3026 mNetIdInUse.delete(nai.network.netId);
3027 }
3028 }
3029
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003030 // If this method proves to be too slow then we can maintain a separate
3031 // pendingIntent => NetworkRequestInfo map.
3032 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3033 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3034 Intent intent = pendingIntent.getIntent();
3035 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3036 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3037 if (existingPendingIntent != null &&
3038 existingPendingIntent.getIntent().filterEquals(intent)) {
3039 return entry.getValue();
3040 }
3041 }
3042 return null;
3043 }
3044
3045 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3046 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3047
3048 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3049 if (existingRequest != null) { // remove the existing request.
3050 if (DBG) log("Replacing " + existingRequest.request + " with "
3051 + nri.request + " because their intents matched.");
Etan Cohenae574a82019-01-08 12:09:18 -08003052 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3053 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003054 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003055 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003056 }
3057
Erik Klineda4bfa82015-04-30 12:58:40 +09003058 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003059 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003060 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003061 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003062 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003063 if (nri.request.networkCapabilities.hasSignalStrength() &&
3064 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3065 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003066 }
3067 }
3068 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003069 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003070 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean08577fc2018-05-02 21:14:54 +09003071 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003072 }
3073 }
3074
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003075 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3076 int callingUid) {
3077 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3078 if (nri != null) {
Etan Cohenae574a82019-01-08 12:09:18 -08003079 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003080 }
3081 }
3082
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003083 // Determines whether the network is the best (or could become the best, if it validated), for
3084 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3085 // on the value of reason:
3086 //
3087 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3088 // then it should be torn down.
3089 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3090 // then it should be lingered.
3091 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3092 final int numRequests;
3093 switch (reason) {
3094 case TEARDOWN:
3095 numRequests = nai.numRequestNetworkRequests();
3096 break;
3097 case LINGER:
3098 numRequests = nai.numForegroundNetworkRequests();
3099 break;
3100 default:
3101 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3102 return true;
3103 }
3104
3105 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003106 return false;
3107 }
Paul Jensene0988542015-06-25 15:30:08 -04003108 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003109 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3110 // Background requests don't affect lingering.
3111 continue;
3112 }
3113
Paul Jensene0988542015-06-25 15:30:08 -04003114 // If this Network is already the highest scoring Network for a request, or if
3115 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003116 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003117 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003118 // Note that this catches two important cases:
3119 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3120 // is currently satisfying the request. This is desirable when
3121 // cellular ends up validating but WiFi does not.
3122 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003123 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003124 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003125 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003126 nai.getCurrentScoreAsValidated())) {
3127 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003128 }
3129 }
Paul Jensene0988542015-06-25 15:30:08 -04003130 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003131 }
3132
Erik Klineacdd6392016-07-07 16:50:58 +09003133 private NetworkRequestInfo getNriForAppRequest(
3134 NetworkRequest request, int callingUid, String requestedOperation) {
3135 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3136
Robert Greenwalt9258c642014-03-26 16:47:06 -07003137 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003138 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003139 log(String.format("UID %d attempted to %s for unowned request %s",
3140 callingUid, requestedOperation, nri));
3141 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003142 }
Erik Klineacdd6392016-07-07 16:50:58 +09003143 }
3144
3145 return nri;
3146 }
3147
Erik Kline57faba92015-11-25 12:49:38 +09003148 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003149 if (mNetworkRequests.get(nri.request) == null) {
3150 return;
Erik Kline57faba92015-11-25 12:49:38 +09003151 }
Hugo Benichicd952782017-09-20 11:20:14 +09003152 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003153 return;
3154 }
3155 if (VDBG || (DBG && nri.request.isRequest())) {
3156 log("releasing " + nri.request + " (timeout)");
3157 }
3158 handleRemoveNetworkRequest(nri);
3159 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003160 }
3161
Etan Cohenae574a82019-01-08 12:09:18 -08003162 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3163 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003164 final NetworkRequestInfo nri =
3165 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3166 if (nri == null) {
3167 return;
Erik Kline57faba92015-11-25 12:49:38 +09003168 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003169 if (VDBG || (DBG && nri.request.isRequest())) {
3170 log("releasing " + nri.request + " (release request)");
3171 }
3172 handleRemoveNetworkRequest(nri);
Etan Cohenae574a82019-01-08 12:09:18 -08003173 if (callOnUnavailable) {
3174 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3175 }
Erik Kline57faba92015-11-25 12:49:38 +09003176 }
Erik Klineacdd6392016-07-07 16:50:58 +09003177
Hugo Benichidba33db2017-03-23 22:40:44 +09003178 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003179 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003180 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003181
Erik Klineacdd6392016-07-07 16:50:58 +09003182 synchronized (mUidToNetworkRequestCount) {
3183 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3184 if (requests < 1) {
3185 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3186 nri.mUid);
3187 } else if (requests == 1) {
3188 mUidToNetworkRequestCount.removeAt(
3189 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3190 } else {
3191 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3192 }
3193 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003194
Erik Klineacdd6392016-07-07 16:50:58 +09003195 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3196 if (nri.request.isRequest()) {
3197 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003198 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003199 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003200 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003201 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003202 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003203 log(" Removing from current network " + nai.name() +
3204 ", leaving " + nai.numNetworkRequests() + " requests.");
3205 }
3206 // If there are still lingered requests on this network, don't tear it down,
3207 // but resume lingering instead.
3208 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003209 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003210 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3211 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003212 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003213 wasKept = true;
3214 }
Hugo Benichicd952782017-09-20 11:20:14 +09003215 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003216 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3217 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003218 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003219 }
Erik Klineacdd6392016-07-07 16:50:58 +09003220 }
3221
Erik Klineacdd6392016-07-07 16:50:58 +09003222 // Maintain the illusion. When this request arrived, we might have pretended
3223 // that a network connected to serve it, even though the network was already
3224 // connected. Now that this request has gone away, we might have to pretend
3225 // that the network disconnected. LegacyTypeTracker will generate that
3226 // phantom disconnect for this type.
3227 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3228 boolean doRemove = true;
3229 if (wasKept) {
3230 // check if any of the remaining requests for this network are for the
3231 // same legacy type - if so, don't remove the nai
3232 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3233 NetworkRequest otherRequest = nai.requestAt(i);
3234 if (otherRequest.legacyType == nri.request.legacyType &&
3235 otherRequest.isRequest()) {
3236 if (DBG) log(" still have other legacy request - leaving");
3237 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003238 }
3239 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003240 }
3241
Erik Klineacdd6392016-07-07 16:50:58 +09003242 if (doRemove) {
3243 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003244 }
3245 }
Erik Klineacdd6392016-07-07 16:50:58 +09003246
3247 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3248 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3249 nri.request);
3250 }
3251 } else {
3252 // listens don't have a singular affectedNetwork. Check all networks to see
3253 // if this listen request applies and remove it.
3254 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3255 nai.removeRequest(nri.request.requestId);
3256 if (nri.request.networkCapabilities.hasSignalStrength() &&
3257 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3258 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3259 }
3260 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003261 }
3262 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003263
Lorenzo Colitti18660282016-07-04 12:55:44 +09003264 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003265 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003266 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003267 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003268 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003269 }
3270
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003271 @Override
lucasline252a742019-03-12 13:08:03 +08003272 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3273 enforceNetworkStackSettingsOrSetup();
3274 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3275 encodeBool(accept), encodeBool(always), network));
3276 }
3277
3278 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003279 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003280 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003281 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3282 }
3283
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003284 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3285 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3286 " accept=" + accept + " always=" + always);
3287
3288 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3289 if (nai == null) {
3290 // Nothing to do.
3291 return;
3292 }
3293
3294 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003295 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003296 return;
3297 }
3298
3299 if (!nai.networkMisc.explicitlySelected) {
3300 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3301 }
3302
3303 if (accept != nai.networkMisc.acceptUnvalidated) {
3304 int oldScore = nai.getCurrentScore();
3305 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003306 // If network becomes partial connectivity and user already accepted to use this
3307 // network, we should respect the user's option and don't need to popup the
3308 // PARTIAL_CONNECTIVITY notification to user again.
3309 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003310 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003311 sendUpdatedScoreToFactories(nai);
3312 }
3313
3314 if (always) {
3315 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003316 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003317 }
3318
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003319 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003320 // Tell the NetworkAgent to not automatically reconnect to the network.
3321 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003322 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003323 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003324 }
3325
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003326 }
3327
lucasline252a742019-03-12 13:08:03 +08003328 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3329 boolean always) {
3330 if (DBG) {
3331 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3332 + " always=" + always);
3333 }
3334
3335 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3336 if (nai == null) {
3337 // Nothing to do.
3338 return;
3339 }
3340
3341 if (nai.lastValidated) {
3342 // The network validated while the dialog box was up. Take no action.
3343 return;
3344 }
3345
3346 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3347 nai.networkMisc.acceptPartialConnectivity = accept;
3348 }
3349
3350 // TODO: Use the current design or save the user choice into IpMemoryStore.
3351 if (always) {
3352 nai.asyncChannel.sendMessage(
3353 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3354 }
3355
3356 if (!accept) {
3357 // Tell the NetworkAgent to not automatically reconnect to the network.
3358 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3359 // Tear down the network.
3360 teardownUnneededNetwork(nai);
3361 } else {
lucaslin43338992019-03-20 18:21:59 +08003362 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3363 // result in a partial connectivity result which will be processed by
3364 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003365 try {
lucaslin43338992019-03-20 18:21:59 +08003366 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003367 } catch (RemoteException e) {
3368 e.rethrowFromSystemServer();
3369 }
3370 }
3371 }
3372
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003373 private void handleSetAvoidUnvalidated(Network network) {
3374 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3375 if (nai == null || nai.lastValidated) {
3376 // Nothing to do. The network either disconnected or revalidated.
3377 return;
3378 }
3379 if (!nai.avoidUnvalidated) {
3380 int oldScore = nai.getCurrentScore();
3381 nai.avoidUnvalidated = true;
3382 rematchAllNetworksAndRequests(nai, oldScore);
3383 sendUpdatedScoreToFactories(nai);
3384 }
3385 }
3386
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003387 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003388 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003389 mHandler.sendMessageDelayed(
3390 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3391 PROMPT_UNVALIDATED_DELAY_MS);
3392 }
3393
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003394 @Override
3395 public void startCaptivePortalApp(Network network) {
3396 enforceConnectivityInternalPermission();
3397 mHandler.post(() -> {
3398 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3399 if (nai == null) return;
3400 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003401 try {
3402 nai.networkMonitor().launchCaptivePortalApp();
3403 } catch (RemoteException e) {
3404 e.rethrowFromSystemServer();
3405 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003406 });
3407 }
3408
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003409 /**
3410 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3411 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003412 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003413 * @param appExtras Bundle to use as intent extras for the captive portal application.
3414 * Must be treated as opaque to avoid preventing the captive portal app to
3415 * update its arguments.
3416 */
3417 @Override
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003418 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003419 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3420
3421 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3422 appIntent.putExtras(appExtras);
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003423 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3424 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003425 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3426
3427 Binder.withCleanCallingIdentity(() ->
3428 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3429 }
3430
Remi NGUYEN VAN5a1b74b2019-02-13 20:58:59 +09003431 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3432 private final Network mNetwork;
3433
3434 private CaptivePortalImpl(Network network) {
3435 mNetwork = network;
3436 }
3437
3438 @Override
3439 public void appResponse(final int response) throws RemoteException {
3440 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3441 enforceSettingsPermission();
3442 }
3443
3444 // getNetworkAgentInfoForNetwork is thread-safe
3445 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3446 if (nai == null) return;
3447
3448 // nai.networkMonitor() is thread-safe
3449 final INetworkMonitor nm = nai.networkMonitor();
3450 if (nm == null) return;
3451
3452 final long token = Binder.clearCallingIdentity();
3453 try {
3454 nm.notifyCaptivePortalAppFinished(response);
3455 } finally {
3456 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3457 Binder.restoreCallingIdentity(token);
3458 }
3459 }
3460
3461 @Override
3462 public void logEvent(int eventId, String packageName) {
3463 enforceSettingsPermission();
3464
3465 new MetricsLogger().action(eventId, packageName);
3466 }
3467 }
3468
Hugo Benichic8e9e122016-09-14 23:23:08 +00003469 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003470 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003471 }
3472
Remi NGUYEN VAN24ec3ff2019-03-22 17:16:52 +09003473 /**
3474 * Return whether the device should maintain continuous, working connectivity by switching away
3475 * from WiFi networks having no connectivity.
3476 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
3477 */
3478 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003479 if (!checkNetworkStackPermission()) {
3480 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3481 }
3482 return avoidBadWifi();
3483 }
3484
3485
Erik Kline065ab6e2016-10-02 18:02:14 +09003486 private void rematchForAvoidBadWifiUpdate() {
3487 rematchAllNetworksAndRequests(null, 0);
3488 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3489 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3490 sendUpdatedScoreToFactories(nai);
3491 }
3492 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003493 }
3494
Erik Kline065ab6e2016-10-02 18:02:14 +09003495 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003496 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003497 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003498 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003499 if (!configRestrict) {
3500 pw.println("Bad Wi-Fi avoidance: unrestricted");
3501 return;
3502 }
3503
3504 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3505 pw.increaseIndent();
3506 pw.println("Config restrict: " + configRestrict);
3507
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003508 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003509 String description;
3510 // Can't use a switch statement because strings are legal case labels, but null is not.
3511 if ("0".equals(value)) {
3512 description = "get stuck";
3513 } else if (value == null) {
3514 description = "prompt";
3515 } else if ("1".equals(value)) {
3516 description = "avoid";
3517 } else {
3518 description = value + " (?)";
3519 }
3520 pw.println("User setting: " + description);
3521 pw.println("Network overrides:");
3522 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003523 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003524 if (nai.avoidUnvalidated) {
3525 pw.println(nai.name());
3526 }
3527 }
3528 pw.decreaseIndent();
3529 pw.decreaseIndent();
3530 }
3531
lucaslind2e045e02019-01-24 15:55:30 +08003532 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003533 final String action;
3534 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003535 case LOGGED_IN:
3536 action = Settings.ACTION_WIFI_SETTINGS;
3537 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3538 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3539 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3540 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003541 case NO_INTERNET:
3542 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3543 break;
3544 case LOST_INTERNET:
3545 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3546 break;
lucasline252a742019-03-12 13:08:03 +08003547 case PARTIAL_CONNECTIVITY:
3548 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3549 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003550 default:
3551 Slog.wtf(TAG, "Unknown notification type " + type);
3552 return;
3553 }
3554
3555 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003556 if (type != NotificationType.LOGGED_IN) {
3557 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3558 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3559 intent.setClassName("com.android.settings",
3560 "com.android.settings.wifi.WifiNoInternetDialog");
3561 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003562
3563 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3564 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3565 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3566 }
3567
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003568 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003569 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003570 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3571
lucasline252a742019-03-12 13:08:03 +08003572 // Only prompt if the network is unvalidated or network has partial internet connectivity
3573 // and was explicitly selected by the user, and if we haven't already been told to switch
3574 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3575 // because we're already prompting the user to sign in.
3576 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3577 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003578 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3579 // we should reevaluate how to handle acceptPartialConnectivity when network just
3580 // connected.
lucasline252a742019-03-12 13:08:03 +08003581 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003582 return;
3583 }
lucasline252a742019-03-12 13:08:03 +08003584 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3585 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3586 // popup the notification immediately when the network is partial connectivity.
3587 if (nai.partialConnectivity) {
3588 // Treat PARTIAL_CONNECTIVITY as NO_INTERNET temporary until Settings has been updated.
3589 // TODO: Need to change back to PARTIAL_CONNECTIVITY when Settings part is merged.
3590 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3591 } else {
3592 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3593 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003594 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003595
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003596 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3597 NetworkCapabilities nc = nai.networkCapabilities;
3598 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003599
lucasline252a742019-03-12 13:08:03 +08003600 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3601 return;
3602 }
3603
3604 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003605 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003606 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003607 }
3608
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003609 @Override
3610 public int getMultipathPreference(Network network) {
3611 enforceAccessPermission();
3612
3613 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003614 if (nai != null && nai.networkCapabilities
3615 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003616 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3617 }
3618
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003619 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3620 if (networkPreference != null) {
3621 return networkPreference;
3622 }
3623
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003624 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3625 }
3626
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003627 @Override
3628 public NetworkRequest getDefaultRequest() {
3629 return mDefaultRequest;
3630 }
3631
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003632 private class InternalHandler extends Handler {
3633 public InternalHandler(Looper looper) {
3634 super(looper);
3635 }
3636
3637 @Override
3638 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003639 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003640 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003641 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003642 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003643 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003644 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003645 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003646 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003647 break;
3648 }
Jason Monkdecd2952013-10-10 14:02:51 -04003649 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003650 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003651 break;
3652 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003653 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003654 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3655 break;
3656 }
3657 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3658 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003659 break;
3660 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003661 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003662 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3663 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3664 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003665 break;
3666 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003667 case EVENT_REGISTER_NETWORK_REQUEST:
3668 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003669 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003670 break;
3671 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003672 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3673 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003674 handleRegisterNetworkRequestWithIntent(msg);
3675 break;
3676 }
Erik Kline57faba92015-11-25 12:49:38 +09003677 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3678 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3679 handleTimedOutNetworkRequest(nri);
3680 break;
3681 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003682 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3683 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3684 break;
3685 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003686 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenae574a82019-01-08 12:09:18 -08003687 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3688 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003689 break;
3690 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003691 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003692 Network network = (Network) msg.obj;
3693 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003694 break;
3695 }
lucasline252a742019-03-12 13:08:03 +08003696 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3697 Network network = (Network) msg.obj;
3698 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3699 toBool(msg.arg2));
3700 break;
3701 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003702 case EVENT_SET_AVOID_UNVALIDATED: {
3703 handleSetAvoidUnvalidated((Network) msg.obj);
3704 break;
3705 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003706 case EVENT_PROMPT_UNVALIDATED: {
3707 handlePromptUnvalidated((Network) msg.obj);
3708 break;
3709 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003710 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3711 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003712 break;
3713 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003714 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003715 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003716 mKeepaliveTracker.handleStartKeepalive(msg);
3717 break;
3718 }
3719 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulaie4135282019-01-03 18:50:15 +08003720 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003721 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3722 int slot = msg.arg1;
3723 int reason = msg.arg2;
3724 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3725 break;
3726 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003727 case EVENT_SYSTEM_READY: {
3728 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003729 // Might have been called already in handleRegisterNetworkAgent since
3730 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3731 // this several times is fine.
3732 try {
3733 nai.networkMonitor().notifySystemReady();
3734 } catch (RemoteException e) {
3735 e.rethrowFromSystemServer();
3736 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003737 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003738 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003739 break;
3740 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003741 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003742 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003743 break;
3744 }
Erik Klinea24d4592018-01-11 21:07:29 +09003745 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3746 handlePrivateDnsSettingsChanged();
3747 break;
dalyk7301aa42018-03-05 12:42:22 -05003748 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3749 handlePrivateDnsValidationUpdate(
3750 (PrivateDnsValidationUpdate) msg.obj);
3751 break;
junyulai05986c62018-08-07 19:50:45 +08003752 case EVENT_UID_RULES_CHANGED:
3753 handleUidRulesChanged(msg.arg1, msg.arg2);
3754 break;
3755 case EVENT_DATA_SAVER_CHANGED:
3756 handleRestrictBackgroundChanged(toBool(msg.arg1));
3757 break;
lucaslind2e045e02019-01-24 15:55:30 +08003758 case EVENT_TIMEOUT_NOTIFICATION:
3759 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3760 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 }
3762 }
3763 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003764
3765 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003766 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003767 public int tether(String iface, String callerPkg) {
3768 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003769 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003770 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003771 } else {
3772 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3773 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003774 }
3775
3776 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003777 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003778 public int untether(String iface, String callerPkg) {
3779 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003780
3781 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003782 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003783 } else {
3784 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3785 }
3786 }
3787
3788 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003789 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003790 public int getLastTetherError(String iface) {
3791 enforceTetherAccessPermission();
3792
3793 if (isTetheringSupported()) {
3794 return mTethering.getLastTetherError(iface);
3795 } else {
3796 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3797 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003798 }
3799
3800 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003801 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003802 public String[] getTetherableUsbRegexs() {
3803 enforceTetherAccessPermission();
3804 if (isTetheringSupported()) {
3805 return mTethering.getTetherableUsbRegexs();
3806 } else {
3807 return new String[0];
3808 }
3809 }
3810
Lorenzo Colitti18660282016-07-04 12:55:44 +09003811 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003812 public String[] getTetherableWifiRegexs() {
3813 enforceTetherAccessPermission();
3814 if (isTetheringSupported()) {
3815 return mTethering.getTetherableWifiRegexs();
3816 } else {
3817 return new String[0];
3818 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003819 }
3820
Lorenzo Colitti18660282016-07-04 12:55:44 +09003821 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003822 public String[] getTetherableBluetoothRegexs() {
3823 enforceTetherAccessPermission();
3824 if (isTetheringSupported()) {
3825 return mTethering.getTetherableBluetoothRegexs();
3826 } else {
3827 return new String[0];
3828 }
3829 }
3830
Lorenzo Colitti18660282016-07-04 12:55:44 +09003831 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003832 public int setUsbTethering(boolean enable, String callerPkg) {
3833 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003834 if (isTetheringSupported()) {
3835 return mTethering.setUsbTethering(enable);
3836 } else {
3837 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3838 }
3839 }
3840
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003841 // TODO - move iface listing, queries, etc to new module
3842 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003843 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003844 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003845 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003846 return mTethering.getTetherableIfaces();
3847 }
3848
Lorenzo Colitti18660282016-07-04 12:55:44 +09003849 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003850 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003851 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003852 return mTethering.getTetheredIfaces();
3853 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003854
Lorenzo Colitti18660282016-07-04 12:55:44 +09003855 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003856 public String[] getTetheringErroredIfaces() {
3857 enforceTetherAccessPermission();
3858 return mTethering.getErroredIfaces();
3859 }
3860
Lorenzo Colitti18660282016-07-04 12:55:44 +09003861 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003862 public String[] getTetheredDhcpRanges() {
3863 enforceConnectivityInternalPermission();
3864 return mTethering.getTetheredDhcpRanges();
3865 }
3866
Udam Saini0e94c362017-06-07 12:06:28 -07003867 @Override
3868 public boolean isTetheringSupported(String callerPkg) {
3869 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3870 return isTetheringSupported();
3871 }
3872
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003873 // if ro.tether.denied = true we default to no tethering
3874 // gservices could set the secure setting to 1 though to enable it on a build where it
3875 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003876 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003877 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3878 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3879 Settings.Global.TETHER_SUPPORTED, defaultVal));
3880 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003881 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003882
3883 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3884 boolean adminUser = false;
3885 final long token = Binder.clearCallingIdentity();
3886 try {
3887 adminUser = mUserManager.isAdminUser();
3888 } finally {
3889 Binder.restoreCallingIdentity(token);
3890 }
3891
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003892 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003893 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003894
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003895 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003896 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3897 String callerPkg) {
3898 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003899 if (!isTetheringSupported()) {
3900 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3901 return;
3902 }
3903 mTethering.startTethering(type, receiver, showProvisioningUi);
3904 }
3905
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003906 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003907 public void stopTethering(int type, String callerPkg) {
3908 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003909 mTethering.stopTethering(type);
3910 }
3911
markchienf2731272019-01-16 17:44:13 +08003912 /**
3913 * Get the latest value of the tethering entitlement check.
3914 *
3915 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3916 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3917 * if it's really needed.
3918 */
3919 @Override
markchien9554abf2019-03-06 16:25:00 +08003920 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003921 boolean showEntitlementUi, String callerPkg) {
3922 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003923 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003924 }
3925
markchien6ea34542019-02-27 14:56:11 +08003926 /** Register tethering event callback. */
3927 @Override
3928 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3929 String callerPkg) {
3930 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3931 mTethering.registerTetheringEventCallback(callback);
3932 }
3933
3934 /** Unregister tethering event callback. */
3935 @Override
3936 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3937 String callerPkg) {
3938 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3939 mTethering.unregisterTetheringEventCallback(callback);
3940 }
3941
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003942 // Called when we lose the default network and have no replacement yet.
3943 // This will automatically be cleared after X seconds or a new default network
3944 // becomes CONNECTED, whichever happens first. The timer is started by the
3945 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003946 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003947 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003948 if (mNetTransitionWakeLock.isHeld()) {
3949 return;
3950 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003951 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003952 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3953 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003954 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003955 mWakelockLogs.log("ACQUIRE for " + forWhom);
3956 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3957 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003958 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003959
Hugo Benichi4c31b342017-03-30 23:18:10 +09003960 // Called when we gain a new default network to release the network transition wakelock in a
3961 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3962 // message is cancelled.
3963 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003964 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003965 if (!mNetTransitionWakeLock.isHeld()) {
3966 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003967 }
3968 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003969 // Cancel self timeout on wakelock hold.
3970 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3971 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3972 mHandler.sendMessageDelayed(msg, 1000);
3973 }
3974
3975 // Called when either message of ensureNetworkTransitionWakelock or
3976 // scheduleReleaseNetworkTransitionWakelock is processed.
3977 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3978 String event = eventName(eventId);
3979 synchronized (this) {
3980 if (!mNetTransitionWakeLock.isHeld()) {
3981 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3982 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3983 return;
3984 }
3985 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003986 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3987 mTotalWakelockDurationMs += lockDuration;
3988 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3989 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003990 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003991 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003992 }
3993
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003994 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003995 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003996 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003997 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003998 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003999 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07004000 }
4001
Lorenzo Colitti18660282016-07-04 12:55:44 +09004002 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04004003 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004004 enforceAccessPermission();
4005 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004006 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004007 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004008 mHandler.sendMessage(
4009 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4010 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004011
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004012 private void handleReportNetworkConnectivity(
4013 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004014 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004015 if (network == null) {
4016 nai = getDefaultNetwork();
4017 } else {
4018 nai = getNetworkAgentInfoForNetwork(network);
4019 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004020 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4021 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4022 return;
4023 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004024 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004025 if (hasConnectivity == nai.lastValidated) {
4026 return;
4027 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004028 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004029 int netid = nai.network.netId;
4030 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004031 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004032 // Validating a network that has not yet connected could result in a call to
4033 // rematchNetworkAndRequests() which is not meant to work on such networks.
4034 if (!nai.everConnected) {
4035 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004036 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004037 LinkProperties lp = getLinkProperties(nai);
4038 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4039 return;
4040 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004041 try {
4042 nai.networkMonitor().forceReevaluation(uid);
4043 } catch (RemoteException e) {
4044 e.rethrowFromSystemServer();
4045 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004046 }
4047
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004048 /**
4049 * Returns information about the proxy a certain network is using. If given a null network, it
4050 * it will return the proxy for the bound network for the caller app or the default proxy if
4051 * none.
4052 *
4053 * @param network the network we want to get the proxy information for.
4054 * @return Proxy information if a network has a proxy configured, or otherwise null.
4055 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004056 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004057 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004058 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004059 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004060 if (network == null) {
4061 // Get the network associated with the calling UID.
4062 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4063 true);
4064 if (activeNetwork == null) {
4065 return null;
4066 }
4067 return getLinkPropertiesProxyInfo(activeNetwork);
4068 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4069 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4070 // caller may not have.
4071 return getLinkPropertiesProxyInfo(network);
4072 }
4073 // No proxy info available if the calling UID does not have network access.
4074 return null;
4075 }
4076
4077 @VisibleForTesting
4078 protected boolean queryUserAccess(int uid, int netId) {
4079 return NetworkUtils.queryUserAccess(uid, netId);
4080 }
4081
4082 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004083 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4084 if (nai == null) return null;
4085 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004086 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4087 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004088 }
4089 }
4090
Chalard Jean3c443fc2018-06-07 18:37:59 +09004091 @Override
4092 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004093 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004094 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004095 }
4096
Chalard Jean5afbc832018-06-07 18:02:37 +09004097 @Override
4098 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004099 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004100 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004101 }
4102
Jason Monk207900c2014-04-25 15:00:09 -04004103 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004104 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004105 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004106 proxy = null;
4107 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004108 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004109 }
4110
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004111 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4112 // when any network changes proxy.
4113 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4114 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004115 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004116 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4117 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4118
Chalard Jean4949dd72018-06-07 17:41:29 +09004119 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004120 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004121 }
4122 }
4123
Robert Greenwalt434203a2010-10-11 16:00:27 -07004124 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004125 final private HashMap<Uri, Integer> mUriEventMap;
4126 final private Context mContext;
4127 final private Handler mHandler;
4128
4129 SettingsObserver(Context context, Handler handler) {
4130 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004131 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004132 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004133 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004134 }
4135
Erik Klineda4bfa82015-04-30 12:58:40 +09004136 void observe(Uri uri, int what) {
4137 mUriEventMap.put(uri, what);
4138 final ContentResolver resolver = mContext.getContentResolver();
4139 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004140 }
4141
4142 @Override
4143 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004144 Slog.wtf(TAG, "Should never be reached.");
4145 }
4146
4147 @Override
4148 public void onChange(boolean selfChange, Uri uri) {
4149 final Integer what = mUriEventMap.get(uri);
4150 if (what != null) {
4151 mHandler.obtainMessage(what.intValue()).sendToTarget();
4152 } else {
4153 loge("No matching event to send for URI=" + uri);
4154 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004155 }
4156 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004157
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004158 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004159 Slog.d(TAG, s);
4160 }
4161
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004162 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004163 Slog.e(TAG, s);
4164 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004165
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004166 private static void loge(String s, Throwable t) {
4167 Slog.e(TAG, s, t);
4168 }
4169
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004170 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004171 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004172 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4173 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4174 *
4175 * @param oldPackage Package name of the application which currently controls VPN, which will
4176 * be replaced. If there is no such application, this should should either be
4177 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4178 * @param newPackage Package name of the application which should gain control of VPN, or
4179 * {@code null} to disable.
4180 * @param userId User for whom to prepare the new VPN.
4181 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004182 * @hide
4183 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004184 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004185 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4186 int userId) {
4187 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004188
Hugo Benichi20035e02017-04-26 14:53:28 +09004189 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004190 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004191 Vpn vpn = mVpns.get(userId);
4192 if (vpn != null) {
4193 return vpn.prepare(oldPackage, newPackage);
4194 } else {
4195 return false;
4196 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004197 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004198 }
4199
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004200 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004201 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4202 * This method is used by system-privileged apps.
4203 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4204 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4205 *
4206 * @param packageName The package for which authorization state should change.
4207 * @param userId User for whom {@code packageName} is installed.
4208 * @param authorized {@code true} if this app should be able to start a VPN connection without
4209 * explicit user approval, {@code false} if not.
4210 *
Jeff Davidson05542602014-08-11 14:07:27 -07004211 * @hide
4212 */
4213 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004214 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4215 enforceCrossUserPermission(userId);
4216
Hugo Benichi20035e02017-04-26 14:53:28 +09004217 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004218 Vpn vpn = mVpns.get(userId);
4219 if (vpn != null) {
4220 vpn.setPackageAuthorization(packageName, authorized);
4221 }
Jeff Davidson05542602014-08-11 14:07:27 -07004222 }
4223 }
4224
4225 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004226 * Configure a TUN interface and return its file descriptor. Parameters
4227 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004228 * and not available in ConnectivityManager. Permissions are checked in
4229 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004230 * @hide
4231 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004232 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004233 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004234 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004235 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004236 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004237 return mVpns.get(user).establish(config);
4238 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004239 }
4240
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004241 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004242 * Start legacy VPN, controlling native daemons as needed. Creates a
4243 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004244 */
4245 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004246 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004247 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004248 final LinkProperties egress = getActiveLinkProperties();
4249 if (egress == null) {
4250 throw new IllegalStateException("Missing active network connection");
4251 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004252 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004253 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004254 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4255 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004256 }
4257
4258 /**
4259 * Return the information of the ongoing legacy VPN. This method is used
4260 * by VpnSettings and not available in ConnectivityManager. Permissions
4261 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004262 */
4263 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004264 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4265 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004266
Hugo Benichi20035e02017-04-26 14:53:28 +09004267 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004268 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004269 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004270 }
4271
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004272 /**
Varun Anand02c50ef2019-02-07 14:13:13 -08004273 * Return the information of all ongoing VPNs.
4274 *
4275 * <p>This method is used to update NetworkStatsService.
4276 *
4277 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004278 */
Varun Anand02c50ef2019-02-07 14:13:13 -08004279 private VpnInfo[] getAllVpnInfo() {
4280 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004281 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004282 if (mLockdownEnabled) {
4283 return new VpnInfo[0];
4284 }
4285
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004286 List<VpnInfo> infoList = new ArrayList<>();
4287 for (int i = 0; i < mVpns.size(); i++) {
4288 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4289 if (info != null) {
4290 infoList.add(info);
4291 }
4292 }
4293 return infoList.toArray(new VpnInfo[infoList.size()]);
4294 }
4295 }
4296
4297 /**
4298 * @return VPN information for accounting, or null if we can't retrieve all required
4299 * information, e.g primary underlying iface.
4300 */
4301 @Nullable
4302 private VpnInfo createVpnInfo(Vpn vpn) {
4303 VpnInfo info = vpn.getVpnInfo();
4304 if (info == null) {
4305 return null;
4306 }
4307 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4308 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4309 // the underlyingNetworks list.
4310 if (underlyingNetworks == null) {
4311 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4312 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4313 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4314 }
4315 } else if (underlyingNetworks.length > 0) {
4316 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4317 if (linkProperties != null) {
4318 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4319 }
4320 }
4321 return info.primaryUnderlyingIface == null ? null : info;
4322 }
4323
4324 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004325 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4326 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004327 * Permissions are checked in Vpn class.
4328 * @hide
4329 */
4330 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004331 public VpnConfig getVpnConfig(int userId) {
4332 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004333 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004334 Vpn vpn = mVpns.get(userId);
4335 if (vpn != null) {
4336 return vpn.getVpnConfig();
4337 } else {
4338 return null;
4339 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004340 }
4341 }
4342
Chalard Jean6b65ec72018-05-18 22:02:56 +09004343 /**
4344 * Ask all VPN objects to recompute and update their capabilities.
4345 *
4346 * When underlying networks change, VPNs may have to update capabilities to reflect things
4347 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4348 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4349 * handler thread through their agent, this is asynchronous. When the capabilities objects
4350 * are computed they will be up-to-date as they are computed synchronously from here and
4351 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004352 */
4353 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004354 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004355 synchronized (mVpns) {
4356 for (int i = 0; i < mVpns.size(); i++) {
4357 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004358 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4359 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004360 }
4361 }
4362 }
4363
Varun Anand4fa80e82019-02-06 10:13:38 -08004364 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4365 ensureRunningOnConnectivityServiceThread();
4366 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4367 if (vpnNai == null || nc == null) {
4368 return;
4369 }
4370 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4371 }
4372
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004373 @Override
4374 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004375 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4376 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4377 return false;
4378 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004379
Hugo Benichi69744342017-11-27 10:57:16 +09004380 synchronized (mVpns) {
4381 // Tear down existing lockdown if profile was removed
4382 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4383 if (mLockdownEnabled) {
4384 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4385 if (profileTag == null) {
4386 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4387 return false;
4388 }
4389 String profileName = new String(profileTag);
4390 final VpnProfile profile = VpnProfile.decode(
4391 profileName, mKeyStore.get(Credentials.VPN + profileName));
4392 if (profile == null) {
4393 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4394 setLockdownTracker(null);
4395 return true;
4396 }
4397 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004398 Vpn vpn = mVpns.get(user);
4399 if (vpn == null) {
4400 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4401 return false;
4402 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004403 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004404 } else {
4405 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004406 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004407 }
4408
4409 return true;
4410 }
4411
4412 /**
4413 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4414 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4415 */
Hugo Benichi69744342017-11-27 10:57:16 +09004416 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004417 private void setLockdownTracker(LockdownVpnTracker tracker) {
4418 // Shutdown any existing tracker
4419 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004420 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4421 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004422 mLockdownTracker = null;
4423 if (existing != null) {
4424 existing.shutdown();
4425 }
4426
Robin Leec3736bc2017-03-10 16:19:54 +00004427 if (tracker != null) {
4428 mLockdownTracker = tracker;
4429 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004430 }
4431 }
4432
Hugo Benichi69744342017-11-27 10:57:16 +09004433 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004434 private void throwIfLockdownEnabled() {
4435 if (mLockdownEnabled) {
4436 throw new IllegalStateException("Unavailable in lockdown mode");
4437 }
4438 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004439
Robin Lee244ce8e2016-01-05 18:03:46 +00004440 /**
Robin Lee17e61832016-05-09 13:46:28 +01004441 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4442 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004443 *
Robin Lee17e61832016-05-09 13:46:28 +01004444 * @return {@code true} if the service was started, the service was already connected, or there
4445 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004446 */
Robin Lee17e61832016-05-09 13:46:28 +01004447 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004448 synchronized (mVpns) {
4449 Vpn vpn = mVpns.get(userId);
4450 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004451 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004452 // exists already.
4453 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4454 return false;
4455 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004456
Robin Lee812800c2016-05-13 15:38:08 +01004457 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004458 }
4459 }
4460
4461 @Override
Charles He36738632017-05-15 17:07:18 +01004462 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4463 enforceSettingsPermission();
4464 enforceCrossUserPermission(userId);
4465
4466 synchronized (mVpns) {
4467 Vpn vpn = mVpns.get(userId);
4468 if (vpn == null) {
4469 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4470 return false;
4471 }
4472 return vpn.isAlwaysOnPackageSupported(packageName);
4473 }
4474 }
4475
4476 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004477 public boolean setAlwaysOnVpnPackage(
4478 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4479 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004480 enforceCrossUserPermission(userId);
4481
Robin Lee244ce8e2016-01-05 18:03:46 +00004482 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004483 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4484 if (LockdownVpnTracker.isEnabled()) {
4485 return false;
4486 }
4487
Robin Lee244ce8e2016-01-05 18:03:46 +00004488 Vpn vpn = mVpns.get(userId);
4489 if (vpn == null) {
4490 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4491 return false;
4492 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004493 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004494 return false;
4495 }
Robin Lee17e61832016-05-09 13:46:28 +01004496 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004497 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004498 return false;
4499 }
4500 }
4501 return true;
4502 }
4503
4504 @Override
4505 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004506 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004507 enforceCrossUserPermission(userId);
4508
4509 synchronized (mVpns) {
4510 Vpn vpn = mVpns.get(userId);
4511 if (vpn == null) {
4512 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4513 return null;
4514 }
4515 return vpn.getAlwaysOnPackage();
4516 }
4517 }
4518
Wink Savilleab9321d2013-06-29 21:10:57 -07004519 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004520 public boolean isVpnLockdownEnabled(int userId) {
4521 enforceControlAlwaysOnVpnPermission();
4522 enforceCrossUserPermission(userId);
4523
4524 synchronized (mVpns) {
4525 Vpn vpn = mVpns.get(userId);
4526 if (vpn == null) {
4527 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4528 return false;
4529 }
4530 return vpn.getLockdown();
4531 }
4532 }
4533
4534 @Override
4535 public List<String> getVpnLockdownWhitelist(int userId) {
4536 enforceControlAlwaysOnVpnPermission();
4537 enforceCrossUserPermission(userId);
4538
4539 synchronized (mVpns) {
4540 Vpn vpn = mVpns.get(userId);
4541 if (vpn == null) {
4542 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4543 return null;
4544 }
4545 return vpn.getLockdownWhitelist();
4546 }
4547 }
4548
4549 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004550 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004551 // TODO: Remove? Any reason to trigger a provisioning check?
4552 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004553 }
4554
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004555 /** Location to an updatable file listing carrier provisioning urls.
4556 * An example:
4557 *
4558 * <?xml version="1.0" encoding="utf-8"?>
4559 * <provisioningUrls>
4560 * <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 -07004561 * </provisioningUrls>
4562 */
4563 private static final String PROVISIONING_URL_PATH =
4564 "/data/misc/radio/provisioning_urls.xml";
4565 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004566
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004567 /** XML tag for root element. */
4568 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4569 /** XML tag for individual url */
4570 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004571 /** XML attribute for mcc */
4572 private static final String ATTR_MCC = "mcc";
4573 /** XML attribute for mnc */
4574 private static final String ATTR_MNC = "mnc";
4575
Paul Jensen434dde82015-06-11 09:43:30 -04004576 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004577 FileReader fileReader = null;
4578 XmlPullParser parser = null;
4579 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004580
4581 try {
4582 fileReader = new FileReader(mProvisioningUrlFile);
4583 parser = Xml.newPullParser();
4584 parser.setInput(fileReader);
4585 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4586
4587 while (true) {
4588 XmlUtils.nextElement(parser);
4589
4590 String element = parser.getName();
4591 if (element == null) break;
4592
Paul Jensen434dde82015-06-11 09:43:30 -04004593 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004594 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4595 try {
4596 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4597 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4598 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4599 parser.next();
4600 if (parser.getEventType() == XmlPullParser.TEXT) {
4601 return parser.getText();
4602 }
4603 }
4604 }
4605 } catch (NumberFormatException e) {
4606 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4607 }
4608 }
4609 }
4610 return null;
4611 } catch (FileNotFoundException e) {
4612 loge("Carrier Provisioning Urls file not found");
4613 } catch (XmlPullParserException e) {
4614 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4615 } catch (IOException e) {
4616 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4617 } finally {
4618 if (fileReader != null) {
4619 try {
4620 fileReader.close();
4621 } catch (IOException e) {}
4622 }
4623 }
4624 return null;
4625 }
4626
Wink Saville42d4f082013-07-20 20:31:59 -07004627 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004628 public String getMobileProvisioningUrl() {
4629 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004630 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004631 if (TextUtils.isEmpty(url)) {
4632 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004633 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004634 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004635 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004636 }
Wink Saville8cf35602013-07-10 23:00:07 -07004637 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004638 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004639 String phoneNumber = mTelephonyManager.getLine1Number();
4640 if (TextUtils.isEmpty(phoneNumber)) {
4641 phoneNumber = "0000000000";
4642 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004643 url = String.format(url,
4644 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4645 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004646 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004647 }
4648
Wink Savilleab9321d2013-06-29 21:10:57 -07004649 return url;
4650 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004651
Wink Saville948282b2013-08-29 08:55:16 -07004652 @Override
4653 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004654 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004655 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004656 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4657 return;
4658 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004659 final long ident = Binder.clearCallingIdentity();
4660 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004661 // Concatenate the range of types onto the range of NetIDs.
4662 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4663 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004664 } finally {
4665 Binder.restoreCallingIdentity(ident);
4666 }
Wink Saville948282b2013-08-29 08:55:16 -07004667 }
Wink Saville7788c612013-08-29 14:57:08 -07004668
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004669 @Override
4670 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004671 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004672 final long ident = Binder.clearCallingIdentity();
4673 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004674 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004675 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004676 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4677 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004678 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004679 } finally {
4680 Binder.restoreCallingIdentity(ident);
4681 }
4682 }
4683
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004684 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004685 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004686 Vpn userVpn = mVpns.get(userId);
4687 if (userVpn != null) {
4688 loge("Starting user already has a VPN");
4689 return;
4690 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004691 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004692 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004693 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4694 updateLockdownVpn();
4695 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004696 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004697 }
4698
4699 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004700 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004701 Vpn userVpn = mVpns.get(userId);
4702 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004703 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004704 return;
4705 }
Robin Lee17e61832016-05-09 13:46:28 +01004706 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004707 mVpns.delete(userId);
4708 }
4709 }
4710
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004711 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004712 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004713 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004714 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004715 final int vpnsSize = mVpns.size();
4716 for (int i = 0; i < vpnsSize; i++) {
4717 Vpn vpn = mVpns.valueAt(i);
4718 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004719 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4720 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004721 }
4722 }
4723 }
4724
4725 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004726 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004727 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004728 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004729 final int vpnsSize = mVpns.size();
4730 for (int i = 0; i < vpnsSize; i++) {
4731 Vpn vpn = mVpns.valueAt(i);
4732 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004733 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4734 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004735 }
4736 }
4737 }
4738
junyulai2454b692018-11-01 17:16:31 +08004739 private void onPackageAdded(String packageName, int uid) {
4740 if (TextUtils.isEmpty(packageName) || uid < 0) {
4741 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4742 return;
4743 }
4744 mPermissionMonitor.onPackageAdded(packageName, uid);
4745 }
4746
junyulaiefb04d32018-11-12 22:39:30 +08004747 private void onPackageReplaced(String packageName, int uid) {
4748 if (TextUtils.isEmpty(packageName) || uid < 0) {
4749 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4750 return;
4751 }
4752 final int userId = UserHandle.getUserId(uid);
4753 synchronized (mVpns) {
4754 final Vpn vpn = mVpns.get(userId);
4755 if (vpn == null) {
4756 return;
4757 }
4758 // Legacy always-on VPN won't be affected since the package name is not set.
4759 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4760 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4761 + userId);
4762 vpn.startAlwaysOnVpn();
4763 }
4764 }
4765 }
4766
4767 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004768 if (TextUtils.isEmpty(packageName) || uid < 0) {
4769 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4770 return;
4771 }
4772 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004773
4774 final int userId = UserHandle.getUserId(uid);
4775 synchronized (mVpns) {
4776 final Vpn vpn = mVpns.get(userId);
4777 if (vpn == null) {
4778 return;
4779 }
4780 // Legacy always-on VPN won't be affected since the package name is not set.
4781 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4782 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4783 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004784 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004785 }
4786 }
junyulai2454b692018-11-01 17:16:31 +08004787 }
4788
Robin Lee89e7a692016-02-29 14:38:17 +00004789 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004790 synchronized (mVpns) {
4791 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4792 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4793 updateLockdownVpn();
4794 } else {
4795 startAlwaysOnVpn(userId);
4796 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004797 }
4798 }
4799
junyulai2454b692018-11-01 17:16:31 +08004800 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004801 @Override
4802 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004803 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004804 final String action = intent.getAction();
4805 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004806 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4807 final Uri packageData = intent.getData();
4808 final String packageName =
4809 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004810 if (userId == UserHandle.USER_NULL) return;
4811
Robin Lee323f29d2016-05-04 16:38:06 +01004812 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004813 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004814 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004815 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004816 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4817 onUserAdded(userId);
4818 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4819 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004820 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4821 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004822 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4823 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004824 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4825 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004826 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004827 final boolean isReplacing = intent.getBooleanExtra(
4828 Intent.EXTRA_REPLACING, false);
4829 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004830 }
4831 }
4832 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004833
Robin Lee95204e02017-01-27 11:59:22 +00004834 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4835 @Override
4836 public void onReceive(Context context, Intent intent) {
4837 // Try creating lockdown tracker, since user present usually means
4838 // unlocked keystore.
4839 updateLockdownVpn();
4840 mContext.unregisterReceiver(this);
4841 }
4842 };
4843
Chalard Jean4133a122018-06-04 13:33:12 +09004844 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4845 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004846
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004847 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4848 // Map from UID to number of NetworkRequests that UID has filed.
4849 @GuardedBy("mUidToNetworkRequestCount")
4850 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4851
Robert Greenwalta67be032014-05-16 15:49:14 -07004852 private static class NetworkFactoryInfo {
4853 public final String name;
4854 public final Messenger messenger;
4855 public final AsyncChannel asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004856 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004857
Chalard Jean08577fc2018-05-02 21:14:54 +09004858 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4859 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004860 this.name = name;
4861 this.messenger = messenger;
4862 this.asyncChannel = asyncChannel;
Chalard Jean08577fc2018-05-02 21:14:54 +09004863 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004864 }
4865 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004866
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004867 private void ensureNetworkRequestHasType(NetworkRequest request) {
4868 if (request.type == NetworkRequest.Type.NONE) {
4869 throw new IllegalArgumentException(
4870 "All NetworkRequests in ConnectivityService must have a type");
4871 }
4872 }
4873
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004874 /**
4875 * Tracks info about the requester.
4876 * Also used to notice when the calling process dies so we can self-expire
4877 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004878 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004879 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004880 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004881 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004882 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004883 final int mPid;
4884 final int mUid;
4885 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004886
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004887 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004888 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004889 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004890 mPendingIntent = pi;
4891 messenger = null;
4892 mBinder = null;
4893 mPid = getCallingPid();
4894 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004895 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004896 }
4897
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004898 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004899 super();
4900 messenger = m;
4901 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004902 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004903 mBinder = binder;
4904 mPid = getCallingPid();
4905 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004906 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004907 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004908
4909 try {
4910 mBinder.linkToDeath(this, 0);
4911 } catch (RemoteException e) {
4912 binderDied();
4913 }
4914 }
4915
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004916 private void enforceRequestCountLimit() {
4917 synchronized (mUidToNetworkRequestCount) {
4918 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4919 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004920 throw new ServiceSpecificException(
4921 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004922 }
4923 mUidToNetworkRequestCount.put(mUid, networkRequests);
4924 }
4925 }
4926
Robert Greenwalt9258c642014-03-26 16:47:06 -07004927 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004928 if (mBinder != null) {
4929 mBinder.unlinkToDeath(this, 0);
4930 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004931 }
4932
4933 public void binderDied() {
4934 log("ConnectivityService NetworkRequestInfo binderDied(" +
4935 request + ", " + mBinder + ")");
4936 releaseNetworkRequest(request);
4937 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004938
4939 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004940 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004941 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004942 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004943 }
4944
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004945 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4946 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4947 if (badCapability != null) {
4948 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004949 }
4950 }
4951
Chalard Jeanb03a6222018-04-11 21:09:10 +09004952 // This checks that the passed capabilities either do not request a specific SSID, or the
4953 // calling app has permission to do so.
4954 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4955 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004956 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004957 throw new SecurityException("Insufficient permissions to request a specific SSID");
4958 }
4959 }
4960
Erik Kline9d598e12015-07-13 16:37:51 +09004961 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004962 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004963 synchronized (nai) {
4964 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4965 if (nri.request.networkCapabilities.hasSignalStrength() &&
4966 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4967 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4968 }
4969 }
4970 }
Chalard Jean4133a122018-06-04 13:33:12 +09004971 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004972 }
4973
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004974 private void updateSignalStrengthThresholds(
4975 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4976 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004977 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004978 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4979
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004980 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004981 String detail;
4982 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4983 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4984 } else {
4985 detail = reason;
4986 }
4987 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4988 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4989 }
4990
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004991 nai.asyncChannel.sendMessage(
4992 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004993 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004994 }
4995
Etan Cohen859748f2017-04-03 17:42:34 -07004996 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4997 if (nc == null) {
4998 return;
4999 }
5000 NetworkSpecifier ns = nc.getNetworkSpecifier();
5001 if (ns == null) {
5002 return;
5003 }
5004 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
5005 ns.assertValidFromUid(Binder.getCallingUid());
5006 }
5007
Robert Greenwalt9258c642014-03-26 16:47:06 -07005008 @Override
5009 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005010 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005011 final NetworkRequest.Type type = (networkCapabilities == null)
5012 ? NetworkRequest.Type.TRACK_DEFAULT
5013 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005014 // If the requested networkCapabilities is null, take them instead from
5015 // the default network request. This allows callers to keep track of
5016 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005017 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005018 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005019 enforceAccessPermission();
5020 } else {
5021 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5022 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005023 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5024 // of the app when the request is filed, but we never change the request if the app
5025 // changes network state. http://b/29964605
5026 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005027 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005028 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005029 ensureSufficientPermissionsForRequest(networkCapabilities,
5030 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005031 // Set the UID range for this request to the single UID of the requester, or to an empty
5032 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005033 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5034 // are no visible methods to set the UIDs, an app could use reflection to try and get
5035 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005036 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005037
Etan Cohenba07c8c2017-02-05 10:42:27 -08005038 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005039 throw new IllegalArgumentException("Bad timeout specified");
5040 }
Etan Cohen859748f2017-04-03 17:42:34 -07005041 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005042
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005043 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005044 nextNetworkRequestId(), type);
5045 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005046 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005047
5048 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005049 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005050 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005051 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005052 }
5053 return networkRequest;
5054 }
5055
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005056 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005057 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005058 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005059 } else {
5060 enforceChangePermission();
5061 }
5062 }
5063
fenglub15e72b2015-03-20 11:29:56 -07005064 @Override
fengludb571472015-04-21 17:12:05 -07005065 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005066 enforceAccessPermission();
5067 NetworkAgentInfo nai = null;
5068 if (network == null) {
5069 return false;
5070 }
5071 synchronized (mNetworkForNetId) {
5072 nai = mNetworkForNetId.get(network.netId);
5073 }
5074 if (nai != null) {
5075 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005076 synchronized (mBandwidthRequests) {
5077 final int uid = Binder.getCallingUid();
5078 Integer uidReqs = mBandwidthRequests.get(uid);
5079 if (uidReqs == null) {
5080 uidReqs = new Integer(0);
5081 }
5082 mBandwidthRequests.put(uid, ++uidReqs);
5083 }
fenglub15e72b2015-03-20 11:29:56 -07005084 return true;
5085 }
5086 return false;
5087 }
5088
Felipe Lemeee27cab2016-06-20 16:36:29 -07005089 private boolean isSystem(int uid) {
5090 return uid < Process.FIRST_APPLICATION_UID;
5091 }
fenglub15e72b2015-03-20 11:29:56 -07005092
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005093 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005094 final int uid = Binder.getCallingUid();
5095 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005096 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005097 return;
5098 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005099 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5100 // Policy already enforced.
5101 return;
5102 }
5103 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5104 // If UID is restricted, don't allow them to bring up metered APNs.
5105 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005106 }
5107 }
5108
Robert Greenwalt9258c642014-03-26 16:47:06 -07005109 @Override
5110 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5111 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005112 checkNotNull(operation, "PendingIntent cannot be null.");
5113 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5114 enforceNetworkRequestPermissions(networkCapabilities);
5115 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005116 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005117 ensureSufficientPermissionsForRequest(networkCapabilities,
5118 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005119 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005120 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005121
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005122 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005123 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5124 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005125 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005126 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5127 nri));
5128 return networkRequest;
5129 }
5130
Jeremy Joslin79294842014-12-03 17:15:28 -08005131 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5132 mHandler.sendMessageDelayed(
5133 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5134 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5135 }
5136
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005137 @Override
5138 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005139 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5141 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005142 }
5143
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005144 // In order to implement the compatibility measure for pre-M apps that call
5145 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5146 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5147 // This ensures it has permission to do so.
5148 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5149 if (nc == null) {
5150 return false;
5151 }
5152 int[] transportTypes = nc.getTransportTypes();
5153 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5154 return false;
5155 }
5156 try {
5157 mContext.enforceCallingOrSelfPermission(
5158 android.Manifest.permission.ACCESS_WIFI_STATE,
5159 "ConnectivityService");
5160 } catch (SecurityException e) {
5161 return false;
5162 }
5163 return true;
5164 }
5165
Robert Greenwalt9258c642014-03-26 16:47:06 -07005166 @Override
5167 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5168 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005169 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5170 enforceAccessPermission();
5171 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005172
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005173 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005174 ensureSufficientPermissionsForRequest(networkCapabilities,
5175 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005176 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005177 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5178 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5179 // onLost and onAvailable callbacks when networks move in and out of the background.
5180 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5181 // can't request networks.
5182 restrictBackgroundRequestForCaller(nc);
5183 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005184
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005185 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005186 NetworkRequest.Type.LISTEN);
5187 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005188 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005189
5190 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5191 return networkRequest;
5192 }
5193
5194 @Override
5195 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5196 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005197 checkNotNull(operation, "PendingIntent cannot be null.");
5198 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5199 enforceAccessPermission();
5200 }
Etan Cohen859748f2017-04-03 17:42:34 -07005201 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005202 ensureSufficientPermissionsForRequest(networkCapabilities,
5203 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005204
Chalard Jeandda156a2018-01-10 21:19:32 +09005205 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005206 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005207
5208 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005209 NetworkRequest.Type.LISTEN);
5210 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005211 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005212
5213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005214 }
5215
Erik Klineacdd6392016-07-07 16:50:58 +09005216 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005217 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005218 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005219 mHandler.sendMessage(mHandler.obtainMessage(
5220 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005221 }
5222
5223 @Override
Chalard Jean08577fc2018-05-02 21:14:54 +09005224 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005225 enforceConnectivityInternalPermission();
Chalard Jean08577fc2018-05-02 21:14:54 +09005226 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5227 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean08577fc2018-05-02 21:14:54 +09005229 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005230 }
5231
Robert Greenwalta67be032014-05-16 15:49:14 -07005232 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005233 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005234 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5235 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5236 }
5237
5238 @Override
5239 public void unregisterNetworkFactory(Messenger messenger) {
5240 enforceConnectivityInternalPermission();
5241 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5242 }
5243
5244 private void handleUnregisterNetworkFactory(Messenger messenger) {
5245 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5246 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005247 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005248 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005249 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005250 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005251 }
5252
Robert Greenwalt7b816022014-04-18 15:25:25 -07005253 /**
5254 * NetworkAgentInfo supporting a request by requestId.
5255 * These have already been vetted (their Capabilities satisfy the request)
5256 * and the are the highest scored network available.
5257 * the are keyed off the Requests requestId.
5258 */
Hugo Benichicd952782017-09-20 11:20:14 +09005259 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5260 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005261 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262
Paul Jensen31a94f42015-02-13 14:18:39 -05005263 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5264 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005265 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005266 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5267 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5268 // there may not be a strict 1:1 correlation between the two.
5269 @GuardedBy("mNetworkForNetId")
5270 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005271
Robert Greenwalt7b816022014-04-18 15:25:25 -07005272 // NetworkAgentInfo keyed off its connecting messenger
5273 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005274 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005275 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005276
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005277 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005278 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005279
Paul Jensen2c311d62014-11-17 12:34:51 -05005280 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005281 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005282
Erik Klineda4bfa82015-04-30 12:58:40 +09005283 // Request used to optionally keep mobile data active even when higher
5284 // priority networks like Wi-Fi are active.
5285 private final NetworkRequest mDefaultMobileDataRequest;
5286
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005287 // Request used to optionally keep wifi data active even when higher
5288 // priority networks like ethernet are active.
5289 private final NetworkRequest mDefaultWifiRequest;
5290
Hugo Benichicd952782017-09-20 11:20:14 +09005291 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5292 synchronized (mNetworkForRequestId) {
5293 return mNetworkForRequestId.get(requestId);
5294 }
5295 }
5296
5297 private void clearNetworkForRequest(int requestId) {
5298 synchronized (mNetworkForRequestId) {
5299 mNetworkForRequestId.remove(requestId);
5300 }
5301 }
5302
5303 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5304 synchronized (mNetworkForRequestId) {
5305 mNetworkForRequestId.put(requestId, nai);
5306 }
5307 }
5308
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005309 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005310 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005311 }
5312
Varun Anand4fa80e82019-02-06 10:13:38 -08005313 @Nullable
5314 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5315 return nai != null ? nai.network : null;
5316 }
5317
5318 private void ensureRunningOnConnectivityServiceThread() {
5319 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5320 throw new IllegalStateException(
5321 "Not running on ConnectivityService thread: "
5322 + Thread.currentThread().getName());
5323 }
5324 }
5325
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005326 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005327 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005328 }
5329
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005330 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5331 return nri.request.requestId == mDefaultRequest.requestId;
5332 }
5333
Chalard Jean08577fc2018-05-02 21:14:54 +09005334 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5335 // changes that would conflict throughout the automerger graph. Having this method temporarily
5336 // helps with the process of going through with all these dependent changes across the entire
5337 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005338 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005339 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005340 int currentScore, NetworkMisc networkMisc) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005341 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5342 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5343 }
5344
5345 /**
5346 * Register a new agent with ConnectivityService to handle a network.
5347 *
5348 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5349 * @param networkInfo the initial info associated with this network. It can be updated later :
5350 * see {@link #updateNetworkInfo}.
5351 * @param linkProperties the initial link properties of this network. They can be updated
5352 * later : see {@link #updateLinkProperties}.
5353 * @param networkCapabilities the initial capabilites of this network. They can be updated
5354 * later : see {@link #updateNetworkCapabilities}.
5355 * @param currentScore the initial score of the network. See
5356 * {@link NetworkAgentInfo#getCurrentScore}.
5357 * @param networkMisc metadata about the network. This is never updated.
5358 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5359 */
5360 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5361 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5362 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005363 enforceConnectivityInternalPermission();
5364
Rubin Xu1bb5c082017-09-05 18:40:49 +01005365 LinkProperties lp = new LinkProperties(linkProperties);
5366 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005367 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5368 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005369 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005370 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005371 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean08577fc2018-05-02 21:14:54 +09005372 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5373 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005374 // Make sure the network capabilities reflect what the agent info says.
5375 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005376 final String extraInfo = networkInfo.getExtraInfo();
5377 final String name = TextUtils.isEmpty(extraInfo)
5378 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005379 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005380 final long token = Binder.clearCallingIdentity();
5381 try {
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005382 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN904a38b2019-03-15 02:25:09 +09005383 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005384 } finally {
5385 Binder.restoreCallingIdentity(token);
5386 }
5387 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5388 // If the network disconnects or sends any other event before that, messages are deferred by
5389 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5390 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005391 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005392 }
5393
Remi NGUYEN VAN310da6f2019-02-14 18:04:20 +09005394 @VisibleForTesting
5395 protected NetworkStackClient getNetworkStack() {
5396 return NetworkStackClient.getInstance();
5397 }
5398
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005399 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5400 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005401 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005402 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005403 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005404 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005405 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005406 synchronized (this) {
5407 if (mSystemReady) {
5408 try {
5409 networkMonitor.notifySystemReady();
5410 } catch (RemoteException e) {
5411 e.rethrowFromSystemServer();
5412 }
5413 }
5414 }
5415
5416 try {
5417 networkMonitor.start();
5418 } catch (RemoteException e) {
5419 e.rethrowFromSystemServer();
5420 }
Erik Klinee5dac902018-03-04 21:01:01 +09005421 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5422 NetworkInfo networkInfo = nai.networkInfo;
5423 nai.networkInfo = null;
5424 updateNetworkInfo(nai, networkInfo);
5425 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005426 }
5427
lucaslin25a4ec32018-11-28 12:51:55 +08005428 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5429 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005430 int netId = networkAgent.network.netId;
5431
Lorenzo Colittidf595632019-01-08 14:43:37 +09005432 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5433 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5434 // are accurate.
5435 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005436
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005437 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005438 updateMtu(newLp, oldLp);
5439 // TODO - figure out what to do for clat
5440// for (LinkProperties lp : newLp.getStackedLinks()) {
5441// updateMtu(lp, null);
5442// }
lucaslin041a1af2018-11-28 19:27:52 +08005443 if (isDefaultNetwork(networkAgent)) {
5444 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5445 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005446
Erik Kline94887872016-04-05 13:30:49 +09005447 updateRoutes(newLp, oldLp, netId);
5448 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005449 // Make sure LinkProperties represents the latest private DNS status.
5450 // This does not need to be done before updateDnses because the
5451 // LinkProperties are not the source of the private DNS configuration.
5452 // updateDnses will fetch the private DNS configuration from DnsManager.
5453 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005454
Paul Jensene0bef712014-12-10 15:12:18 -05005455 if (isDefaultNetwork(networkAgent)) {
5456 handleApplyDefaultProxy(newLp.getHttpProxy());
5457 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005458 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005459 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005460 // TODO - move this check to cover the whole function
5461 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005462 synchronized (networkAgent) {
5463 networkAgent.linkProperties = newLp;
5464 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005465 // Start or stop DNS64 detection and 464xlat according to network state.
5466 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005467 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005468 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005469 try {
5470 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5471 } catch (RemoteException e) {
5472 e.rethrowFromSystemServer();
5473 }
lucaslin25a4ec32018-11-28 12:51:55 +08005474 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5475 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005476 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005477
5478 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005479 }
5480
Joel Scherpelz668370b2017-06-08 15:35:21 +09005481 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005482 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005483 // marks on unsupported interfaces is harmless.
5484 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5485 return;
5486 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005487
Joel Scherpelz668370b2017-06-08 15:35:21 +09005488 int mark = mContext.getResources().getInteger(
5489 com.android.internal.R.integer.config_networkWakeupPacketMark);
5490 int mask = mContext.getResources().getInteger(
5491 com.android.internal.R.integer.config_networkWakeupPacketMask);
5492
5493 // Mask/mark of zero will not detect anything interesting.
5494 // Don't install rules unless both values are nonzero.
5495 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005496 return;
5497 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005498
5499 final String prefix = "iface:" + iface;
5500 try {
5501 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005502 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005503 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005504 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005505 }
5506 } catch (Exception e) {
5507 loge("Exception modifying wakeup packet monitoring: " + e);
5508 }
5509
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005510 }
5511
5512 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5513 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005514 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005515 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5516 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005517 for (String iface : interfaceDiff.added) {
5518 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005519 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005520 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005521 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005522 } catch (Exception e) {
5523 loge("Exception adding interface: " + e);
5524 }
5525 }
5526 for (String iface : interfaceDiff.removed) {
5527 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005528 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005529 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005530 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005531 } catch (Exception e) {
5532 loge("Exception removing interface: " + e);
5533 }
5534 }
5535 }
5536
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005537 /**
5538 * Have netd update routes from oldLp to newLp.
5539 * @return true if routes changed between oldLp and newLp
5540 */
5541 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005542 // Compare the route diff to determine which routes should be added and removed.
5543 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5544 oldLp != null ? oldLp.getAllRoutes() : null,
5545 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005546
5547 // add routes before removing old in case it helps with continuous connectivity
5548
Chalard Jean4d660112018-06-04 16:52:49 +09005549 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005550 for (RouteInfo route : routeDiff.added) {
5551 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005552 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005553 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005554 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005555 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005556 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5557 loge("Exception in addRoute for non-gateway: " + e);
5558 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005559 }
5560 }
5561 for (RouteInfo route : routeDiff.added) {
5562 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005563 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005564 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005565 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005566 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005567 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5568 loge("Exception in addRoute for gateway: " + e);
5569 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005570 }
5571 }
5572
5573 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005574 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005575 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005576 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005577 } catch (Exception e) {
5578 loge("Exception in removeRoute: " + e);
5579 }
5580 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005581 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005582 }
Erik Kline41368502015-06-17 13:19:54 +09005583
Erik Kline94887872016-04-05 13:30:49 +09005584 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5585 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5586 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005587 }
Erik Kline94887872016-04-05 13:30:49 +09005588
Erik Kline1742fe12017-12-13 19:40:49 +09005589 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5590 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5591
Erik Klinea24d4592018-01-11 21:07:29 +09005592 if (DBG) {
5593 final Collection<InetAddress> dnses = newLp.getDnsServers();
5594 log("Setting DNS servers for network " + netId + " to " + dnses);
5595 }
Erik Kline94887872016-04-05 13:30:49 +09005596 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005597 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005598 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005599 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005600 }
Erik Kline4edba012017-04-07 15:29:29 +09005601 }
5602
Luke Huang8a462ec2018-08-24 20:33:16 +08005603 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005604 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005605 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005606 }
5607 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005608 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005609 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005610 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005611 }
5612
Paul Jensen3d194ea2015-06-16 14:27:36 -04005613 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005614 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5615 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5616 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005617 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005618 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005619 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005620 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5621 // causing a connect/teardown loop.
5622 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5623 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005624 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005625 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005626 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5627 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005628 // does not cause any request (that is not a listen) currently matching that agent to
5629 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005630 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005631 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005632 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005633 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005634 }
5635
Paul Jensen3d194ea2015-06-16 14:27:36 -04005636 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005637 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005638 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005639 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005640 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005641 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005642 }
Paul Jensene0988542015-06-25 15:30:08 -04005643 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005644 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005645 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005646 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005647 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005648 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005649 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005650 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005651 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005652 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005653 if (nai.isSuspended()) {
5654 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5655 } else {
5656 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5657 }
lucasline252a742019-03-12 13:08:03 +08005658 if (nai.partialConnectivity) {
5659 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5660 } else {
5661 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5662 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005663
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005664 return newNc;
5665 }
5666
5667 /**
5668 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5669 *
5670 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5671 * capabilities we manage and store in {@code nai}, such as validated status and captive
5672 * portal status)
5673 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5674 * potentially triggers rematches.
5675 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5676 * change.)
5677 *
5678 * @param oldScore score of the network before any of the changes that prompted us
5679 * to call this function.
5680 * @param nai the network having its capabilities updated.
5681 * @param nc the new network capabilities.
5682 */
5683 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5684 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5685
5686 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005687
Luke Huang8a462ec2018-08-24 20:33:16 +08005688 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5689 final int newPermission = getNetworkPermission(newNc);
5690 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005691 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005692 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005693 } catch (RemoteException e) {
5694 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005695 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005696 }
5697
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005698 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005699 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005700 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005701 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005702 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005703
Chalard Jeanf213ca12018-01-16 18:43:05 +09005704 updateUids(nai, prevNc, newNc);
5705
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005706 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005707 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5708 // the change we're processing can't affect any requests, it can only affect the listens
5709 // on this network. We might have been called by rematchNetworkAndRequests when a
5710 // network changed foreground state.
5711 processListenRequests(nai, true);
5712 } else {
5713 // If the requestable capabilities have changed or the score changed, we can't have been
5714 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005715 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005716 try {
5717 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5718 } catch (RemoteException e) {
5719 e.rethrowFromSystemServer();
5720 }
Paul Jensene0988542015-06-25 15:30:08 -04005721 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005722 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005723
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005724 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005725 final boolean oldMetered = prevNc.isMetered();
5726 final boolean newMetered = newNc.isMetered();
5727 final boolean meteredChanged = oldMetered != newMetered;
5728
5729 if (meteredChanged) {
5730 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5731 mRestrictBackground);
5732 }
5733
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005734 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005735 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005736
5737 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005738 if (meteredChanged || roamingChanged) {
5739 notifyIfacesChangedForNetworkStats();
5740 }
5741 }
5742
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005743 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005744 // Tell VPNs about updated capabilities, since they may need to
5745 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005746 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005747 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005748 }
5749
Chalard Jeanf213ca12018-01-16 18:43:05 +09005750 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5751 NetworkCapabilities newNc) {
5752 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5753 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5754 if (null == prevRanges) prevRanges = new ArraySet<>();
5755 if (null == newRanges) newRanges = new ArraySet<>();
5756 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5757
5758 prevRanges.removeAll(newRanges);
5759 newRanges.removeAll(prevRangesCopy);
5760
5761 try {
5762 if (!newRanges.isEmpty()) {
5763 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5764 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005765 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005766 }
5767 if (!prevRanges.isEmpty()) {
5768 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5769 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005770 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005771 }
5772 } catch (Exception e) {
5773 // Never crash!
5774 loge("Exception in updateUids: " + e);
5775 }
5776 }
5777
Hugo Benichief502882017-09-01 01:23:32 +00005778 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005779 ensureRunningOnConnectivityServiceThread();
5780
Erik Kline736353a2018-03-21 07:18:33 -07005781 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005782 // Ignore updates for disconnected networks
5783 return;
5784 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005785 // newLp is already a defensive copy.
5786 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005787 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005788 log("Update of LinkProperties for " + nai.name() +
5789 "; created=" + nai.created +
5790 "; everConnected=" + nai.everConnected);
5791 }
lucaslin25a4ec32018-11-28 12:51:55 +08005792 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005793 }
5794
Paul Jensenc8b9a742014-09-30 15:37:41 -04005795 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005796 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5797 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005798 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005799 if (nr.isListen()) continue;
Chalard Jean08577fc2018-05-02 21:14:54 +09005800 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005801 }
5802 }
5803
Chalard Jean08577fc2018-05-02 21:14:54 +09005804 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5805 int score = 0;
5806 int serial = 0;
5807 if (nai != null) {
5808 score = nai.getCurrentScore();
5809 serial = nai.factorySerialNumber;
5810 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005811 if (VDBG || DDBG){
5812 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5813 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005814 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean08577fc2018-05-02 21:14:54 +09005815 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5816 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005817 }
5818 }
5819
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005820 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5821 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005822 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005823 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005824 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5825 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005826 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005827 sendIntent(nri.mPendingIntent, intent);
5828 }
5829 // else not handled
5830 }
5831
5832 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5833 mPendingIntentWakeLock.acquire();
5834 try {
5835 if (DBG) log("Sending " + pendingIntent);
5836 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5837 } catch (PendingIntent.CanceledException e) {
5838 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5839 mPendingIntentWakeLock.release();
5840 releasePendingNetworkRequest(pendingIntent);
5841 }
5842 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5843 }
5844
5845 @Override
5846 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5847 String resultData, Bundle resultExtras) {
5848 if (DBG) log("Finished sending " + pendingIntent);
5849 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005850 // Release with a delay so the receiving client has an opportunity to put in its
5851 // own request.
5852 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005853 }
5854
Chalard Jeanf19db372018-01-26 19:24:40 +09005855 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005856 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005857 if (nri.messenger == null) {
5858 return; // Default request has no msgr
5859 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005860 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005861 // TODO: check if defensive copies of data is needed.
5862 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005863 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005864 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5865 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005866 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005867 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005868 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005869 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5870 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005871 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005872 // For this notification, arg1 contains the blocked status.
5873 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005874 break;
5875 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005876 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005877 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005878 break;
5879 }
5880 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005881 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005882 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005883 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005884 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005885 break;
5886 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005887 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005888 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005889 break;
5890 }
junyulai05986c62018-08-07 19:50:45 +08005891 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005892 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005893 msg.arg1 = arg1;
5894 break;
5895 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005896 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005897 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005898 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005899 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005900 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005901 String notification = ConnectivityManager.getCallbackName(notificationType);
5902 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005903 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005904 nri.messenger.send(msg);
5905 } catch (RemoteException e) {
5906 // may occur naturally in the race of binder death.
5907 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5908 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005909 }
5910
Hugo Benichidba33db2017-03-23 22:40:44 +09005911 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5912 bundle.putParcelable(t.getClass().getSimpleName(), t);
5913 }
5914
Paul Jensenc8b9a742014-09-30 15:37:41 -04005915 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005916 if (nai.numRequestNetworkRequests() != 0) {
5917 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5918 NetworkRequest nr = nai.requestAt(i);
5919 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005920 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005921 loge("Dead network still had at least " + nr);
5922 break;
5923 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005924 }
5925 nai.asyncChannel.disconnect();
5926 }
5927
Robert Greenwalt7b816022014-04-18 15:25:25 -07005928 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5929 if (oldNetwork == null) {
5930 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5931 return;
5932 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005933 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005934
5935 // If we get here it means that the last linger timeout for this network expired. So there
5936 // must be no other active linger timers, and we must stop lingering.
5937 oldNetwork.clearLingerState();
5938
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005939 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005940 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005941 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005942 } else {
5943 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005944 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5945 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005946 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005947 }
5948
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005949 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005950 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005951
Paul Jensen27b02b72014-07-14 12:03:33 -04005952 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005953 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005954 } catch (Exception e) {
5955 loge("Exception setting default network :" + e);
5956 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005957
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005958 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005959 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005960 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005961 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005962 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005963 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5964 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005965 }
5966
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005967 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005968 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5969 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5970 NetworkRequest nr = nri.request;
5971 if (!nr.isListen()) continue;
5972 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5973 nai.removeRequest(nri.request.requestId);
5974 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5975 }
5976 }
5977
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005978 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005979 try {
5980 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5981 } catch (RemoteException e) {
5982 e.rethrowFromSystemServer();
5983 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005984 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5985 }
5986
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005987 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5988 NetworkRequest nr = nri.request;
5989 if (!nr.isListen()) continue;
5990 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5991 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005992 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005993 }
5994 }
5995 }
5996
Paul Jensen2161a8e2014-09-11 11:00:39 -04005997 // Handles a network appearing or improving its score.
5998 //
5999 // - Evaluates all current NetworkRequests that can be
6000 // satisfied by newNetwork, and reassigns to newNetwork
6001 // any such requests for which newNetwork is the best.
6002 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006003 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04006004 // needed. A network is needed if it is the best network for
6005 // one or more NetworkRequests, or if it is a VPN.
6006 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006007 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04006008 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006009 //
6010 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
6011 // networks that have no chance (i.e. even if validated)
6012 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006013 //
6014 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6015 // it does not remove NetworkRequests that other Networks could better satisfy.
6016 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6017 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6018 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006019 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006020 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006021 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6022 // performed to tear down unvalidated networks that have no chance (i.e. even if
6023 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006024 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006025 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006026 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006027 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006028 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006029 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006030
6031 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6032 final int score = newNetwork.getCurrentScore();
6033
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006034 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006035
Paul Jensen2161a8e2014-09-11 11:00:39 -04006036 // Find and migrate to this Network any NetworkRequests for
6037 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006038 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6039 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006040 NetworkCapabilities nc = newNetwork.networkCapabilities;
6041 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006042 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006043 // Process requests in the first pass and listens in the second pass. This allows us to
6044 // change a network's capabilities depending on which requests it has. This is only
6045 // correct if the change in capabilities doesn't affect whether the network satisfies
6046 // requests or not, and doesn't affect the network's score.
6047 if (nri.request.isListen()) continue;
6048
Hugo Benichicd952782017-09-20 11:20:14 +09006049 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006050 final boolean satisfies = newNetwork.satisfies(nri.request);
6051 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006052 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006053 log("Network " + newNetwork.name() + " was already satisfying" +
6054 " request " + nri.request.requestId + ". No change.");
6055 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006056 keep = true;
6057 continue;
6058 }
6059
6060 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006061 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006062 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006063 // next check if it's better than any current network we're using for
6064 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006065 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006066 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006067 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006068 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006069 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006070 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006071 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006072 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006073 if (VDBG || DDBG){
6074 log(" accepting network in place of " + currentNetwork.name());
6075 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006076 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006077 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006078 affectedNetworks.add(currentNetwork);
6079 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006080 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006081 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006082 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006083 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006084 if (!newNetwork.addRequest(nri.request)) {
6085 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6086 }
6087 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006088 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006089 // Tell NetworkFactories about the new score, so they can stop
6090 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006091 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006092 // network. Think about if there is a way to reduce this. Push
6093 // netid->request mapping to each factory?
Chalard Jean08577fc2018-05-02 21:14:54 +09006094 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006095 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006096 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006097 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006098 if (currentNetwork != null) {
6099 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6100 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006101 }
6102 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006103 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006104 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6105 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006106 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006107 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6108 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6109 // This means this code doesn't have to handle the case where "currentNetwork" no
6110 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6111 if (DBG) {
6112 log("Network " + newNetwork.name() + " stopped satisfying" +
6113 " request " + nri.request.requestId);
6114 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006115 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006116 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006117 clearNetworkForRequest(nri.request.requestId);
Chalard Jean08577fc2018-05-02 21:14:54 +09006118 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006119 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006120 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6121 newNetwork.name() +
6122 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006123 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006124 // TODO: Technically, sending CALLBACK_LOST here is
6125 // incorrect if there is a replacement network currently
6126 // connected that can satisfy nri, which is a request
6127 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006128 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6129 // so this code is only incorrect for a network that loses
6130 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006131 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006132 }
6133 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006134 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006135 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006136 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006137 makeDefault(newNetwork);
6138 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006139 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006140 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006141 // Have a new default network, release the transition wakelock in
6142 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006143 }
6144
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006145 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6146 Slog.wtf(TAG, String.format(
6147 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006148 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006149 }
6150 if (newNetwork.getCurrentScore() != score) {
6151 Slog.wtf(TAG, String.format(
6152 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006153 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006154 }
6155
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006156 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006157 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6158 // If the network went from background to foreground or vice versa, we need to update
6159 // its foreground state. It is safe to do this after rematching the requests because
6160 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6161 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006162 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006163 } else {
6164 processListenRequests(newNetwork, false);
6165 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006166
Paul Jensencf4c2c62015-07-01 14:16:32 -04006167 // do this after the default net is switched, but
6168 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006169 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006170
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006171 // Linger any networks that are no longer needed. This should be done after sending the
6172 // available callback for newNetwork.
6173 for (NetworkAgentInfo nai : affectedNetworks) {
6174 updateLingerState(nai, now);
6175 }
6176 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6177 // does not need to be done in any particular order.
6178 updateLingerState(newNetwork, now);
6179
Paul Jensencf4c2c62015-07-01 14:16:32 -04006180 if (isNewDefault) {
6181 // Maintain the illusion: since the legacy API only
6182 // understands one network at a time, we must pretend
6183 // that the current default network disconnected before
6184 // the new one connected.
6185 if (oldDefaultNetwork != null) {
6186 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6187 oldDefaultNetwork, true);
6188 }
6189 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6190 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6191 notifyLockdownVpn(newNetwork);
6192 }
6193
Robert Greenwalt7b816022014-04-18 15:25:25 -07006194 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006195 // Notify battery stats service about this network, both the normal
6196 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006197 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006198 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006199 final IBatteryStats bs = BatteryStatsService.getService();
6200 final int type = newNetwork.networkInfo.getType();
6201
6202 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6203 bs.noteNetworkInterfaceType(baseIface, type);
6204 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6205 final String stackedIface = stacked.getInterfaceName();
6206 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006207 }
6208 } catch (RemoteException ignored) {
6209 }
6210
Robert Greenwalt152ed372014-12-17 17:19:53 -08006211 // This has to happen after the notifyNetworkCallbacks as that tickles each
6212 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006213 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006214 // and will generally do a dns request so they can ensureRouteToHost and if
6215 // they do that before the callbacks happen they'll use the default network.
6216 //
6217 // TODO: Is there still a race here? We send the broadcast
6218 // after sending the callback, but if the app can receive the
6219 // broadcast before the callback, it might still break.
6220 //
6221 // This *does* introduce a race where if the user uses the new api
6222 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6223 // they may get old info. Reverse this after the old startUsing api is removed.
6224 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006225 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6226 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006227 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006228 // legacy type tracker filters out repeat adds
6229 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6230 }
6231 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006232
6233 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6234 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6235 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6236 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6237 if (newNetwork.isVPN()) {
6238 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6239 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006240 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006241 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6242 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006243 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006244 if (nai.getLingerExpiry() > 0) {
6245 // This network has active linger timers and no requests, but is not
6246 // lingering. Linger it.
6247 //
6248 // One way (the only way?) this can happen if this network is unvalidated
6249 // and became unneeded due to another network improving its score to the
6250 // point where this network will no longer be able to satisfy any requests
6251 // even if it validates.
6252 updateLingerState(nai, now);
6253 } else {
6254 if (DBG) log("Reaping " + nai.name());
6255 teardownUnneededNetwork(nai);
6256 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006257 }
6258 }
6259 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006260 }
6261
Paul Jensen1c7ba022015-06-16 14:27:36 -04006262 /**
6263 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6264 * being disconnected.
6265 * @param changed If only one Network's score or capabilities have been modified since the last
6266 * time this function was called, pass this Network in this argument, otherwise pass
6267 * null.
6268 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6269 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6270 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6271 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6272 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006273 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006274 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006275 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6276 // to avoid the slowness. It is not simply enough to process just "changed", for
6277 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006278 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006279
6280 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6281 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6282 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006283 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006284 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006285 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006286 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006287 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6288 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6289 // Rematch higher scoring networks first to prevent requests first matching a lower
6290 // scoring network and then a higher scoring network, which could produce multiple
6291 // callbacks and inadvertently unlinger networks.
6292 Arrays.sort(nais);
6293 for (NetworkAgentInfo nai : nais) {
6294 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006295 // Only reap the last time through the loop. Reaping before all rematching
6296 // is complete could incorrectly teardown a network that hasn't yet been
6297 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006298 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006299 : ReapUnvalidatedNetworks.REAP,
6300 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006301 }
6302 }
6303 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006304
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006305 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006306 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006307 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006308 // For now only update icons for default connection.
6309 // TODO: Update WiFi and cellular icons separately. b/17237507
6310 if (!isDefaultNetwork(nai)) return;
6311
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006312 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006313 // Don't repeat publish.
6314 if (newInetCondition == mDefaultInetConditionPublished) return;
6315
6316 mDefaultInetConditionPublished = newInetCondition;
6317 sendInetConditionBroadcast(nai.networkInfo);
6318 }
6319
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006320 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006321 synchronized (mVpns) {
6322 if (mLockdownTracker != null) {
6323 if (nai != null && nai.isVPN()) {
6324 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6325 } else {
6326 mLockdownTracker.onNetworkInfoChanged();
6327 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006328 }
6329 }
6330 }
6331
Robert Greenwalt7b816022014-04-18 15:25:25 -07006332 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006333 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006334 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006335 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006336 synchronized (networkAgent) {
6337 oldInfo = networkAgent.networkInfo;
6338 networkAgent.networkInfo = newInfo;
6339 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006340 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006341
Robert Greenwalt7b816022014-04-18 15:25:25 -07006342 if (DBG) {
6343 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6344 (oldInfo == null ? "null" : oldInfo.getState()) +
6345 " to " + state);
6346 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006347
Robin Lee585e2482016-05-01 23:00:00 +01006348 if (!networkAgent.created
6349 && (state == NetworkInfo.State.CONNECTED
6350 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006351
6352 // A network that has just connected has zero requests and is thus a foreground network.
6353 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6354
Robert Greenwalt7b816022014-04-18 15:25:25 -07006355 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006356 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006357 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006358 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006359 (networkAgent.networkMisc == null ||
6360 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006361 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006362 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006363 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006364 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006365 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006366 loge("Error creating network " + networkAgent.network.netId + ": "
6367 + e.getMessage());
6368 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006369 }
Paul Jenseneec75412014-08-04 12:21:19 -04006370 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006371 }
6372
6373 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6374 networkAgent.everConnected = true;
6375
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006376 if (networkAgent.linkProperties == null) {
6377 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6378 }
6379
Erik Kline736353a2018-03-21 07:18:33 -07006380 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006381 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6382 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006383
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006384 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6385 // command must be sent after updating LinkProperties to maximize chances of
6386 // NetworkMonitor seeing the correct LinkProperties when starting.
6387 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6388 try {
lucaslin43338992019-03-20 18:21:59 +08006389 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6390 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6391 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006392 networkAgent.networkMonitor().notifyNetworkConnected();
6393 } catch (RemoteException e) {
6394 e.rethrowFromSystemServer();
6395 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006396 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006397
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006398 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6399 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6400 // capabilities, so it only needs to be done once on initial connect, not every time the
6401 // network's capabilities change. Note that we do this before rematching the network,
6402 // so we could decide to tear it down immediately afterwards. That's fine though - on
6403 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6404 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006405 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006406
Varun Anand4fa80e82019-02-06 10:13:38 -08006407 if (networkAgent.isVPN()) {
6408 updateAllVpnsCapabilities();
6409 }
6410
Paul Jensen2161a8e2014-09-11 11:00:39 -04006411 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006412 final long now = SystemClock.elapsedRealtime();
6413 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006414
6415 // This has to happen after matching the requests, because callbacks are just requests.
6416 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006417 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006418 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006419 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006420 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006421 }
Chalard Jean392971c2018-05-11 20:19:20 +09006422 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006423 if (networkAgent.isVPN()) {
6424 // As the active or bound network changes for apps, broadcast the default proxy, as
6425 // apps may need to update their proxy data. This is called after disconnecting from
6426 // VPN to make sure we do not broadcast the old proxy data.
6427 // TODO(b/122649188): send the broadcast only to VPN users.
6428 mProxyTracker.sendProxyBroadcast();
6429 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006430 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6431 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006432 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006433 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006434 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006435 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006436 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6437 networkAgent.networkCapabilities);
6438 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6439 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006440 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6441 ConnectivityManager.CALLBACK_SUSPENDED :
6442 ConnectivityManager.CALLBACK_RESUMED));
6443 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006444 }
6445 }
6446
Robert Greenwaltac96c522014-06-03 16:43:57 -07006447 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006448 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006449 if (score < 0) {
6450 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6451 "). Bumping score to min of 0");
6452 score = 0;
6453 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006454
Paul Jensen2161a8e2014-09-11 11:00:39 -04006455 final int oldScore = nai.getCurrentScore();
6456 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006457
Paul Jensen85cf78e2015-06-25 13:25:07 -04006458 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006459
Paul Jensenc8b9a742014-09-30 15:37:41 -04006460 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006461 }
6462
Erik Klinec75d4fa2017-02-15 19:59:17 +09006463 // Notify only this one new request of the current state. Transfer all the
6464 // current state by calling NetworkCapabilities and LinkProperties callbacks
6465 // so that callers can be guaranteed to have as close to atomicity in state
6466 // transfer as can be supported by this current API.
6467 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006468 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006469 if (nri.mPendingIntent != null) {
6470 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6471 // Attempt no subsequent state pushes where intents are involved.
6472 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006473 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006474
junyulai05986c62018-08-07 19:50:45 +08006475 final boolean metered = nai.networkCapabilities.isMetered();
6476 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6477 metered, mRestrictBackground);
6478 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6479 }
6480
6481 /**
6482 * Notify of the blocked state apps with a registered callback matching a given NAI.
6483 *
6484 * Unlike other callbacks, blocked status is different between each individual uid. So for
6485 * any given nai, all requests need to be considered according to the uid who filed it.
6486 *
6487 * @param nai The target NetworkAgentInfo.
6488 * @param oldMetered True if the previous network capabilities is metered.
6489 * @param newRestrictBackground True if data saver is enabled.
6490 */
6491 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6492 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6493
6494 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6495 NetworkRequest nr = nai.requestAt(i);
6496 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6497 final int uidRules = mUidRules.get(nri.mUid);
6498 final boolean oldBlocked, newBlocked;
6499 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6500 // between these two calls.
6501 synchronized (mVpns) {
6502 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6503 oldRestrictBackground);
6504 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6505 newRestrictBackground);
6506 }
6507 if (oldBlocked != newBlocked) {
6508 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6509 encodeBool(newBlocked));
6510 }
6511 }
6512 }
6513
6514 /**
6515 * Notify apps with a given UID of the new blocked state according to new uid rules.
6516 * @param uid The uid for which the rules changed.
6517 * @param newRules The new rules to apply.
6518 */
6519 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6520 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6521 final boolean metered = nai.networkCapabilities.isMetered();
6522 final boolean oldBlocked, newBlocked;
6523 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6524 // rules changed event. And this function actually loop through all connected nai and
6525 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6526 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6527 synchronized (mVpns) {
6528 oldBlocked = isUidNetworkingWithVpnBlocked(
6529 uid, mUidRules.get(uid), metered, mRestrictBackground);
6530 newBlocked = isUidNetworkingWithVpnBlocked(
6531 uid, newRules, metered, mRestrictBackground);
6532 }
6533 if (oldBlocked == newBlocked) {
6534 return;
6535 }
6536 final int arg = encodeBool(newBlocked);
6537 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6538 NetworkRequest nr = nai.requestAt(i);
6539 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6540 if (nri != null && nri.mUid == uid) {
6541 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6542 }
6543 }
6544 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006545 }
6546
Robert Greenwalt8d482522015-06-24 13:23:42 -07006547 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006548 // The NetworkInfo we actually send out has no bearing on the real
6549 // state of affairs. For example, if the default connection is mobile,
6550 // and a request for HIPRI has just gone away, we need to pretend that
6551 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6552 // the state to DISCONNECTED, even though the network is of type MOBILE
6553 // and is still connected.
6554 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6555 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006556 if (state != DetailedState.DISCONNECTED) {
6557 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006558 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006559 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006560 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006561 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6562 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6563 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6564 if (info.isFailover()) {
6565 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6566 nai.networkInfo.setFailover(false);
6567 }
6568 if (info.getReason() != null) {
6569 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6570 }
6571 if (info.getExtraInfo() != null) {
6572 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6573 }
6574 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006575 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006576 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006577 if (newDefaultAgent != null) {
6578 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6579 newDefaultAgent.networkInfo);
6580 } else {
6581 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6582 }
6583 }
6584 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6585 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006586 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006587 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006588 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006589 }
6590 }
6591 }
6592
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006593 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006594 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006595 String notification = ConnectivityManager.getCallbackName(notifyType);
6596 log("notifyType " + notification + " for " + networkAgent.name());
6597 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006598 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6599 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006600 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6601 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006602 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6603 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006604 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006605 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006606 } else {
6607 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6608 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006609 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006610 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006611
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006612 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6613 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6614 }
6615
Jeff Sharkey69736342014-12-08 14:50:12 -08006616 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006617 * Returns the list of all interfaces that could be used by network traffic that does not
6618 * explicitly specify a network. This includes the default network, but also all VPNs that are
6619 * currently connected.
6620 *
6621 * Must be called on the handler thread.
6622 */
6623 private Network[] getDefaultNetworks() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006624 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006625 ArrayList<Network> defaultNetworks = new ArrayList<>();
6626 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6627 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6628 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6629 defaultNetworks.add(nai.network);
6630 }
6631 }
6632 return defaultNetworks.toArray(new Network[0]);
6633 }
6634
6635 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006636 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6637 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006638 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006639 private void notifyIfacesChangedForNetworkStats() {
Varun Anand02c50ef2019-02-07 14:13:13 -08006640 ensureRunningOnConnectivityServiceThread();
6641 String activeIface = null;
6642 LinkProperties activeLinkProperties = getActiveLinkProperties();
6643 if (activeLinkProperties != null) {
6644 activeIface = activeLinkProperties.getInterfaceName();
6645 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006646 try {
Varun Anand02c50ef2019-02-07 14:13:13 -08006647 mStatsService.forceUpdateIfaces(
6648 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006649 } catch (Exception ignored) {
6650 }
6651 }
6652
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006653 @Override
6654 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006655 int user = UserHandle.getUserId(Binder.getCallingUid());
6656 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006657 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006658 return mVpns.get(user).addAddress(address, prefixLength);
6659 }
6660 }
6661
6662 @Override
6663 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006664 int user = UserHandle.getUserId(Binder.getCallingUid());
6665 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006666 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006667 return mVpns.get(user).removeAddress(address, prefixLength);
6668 }
6669 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006670
6671 @Override
6672 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006673 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006674 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006675 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006676 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006677 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006678 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006679 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006680 mHandler.post(() -> {
6681 // Update VPN's capabilities based on updated underlying network set.
6682 updateAllVpnsCapabilities();
6683 notifyIfacesChangedForNetworkStats();
6684 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006685 }
6686 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006687 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006688
6689 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006690 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006691 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006692 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006693 }
6694
6695 @Override
junyulai7c469172019-01-16 20:23:34 +08006696 public void startNattKeepalive(Network network, int intervalSeconds,
6697 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006698 enforceKeepalivePermission();
6699 mKeepaliveTracker.startNattKeepalive(
6700 getNetworkAgentInfoForNetwork(network),
junyulai7c469172019-01-16 20:23:34 +08006701 intervalSeconds, cb,
junyulaie4135282019-01-03 18:50:15 +08006702 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006703 }
6704
6705 @Override
junyulai215b8772019-01-15 11:32:44 +08006706 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
junyulai7c469172019-01-16 20:23:34 +08006707 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulai215b8772019-01-15 11:32:44 +08006708 String dstAddr) {
6709 enforceKeepalivePermission();
6710 mKeepaliveTracker.startNattKeepalive(
6711 getNetworkAgentInfoForNetwork(network), fd, resourceId,
junyulai7c469172019-01-16 20:23:34 +08006712 intervalSeconds, cb,
junyulai215b8772019-01-15 11:32:44 +08006713 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6714 }
6715
6716 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006717 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
junyulai7c469172019-01-16 20:23:34 +08006718 ISocketKeepaliveCallback cb) {
junyulai352dc2f2019-01-08 20:04:33 +08006719 enforceKeepalivePermission();
6720 mKeepaliveTracker.startTcpKeepalive(
junyulai7c469172019-01-16 20:23:34 +08006721 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
junyulai352dc2f2019-01-08 20:04:33 +08006722 }
6723
6724 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006725 public void stopKeepalive(Network network, int slot) {
6726 mHandler.sendMessage(mHandler.obtainMessage(
junyulaie4135282019-01-03 18:50:15 +08006727 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006728 }
6729
6730 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006731 public void factoryReset() {
6732 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006733
6734 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6735 return;
6736 }
6737
Robin Lee3b3dd942015-05-12 18:14:58 +01006738 final int userId = UserHandle.getCallingUserId();
6739
Stuart Scottf1fb3972015-04-02 18:00:02 -07006740 // Turn airplane mode off
6741 setAirplaneMode(false);
6742
Stuart Scotte3e314d2015-04-20 14:07:45 -07006743 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6744 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006745 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006746 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006747 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006748 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006749 }
6750
Stuart Scotte3e314d2015-04-20 14:07:45 -07006751 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006752 // Remove always-on package
6753 synchronized (mVpns) {
6754 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6755 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006756 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006757 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6758 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006759
Hugo Benichi69744342017-11-27 10:57:16 +09006760 // Turn Always-on VPN off
6761 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6762 final long ident = Binder.clearCallingIdentity();
6763 try {
6764 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6765 mLockdownEnabled = false;
6766 setLockdownTracker(null);
6767 } finally {
6768 Binder.restoreCallingIdentity(ident);
6769 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006770 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006771
Hugo Benichi69744342017-11-27 10:57:16 +09006772 // Turn VPN off
6773 VpnConfig vpnConfig = getVpnConfig(userId);
6774 if (vpnConfig != null) {
6775 if (vpnConfig.legacy) {
6776 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6777 } else {
6778 // Prevent this app (packagename = vpnConfig.user) from initiating
6779 // VPN connections in the future without user intervention.
6780 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006781
Hugo Benichi69744342017-11-27 10:57:16 +09006782 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6783 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006784 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006785 }
6786 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006787
6788 Settings.Global.putString(mContext.getContentResolver(),
6789 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006790 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006791
Ricky Wai44dcbde2018-01-23 04:09:45 +00006792 @Override
6793 public byte[] getNetworkWatchlistConfigHash() {
6794 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6795 if (nwm == null) {
6796 loge("Unable to get NetworkWatchlistManager");
6797 return null;
6798 }
6799 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6800 return nwm.getWatchlistConfigHash();
6801 }
6802
Paul Jensencf4c2c62015-07-01 14:16:32 -04006803 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006804 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6805 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006806 }
6807
6808 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006809 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6810 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6811 }
6812
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006813 @VisibleForTesting
6814 public boolean hasService(String name) {
6815 return ServiceManager.checkService(name) != null;
6816 }
6817
Hugo Benichi64901e52017-10-19 14:42:40 +09006818 @VisibleForTesting
6819 protected IpConnectivityMetrics.Logger metricsLogger() {
6820 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6821 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006822 }
6823
6824 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006825 int[] transports = nai.networkCapabilities.getTransportTypes();
6826 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006827 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006828
6829 private static boolean toBool(int encodedBoolean) {
6830 return encodedBoolean != 0; // Only 0 means false.
6831 }
6832
6833 private static int encodeBool(boolean b) {
6834 return b ? 1 : 0;
6835 }
mswest46386886f2018-03-12 10:34:34 -07006836
6837 @Override
6838 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6839 FileDescriptor err, String[] args, ShellCallback callback,
6840 ResultReceiver resultReceiver) {
6841 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6842 }
6843
6844 private class ShellCmd extends ShellCommand {
6845
6846 @Override
6847 public int onCommand(String cmd) {
6848 if (cmd == null) {
6849 return handleDefaultCommands(cmd);
6850 }
6851 final PrintWriter pw = getOutPrintWriter();
6852 try {
6853 switch (cmd) {
6854 case "airplane-mode":
6855 final String action = getNextArg();
6856 if ("enable".equals(action)) {
6857 setAirplaneMode(true);
6858 return 0;
6859 } else if ("disable".equals(action)) {
6860 setAirplaneMode(false);
6861 return 0;
6862 } else if (action == null) {
6863 final ContentResolver cr = mContext.getContentResolver();
6864 final int enabled = Settings.Global.getInt(cr,
6865 Settings.Global.AIRPLANE_MODE_ON);
6866 pw.println(enabled == 0 ? "disabled" : "enabled");
6867 return 0;
6868 } else {
6869 onHelp();
6870 return -1;
6871 }
6872 default:
6873 return handleDefaultCommands(cmd);
6874 }
6875 } catch (Exception e) {
6876 pw.println(e);
6877 }
6878 return -1;
6879 }
6880
6881 @Override
6882 public void onHelp() {
6883 PrintWriter pw = getOutPrintWriter();
6884 pw.println("Connectivity service commands:");
6885 pw.println(" help");
6886 pw.println(" Print this help text.");
6887 pw.println(" airplane-mode [enable|disable]");
6888 pw.println(" Turn airplane mode on or off.");
6889 pw.println(" airplane-mode");
6890 pw.println(" Get airplane mode.");
6891 }
6892 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006893
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006894 @GuardedBy("mVpns")
6895 private Vpn getVpnIfOwner() {
6896 final int uid = Binder.getCallingUid();
6897 final int user = UserHandle.getUserId(uid);
6898
6899 final Vpn vpn = mVpns.get(user);
6900 if (vpn == null) {
6901 return null;
6902 } else {
6903 final VpnInfo info = vpn.getVpnInfo();
6904 return (info == null || info.ownerUid != uid) ? null : vpn;
6905 }
6906 }
6907
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006908 /**
6909 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6910 * for testing.
6911 */
6912 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6913 if (checkNetworkStackPermission()) {
6914 return null;
6915 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006916 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006917 Vpn vpn = getVpnIfOwner();
6918 if (vpn != null) {
6919 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006920 }
6921 }
6922 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6923 + "permission");
6924 }
6925
6926 /**
6927 * @param connectionInfo the connection to resolve.
6928 * @return {@code uid} if the connection is found and the app has permission to observe it
6929 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6930 * connection is not found.
6931 */
6932 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6933 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6934 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6935 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6936 }
6937
6938 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6939 connectionInfo.local, connectionInfo.remote);
6940
6941 /* Filter out Uids not associated with the VPN. */
6942 if (vpn != null && !vpn.appliesToUid(uid)) {
6943 return INVALID_UID;
6944 }
6945
6946 return uid;
6947 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006948
6949 @Override
6950 public boolean isCallerCurrentAlwaysOnVpnApp() {
6951 synchronized (mVpns) {
6952 Vpn vpn = getVpnIfOwner();
6953 return vpn != null && vpn.getAlwaysOn();
6954 }
6955 }
6956
6957 @Override
6958 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6959 synchronized (mVpns) {
6960 Vpn vpn = getVpnIfOwner();
6961 return vpn != null && vpn.getLockdown();
6962 }
6963 }
Benedict Wong99a48412018-11-09 14:45:34 -08006964
6965 /**
6966 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
6967 *
6968 * <p>The TestNetworkService must be run in the system server due to TUN creation.
6969 */
6970 @Override
6971 public IBinder startOrGetTestNetworkService() {
6972 synchronized (mTNSLock) {
6973 TestNetworkService.enforceTestNetworkPermissions(mContext);
6974
6975 if (mTNS == null) {
6976 mTNS = new TestNetworkService(mContext, mNMS);
6977 }
6978
6979 return mTNS;
6980 }
6981 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006982}