blob: 8384ca054f6d56b2b723539c37cd20912b34053b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
lucasline252a742019-03-12 13:08:03 +080028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090029import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040030import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090032import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
34import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
lucasline252a742019-03-12 13:08:03 +080038import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090039import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060040import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080041import static android.net.NetworkPolicyManager.RULE_NONE;
42import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090043import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090044import static android.net.shared.NetworkParcelableUtil.toStableParcelable;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070045import static android.os.Process.INVALID_UID;
46import static android.system.OsConstants.IPPROTO_TCP;
47import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060048
Hugo Benichia0385682017-03-22 17:07:57 +090049import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060050
Wenchao Tongf5ea3402015-03-04 13:26:38 -080051import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080052import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090053import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070054import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070055import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.ContentResolver;
57import android.content.Context;
58import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070059import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070060import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070061import android.database.ContentObserver;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090062import android.net.CaptivePortal;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070063import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.ConnectivityManager;
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +090065import android.net.ICaptivePortal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050067import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080068import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050069import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070070import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090071import android.net.INetworkMonitor;
72import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070073import android.net.INetworkPolicyListener;
74import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070075import android.net.INetworkStatsService;
markchien26299ed2019-02-27 14:56:11 +080076import android.net.ITetheringEventCallback;
Lorenzo Colitti6998fa82019-01-08 10:04:25 +090077import android.net.InetAddresses;
78import android.net.IpPrefix;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080079import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070080import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010081import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080082import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070083import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070084import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070085import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070086import android.net.NetworkConfig;
Chalard Jean05ab6812018-05-02 21:14:54 +090087import android.net.NetworkFactory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070089import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070090import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090091import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070092import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070093import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070094import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090095import android.net.NetworkStack;
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +090096import android.net.NetworkStackClient;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070097import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070098import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000099import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900100import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -0400101import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -0700102import android.net.RouteInfo;
junyulai06835112019-01-03 18:50:15 +0800103import android.net.SocketKeepalive;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400104import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -0400105import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -0600106import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +0900107import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900108import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700109import android.net.netlink.InetDiagMessage;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900110import android.net.shared.NetworkMonitorUtils;
111import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900112import android.net.util.MultinetworkPolicyTracker;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +0900113import android.net.util.NetdService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800115import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700116import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700118import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700120import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.os.Looper;
122import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700123import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700124import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900125import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700126import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700127import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700128import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800129import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900130import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900131import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700132import android.os.ShellCallback;
133import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900134import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700135import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400136import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700138import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700139import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700140import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900142import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700143import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600144import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900145import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800146import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700147import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500148import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700149import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Wink Savilleab9321d2013-06-29 21:10:57 -0700152import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400153import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400154import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700155import com.android.internal.app.IBatteryStats;
Remi NGUYEN VANde602212019-01-30 15:22:01 +0900156import com.android.internal.logging.MetricsLogger;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700157import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700158import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800159import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700160import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900161import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700162import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600163import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700164import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900165import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900166import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700167import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700168import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400169import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900170import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500171import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900172import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900173import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100174import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700175import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900176import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700177import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600178import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900179import com.android.server.connectivity.NetworkNotificationManager;
180import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700181import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900182import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800183import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700184import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100185import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500186import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700187import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700188import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900189import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700190import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600191
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700192import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700193
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700194import org.xmlpull.v1.XmlPullParser;
195import org.xmlpull.v1.XmlPullParserException;
196
197import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700199import java.io.FileNotFoundException;
200import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700201import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700203import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700204import java.net.InetAddress;
205import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700206import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700207import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700208import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900209import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800210import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700211import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700212import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700214import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700215import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900216import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600217import java.util.SortedSet;
218import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
220/**
221 * @hide
222 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800223public class ConnectivityService extends IConnectivityManager.Stub
224 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900225 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Chalard Jean4133a122018-06-04 13:33:12 +0900227 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900228 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900229 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900230 private static final String NETWORK_ARG = "networks";
231 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900232
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900233 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900234 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
235 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900237 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700238
Jeff Sharkey899223b2012-08-04 15:24:58 -0700239 // TODO: create better separation between radio types and network types
240
Robert Greenwalt42acef32009-08-12 16:08:25 -0700241 // how long to wait before switching back to a radio's default network
242 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
243 // system property that can override the above value
244 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
245 "android.telephony.apn-restore";
246
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900247 // How long to wait before putting up a "This network doesn't have an Internet connection,
248 // connect anyway?" dialog after the user selects a network that doesn't validate.
249 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
250
lucaslind2e045e02019-01-24 15:55:30 +0800251 // How long to dismiss network notification.
252 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
253
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900254 // Default to 30s linger time-out. Modifiable only for testing.
255 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
256 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
257 @VisibleForTesting
258 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
259
Jeremy Joslin79294842014-12-03 17:15:28 -0800260 // How long to delay to removal of a pending intent based request.
261 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
262 private final int mReleasePendingIntentDelayMs;
263
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900264 private MockableSystemProperties mSystemProperties;
265
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800266 private Tethering mTethering;
267
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700268 private final PermissionMonitor mPermissionMonitor;
269
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700270 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700271
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900272 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700273 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900274 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700275
Hugo Benichi69744342017-11-27 10:57:16 +0900276 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
277 // a direct call to LockdownVpnTracker.isEnabled().
278 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700279 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900280 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700281 private LockdownVpnTracker mLockdownTracker;
282
junyulai05986c62018-08-07 19:50:45 +0800283 /**
284 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
285 * handler thread, they don't need a lock.
286 */
287 private SparseIntArray mUidRules = new SparseIntArray();
288 /** Flag indicating if background data is restricted. */
289 private boolean mRestrictBackground;
290
Erik Klineda4bfa82015-04-30 12:58:40 +0900291 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700292 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700293 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
Luke Huang4e25ec62018-09-27 16:58:23 +0800295 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800296 @VisibleForTesting
297 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800298 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700299 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900300 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700301
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700302 private String mCurrentTcpBufferSizes;
303
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900304 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900305 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
306 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900307
Paul Jensenb10e37f2014-11-25 12:33:08 -0500308 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400309 // Tear down networks that have no chance (e.g. even if validated) of becoming
310 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500311 // all networks have been rematched against all NetworkRequests.
312 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400313 // Don't reap networks. This should be passed when some networks have not yet been
314 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500315 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900316 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500317
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900318 private enum UnneededFor {
319 LINGER, // Determine whether this network is unneeded and should be lingered.
320 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
321 }
322
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700323 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700324 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700325 * from one net to another. Clear happens when we get a new
326 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
327 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700328 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700329 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700330
Robert Greenwalt434203a2010-10-11 16:00:27 -0700331 /**
332 * used internally to reload global proxy settings
333 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700334 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700335
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700336 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400337 * PAC manager has received new port.
338 */
339 private static final int EVENT_PROXY_HAS_CHANGED = 16;
340
Robert Greenwalte049c232014-04-11 15:53:27 -0700341 /**
342 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700343 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700344 */
345 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
346
Robert Greenwalt7b816022014-04-18 15:25:25 -0700347 /**
348 * used internally when registering NetworkAgents
349 * obj = Messenger
350 */
351 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
352
Robert Greenwalt9258c642014-03-26 16:47:06 -0700353 /**
354 * used to add a network request
355 * includes a NetworkRequestInfo
356 */
357 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
358
359 /**
360 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900361 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700362 * cancel it.
363 * includes a NetworkRequestInfo
364 */
365 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
366
367 /**
368 * used to add a network listener - no request
369 * includes a NetworkRequestInfo
370 */
371 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
372
373 /**
374 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400375 * arg1 = UID of caller
376 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700377 */
378 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
379
Robert Greenwalta67be032014-05-16 15:49:14 -0700380 /**
381 * used internally when registering NetworkFactories
382 * obj = Messenger
383 */
384 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
385
Robert Greenwalt27711812014-06-25 16:45:57 -0700386 /**
387 * used internally to expire a wakelock when transitioning
388 * from one net to another. Expire happens when we fail to find
389 * a new network (typically after 1 minute) -
390 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
391 * a replacement network.
392 */
393 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
394
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700395 /**
396 * Used internally to indicate the system is ready.
397 */
398 private static final int EVENT_SYSTEM_READY = 25;
399
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800400 /**
401 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400402 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800403 */
404 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
405
406 /**
407 * used to remove a pending intent and its associated network request.
408 * arg1 = UID of caller
409 * obj = PendingIntent
410 */
411 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
412
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900413 /**
414 * used to specify whether a network should be used even if unvalidated.
415 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
416 * arg2 = whether to remember this choice in the future (1 or 0)
417 * obj = network
418 */
419 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
420
421 /**
422 * used to ask the user to confirm a connection to an unvalidated network.
423 * obj = network
424 */
425 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700426
Erik Klineda4bfa82015-04-30 12:58:40 +0900427 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700428 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900429 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700430 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900431
Paul Jensen694f2b82015-06-17 14:15:39 -0400432 /**
433 * used to add a network listener with a pending intent
434 * obj = NetworkRequestInfo
435 */
436 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
437
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900438 /**
439 * used to specify whether a network should not be penalized when it becomes unvalidated.
440 */
441 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
442
443 /**
444 * used to trigger revalidation of a network.
445 */
446 private static final int EVENT_REVALIDATE_NETWORK = 36;
447
Erik Klinea24d4592018-01-11 21:07:29 +0900448 // Handle changes in Private DNS settings.
449 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
450
dalyk7301aa42018-03-05 12:42:22 -0500451 // Handle private DNS validation status updates.
452 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
453
junyulai05986c62018-08-07 19:50:45 +0800454 /**
455 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
456 */
457 private static final int EVENT_UID_RULES_CHANGED = 39;
458
459 /**
460 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
461 */
462 private static final int EVENT_DATA_SAVER_CHANGED = 40;
463
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900464 /**
465 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
466 * been tested.
467 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
468 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
469 * arg2 = NetID.
470 */
471 public static final int EVENT_NETWORK_TESTED = 41;
472
473 /**
474 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
475 * config was resolved.
476 * obj = PrivateDnsConfig
477 * arg2 = netid
478 */
479 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
480
481 /**
482 * Request ConnectivityService display provisioning notification.
483 * arg1 = Whether to make the notification visible.
484 * arg2 = NetID.
485 * obj = Intent to be launched when notification selected by user, null if !arg1.
486 */
487 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
488
489 /**
lucaslind2e045e02019-01-24 15:55:30 +0800490 * This event can handle dismissing notification by given network id.
491 */
492 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
493
494 /**
lucasline252a742019-03-12 13:08:03 +0800495 * Used to specify whether a network should be used even if connectivity is partial.
496 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
497 * false)
498 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
499 * obj = network
500 */
501 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 45;
502
503 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900504 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
505 * should be shown.
506 */
507 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
508
509 /**
510 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
511 * should be hidden.
512 */
513 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
514
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900515 private static String eventName(int what) {
516 return sMagicDecoderRing.get(what, Integer.toString(what));
517 }
518
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900519 /** Handler thread used for both of the handlers below. */
520 @VisibleForTesting
521 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700522 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700523 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700524 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700525 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900526 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700527
Mike Lockwood0f79b542009-08-14 14:18:49 -0400528 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800529 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400530
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700531 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700532 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800533 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700534
Chalard Jean52c2aa72018-06-07 16:44:04 +0900535 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
536 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000537 @VisibleForTesting
538 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400539
Erik Klineda4bfa82015-04-30 12:58:40 +0900540 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700541
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400542 private UserManager mUserManager;
543
Chalard Jean4133a122018-06-04 13:33:12 +0900544 private NetworkConfig[] mNetConfigs;
545 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700546
Robert Greenwalt50393202011-06-21 17:26:14 -0700547 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900548 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700549
Chalard Jean4133a122018-06-04 13:33:12 +0900550 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400551
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900552 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900553 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900554 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900555
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700556 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800557 private static final int MIN_NET_ID = 100; // some reserved marks
558 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700559 private int mNextNetId = MIN_NET_ID;
560
Robert Greenwalt34524f02014-05-18 16:22:10 -0700561 // sequence number of NetworkRequests
562 private int mNextNetworkRequestId = 1;
563
Erik Kline7523eb32015-07-09 18:24:03 +0900564 // NetworkRequest activity String log entries.
565 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
566 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
567
Hugo Benichic2ae2872016-07-11 11:05:12 +0900568 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900569 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900570 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
571
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900572 private static final int MAX_WAKELOCK_LOGS = 20;
573 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900574 private int mTotalWakelockAcquisitions = 0;
575 private int mTotalWakelockReleases = 0;
576 private long mTotalWakelockDurationMs = 0;
577 private long mMaxWakelockDurationMs = 0;
578 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900579
Hugo Benichif9fdf872016-07-28 17:53:06 +0900580 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900581
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700582 @GuardedBy("mBandwidthRequests")
583 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
584
Erik Kline065ab6e2016-10-02 18:02:14 +0900585 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900586 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900587
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900588 @VisibleForTesting
589 final MultipathPolicyTracker mMultipathPolicyTracker;
590
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700591 /**
592 * Implements support for the legacy "one network per network type" model.
593 *
594 * We used to have a static array of NetworkStateTrackers, one for each
595 * network type, but that doesn't work any more now that we can have,
596 * for example, more that one wifi network. This class stores all the
597 * NetworkAgentInfo objects that support a given type, but the legacy
598 * API will only see the first one.
599 *
600 * It serves two main purposes:
601 *
602 * 1. Provide information about "the network for a given type" (since this
603 * API only supports one).
604 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
605 * the first network for a given type changes, or if the default network
606 * changes.
607 */
608 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900610 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700613 /**
614 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
615 * Each list holds references to all NetworkAgentInfos that are used to
616 * satisfy requests for that network type.
617 *
618 * This array is built out at startup such that an unsupported network
619 * doesn't get an ArrayList instance, making this a tristate:
620 * unsupported, supported but not active and active.
621 *
622 * The actual lists are populated when we scan the network types that
623 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900624 *
625 * Threading model:
626 * - addSupportedType() is only called in the constructor
627 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
628 * They are therefore not thread-safe with respect to each other.
629 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
630 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
631 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900633 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700634
635 public LegacyTypeTracker() {
636 mTypeLists = (ArrayList<NetworkAgentInfo>[])
637 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
638 }
639
640 public void addSupportedType(int type) {
641 if (mTypeLists[type] != null) {
642 throw new IllegalStateException(
643 "legacy list for type " + type + "already initialized");
644 }
Chalard Jean4133a122018-06-04 13:33:12 +0900645 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700646 }
647
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700648 public boolean isTypeSupported(int type) {
649 return isNetworkTypeValid(type) && mTypeLists[type] != null;
650 }
651
652 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900653 synchronized (mTypeLists) {
654 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
655 return mTypeLists[type].get(0);
656 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700657 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900658 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700659 }
660
Robert Greenwalt8d482522015-06-24 13:23:42 -0700661 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900662 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900663 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700664 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900665 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900666 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900667 }
668 }
669
670 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700671 public void add(int type, NetworkAgentInfo nai) {
672 if (!isTypeSupported(type)) {
673 return; // Invalid network type.
674 }
675 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
676
677 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
678 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700679 return;
680 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900681 synchronized (mTypeLists) {
682 list.add(nai);
683 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900684
685 // 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 +0900686 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900687 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700688 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
689 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700691 }
692
Lorenzo Colittia793a672014-07-31 23:20:17 +0900693 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900694 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900695 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
696 if (list == null || list.isEmpty()) {
697 return;
698 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900699 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900700
Hugo Benichi78caa2582016-06-21 09:48:07 +0900701 synchronized (mTypeLists) {
702 if (!list.remove(nai)) {
703 return;
704 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900705 }
706
Robert Greenwalt8d482522015-06-24 13:23:42 -0700707 final DetailedState state = DetailedState.DISCONNECTED;
708
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900709 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700710 maybeLogBroadcast(nai, state, type, wasDefault);
711 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900712 }
713
714 if (!list.isEmpty() && wasFirstNetwork) {
715 if (DBG) log("Other network available for type " + type +
716 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900717 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700718 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
719 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900720 }
721 }
722
723 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900724 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
725 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700726 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900727 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700728 }
729 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700730
Robert Greenwalt8d482522015-06-24 13:23:42 -0700731 // send out another legacy broadcast - currently only used for suspend/unsuspend
732 // toggle
733 public void update(NetworkAgentInfo nai) {
734 final boolean isDefault = isDefaultNetwork(nai);
735 final DetailedState state = nai.networkInfo.getDetailedState();
736 for (int type = 0; type < mTypeLists.length; type++) {
737 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700738 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900739 final boolean isFirst = contains && (nai == list.get(0));
740 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700741 maybeLogBroadcast(nai, state, type, isDefault);
742 sendLegacyNetworkBroadcast(nai, state, type);
743 }
744 }
745 }
746
Lorenzo Colittia793a672014-07-31 23:20:17 +0900747 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900748 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900749 String state = (nai.networkInfo != null) ?
750 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
751 "???/???";
752 return name + " " + state;
753 }
754
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700755 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900756 pw.println("mLegacyTypeTracker:");
757 pw.increaseIndent();
758 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700759 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900760 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700761 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900762 pw.println();
763 pw.println("Current state:");
764 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900765 synchronized (mTypeLists) {
766 for (int type = 0; type < mTypeLists.length; type++) {
767 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
768 for (NetworkAgentInfo nai : mTypeLists[type]) {
769 pw.println(type + " " + naiToString(nai));
770 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900771 }
772 }
773 pw.decreaseIndent();
774 pw.decreaseIndent();
775 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700776 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700777 }
778 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
779
Vishnu Nair5c010902017-10-26 10:08:50 -0700780 /**
781 * Helper class which parses out priority arguments and dumps sections according to their
782 * priority. If priority arguments are omitted, function calls the legacy dump command.
783 */
784 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
785 @Override
786 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
787 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
788 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
789 }
790
791 @Override
792 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
793 doDump(fd, pw, args, asProto);
794 }
795
796 @Override
797 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
798 doDump(fd, pw, args, asProto);
799 }
800 };
801
Jeff Sharkey899223b2012-08-04 15:24:58 -0700802 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700803 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900804 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
805 }
806
807 @VisibleForTesting
808 protected ConnectivityService(Context context, INetworkManagementService netManager,
809 INetworkStatsService statsService, INetworkPolicyManager policyManager,
810 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800811 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800812
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900813 mSystemProperties = getSystemProperties();
814
Hugo Benichif9fdf872016-07-28 17:53:06 +0900815 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900816 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900817 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900818 mNetworkRequests.put(mDefaultRequest, defaultNRI);
819 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900820
Chalard Jeandda156a2018-01-10 21:19:32 +0900821 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900822 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700823
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700824 // The default WiFi request is a background request so that apps using WiFi are
825 // migrated to a better network (typically ethernet) when one comes up, instead
826 // of staying on WiFi forever.
827 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
828 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
829
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900830 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900831 mHandlerThread.start();
832 mHandler = new InternalHandler(mHandlerThread.getLooper());
833 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700834
Jeremy Joslin79294842014-12-03 17:15:28 -0800835 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
836 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
837
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900838 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900839
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700840 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800841 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800842 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700843 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900844 mPolicyManagerInternal = checkNotNull(
845 LocalServices.getService(NetworkPolicyManagerInternal.class),
846 "missing NetworkPolicyManagerInternal");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000847 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900848
Luke Huang674660f2018-09-27 19:33:11 +0800849 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700850 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700851 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700852
junyulai05986c62018-08-07 19:50:45 +0800853 // To ensure uid rules are synchronized with Network Policy, register for
854 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
855 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700856 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900857 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700858 } catch (RemoteException e) {
859 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700860 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700861 }
862
863 final PowerManager powerManager = (PowerManager) context.getSystemService(
864 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700865 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
866 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
867 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800868 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700869
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700870 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700871
Wink Saville51f456f2013-04-23 14:26:51 -0700872 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900873 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700874 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700875 String[] naStrings = context.getResources().getStringArray(
876 com.android.internal.R.array.networkAttributes);
877 for (String naString : naStrings) {
878 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700879 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700880 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700881 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800882 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700883 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700884 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700885 }
Wink Saville51f456f2013-04-23 14:26:51 -0700886 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
887 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
888 n.type);
889 continue;
890 }
Wink Saville975c8482011-04-07 14:23:45 -0700891 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800892 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700893 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700894 continue;
895 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700896 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700897
Wink Saville975c8482011-04-07 14:23:45 -0700898 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700899 mNetworksDefined++;
900 } catch(Exception e) {
901 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700902 }
903 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700904
905 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
906 if (mNetConfigs[TYPE_VPN] == null) {
907 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
908 // don't need to add TYPE_VPN to mNetConfigs.
909 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
910 mNetworksDefined++; // used only in the log() statement below.
911 }
912
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900913 // Do the same for Ethernet, since it's often not specified in the configs, although many
914 // devices can use it via USB host adapters.
915 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
916 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
917 mNetworksDefined++;
918 }
919
Wink Saville5e56bc52013-07-29 15:00:57 -0700920 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700921
Robert Greenwalt50393202011-06-21 17:26:14 -0700922 mProtectedNetworks = new ArrayList<Integer>();
923 int[] protectedNetworks = context.getResources().getIntArray(
924 com.android.internal.R.array.config_protectedNetworks);
925 for (int p : protectedNetworks) {
926 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
927 mProtectedNetworks.add(p);
928 } else {
929 if (DBG) loge("Ignoring protectedNetwork " + p);
930 }
931 }
932
Erik Kline47222fc2017-04-30 19:36:15 +0900933 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800934
Luke Huang4e25ec62018-09-27 16:58:23 +0800935 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700936
Varun Anand4fa80e82019-02-06 10:13:38 -0800937 // Set up the listener for user state for creating user VPNs.
938 // Should run on mHandler to avoid any races.
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700939 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100940 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700941 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700942 intentFilter.addAction(Intent.ACTION_USER_ADDED);
943 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000944 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700945 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800946 mIntentReceiver,
947 UserHandle.ALL,
948 intentFilter,
949 null /* broadcastPermission */,
950 mHandler);
Robin Lee95204e02017-01-27 11:59:22 +0000951 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
952 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900953
junyulai2454b692018-11-01 17:16:31 +0800954 // Listen to package add and removal events for all users.
955 intentFilter = new IntentFilter();
956 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800957 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800958 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
959 intentFilter.addDataScheme("package");
960 mContext.registerReceiverAsUser(
Varun Anand4fa80e82019-02-06 10:13:38 -0800961 mIntentReceiver,
962 UserHandle.ALL,
963 intentFilter,
964 null /* broadcastPermission */,
965 mHandler);
junyulai2454b692018-11-01 17:16:31 +0800966
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700967 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800968 mNMS.registerObserver(mTethering);
969 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700970 } catch (RemoteException e) {
971 loge("Error registering observer :" + e);
972 }
973
Erik Klineda4bfa82015-04-30 12:58:40 +0900974 mSettingsObserver = new SettingsObserver(mContext, mHandler);
975 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800976
Chalard Jean4133a122018-06-04 13:33:12 +0900977 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
978 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400979
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400980 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900981
982 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900983 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
984 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900985
986 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
987 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
988 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
989 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
990 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
991 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
992 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900993
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900994 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900995 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900996 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900997
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900998 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
999
Luke Huang4e25ec62018-09-27 16:58:23 +08001000 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +09001001 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001003
Mike Yuf9729752018-08-17 15:22:05 +08001004 @VisibleForTesting
1005 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +09001006 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +09001007 final TetheringDependencies deps = new TetheringDependencies() {
1008 @Override
1009 public boolean isTetheringSupported() {
1010 return ConnectivityService.this.isTetheringSupported();
1011 }
Erik Kline72302902018-06-14 17:36:40 +09001012 @Override
1013 public NetworkRequest getDefaultNetworkRequest() {
1014 return mDefaultRequest;
1015 }
Erik Kline465ff3a2018-03-09 14:18:02 +09001016 };
Luke Huang4e25ec62018-09-27 16:58:23 +08001017 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +09001018 IoThread.get().getLooper(), new MockableSystemProperties(),
1019 deps);
1020 }
1021
Irina Dumitrescu044a4362018-12-05 16:19:47 +00001022 @VisibleForTesting
1023 protected ProxyTracker makeProxyTracker() {
1024 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
1025 }
1026
Chalard Jean26400492018-04-18 20:18:38 +09001027 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1028 final NetworkCapabilities netCap = new NetworkCapabilities();
1029 netCap.addCapability(NET_CAPABILITY_INTERNET);
1030 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1031 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1032 netCap.setSingleUid(uid);
1033 return netCap;
1034 }
1035
Chalard Jeandda156a2018-01-10 21:19:32 +09001036 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001037 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001038 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001039 netCap.addCapability(NET_CAPABILITY_INTERNET);
1040 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001041 if (transportType > -1) {
1042 netCap.addTransportType(transportType);
1043 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001044 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001045 }
1046
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001047 // Used only for testing.
1048 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001049 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001050 // changing ContentResolver to make registerContentObserver non-final).
1051 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1052 // by subclassing SettingsObserver.
1053 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001054 void updateAlwaysOnNetworks() {
1055 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001056 }
1057
Erik Kline736353a2018-03-21 07:18:33 -07001058 // See FakeSettingsProvider comment above.
1059 @VisibleForTesting
1060 void updatePrivateDnsSettings() {
1061 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1062 }
1063
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001064 private void handleAlwaysOnNetworkRequest(
1065 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001066 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001067 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1068 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001069 if (enable == isEnabled) {
1070 return; // Nothing to do.
1071 }
1072
1073 if (enable) {
1074 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001075 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001076 } else {
Etan Cohenddb720a2019-01-08 12:09:18 -08001077 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1078 /* callOnUnavailable */ false);
Erik Klineda4bfa82015-04-30 12:58:40 +09001079 }
1080 }
1081
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001082 private void handleConfigureAlwaysOnNetworks() {
1083 handleAlwaysOnNetworkRequest(
1084 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1085 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1086 false);
1087 }
1088
Erik Klineda4bfa82015-04-30 12:58:40 +09001089 private void registerSettingsCallbacks() {
1090 // Watch for global HTTP proxy changes.
1091 mSettingsObserver.observe(
1092 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1093 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1094
1095 // Watch for whether or not to keep mobile data always on.
1096 mSettingsObserver.observe(
1097 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001098 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1099
1100 // Watch for whether or not to keep wifi always on.
1101 mSettingsObserver.observe(
1102 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1103 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001104 }
1105
Erik Klinea24d4592018-01-11 21:07:29 +09001106 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001107 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1108 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001109 }
1110 }
1111
Robert Greenwalt34524f02014-05-18 16:22:10 -07001112 private synchronized int nextNetworkRequestId() {
1113 return mNextNetworkRequestId++;
1114 }
1115
Paul Jensen67b0b072015-06-10 11:22:17 -04001116 @VisibleForTesting
1117 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001118 synchronized (mNetworkForNetId) {
1119 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1120 int netId = mNextNetId;
1121 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1122 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001123 if (!mNetIdInUse.get(netId)) {
1124 mNetIdInUse.put(netId, true);
1125 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001126 }
1127 }
1128 }
1129 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001130 }
1131
Chalard Jeanc0982912018-06-07 16:11:34 +09001132 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001133 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1135 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001136 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001137 state = nai.getNetworkState();
1138 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 final NetworkInfo info = new NetworkInfo(networkType, 0,
1141 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001142 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1143 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001144 final NetworkCapabilities capabilities = new NetworkCapabilities();
1145 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1146 !info.isRoaming());
1147 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001148 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001150 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001151 return state;
1152 } else {
1153 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001155 }
1156
junyulai4a192e22018-06-13 15:00:37 +08001157 @VisibleForTesting
1158 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 if (network == null) {
1160 return null;
1161 }
Erik Kline736353a2018-03-21 07:18:33 -07001162 return getNetworkAgentInfoForNetId(network.netId);
1163 }
1164
1165 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001167 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001169 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001171 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001172 synchronized (mVpns) {
1173 if (!mLockdownEnabled) {
1174 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001175 Vpn vpn = mVpns.get(user);
1176 if (vpn != null && vpn.appliesToUid(uid)) {
1177 return vpn.getUnderlyingNetworks();
1178 }
1179 }
1180 }
1181 return null;
1182 }
1183
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001184 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001185 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001186
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001187 final Network[] networks = getVpnUnderlyingNetworks(uid);
1188 if (networks != null) {
1189 // getUnderlyingNetworks() returns:
1190 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1191 // empty array => the VPN explicitly said "no default network".
1192 // non-empty array => the VPN specified one or more default networks; we use the
1193 // first one.
1194 if (networks.length > 0) {
1195 nai = getNetworkAgentInfoForNetwork(networks[0]);
1196 } else {
1197 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001198 }
1199 }
1200
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001202 return nai.getNetworkState();
1203 } else {
1204 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001206 }
1207
1208 /**
1209 * Check if UID should be blocked from using the network with the given LinkProperties.
1210 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001211 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1212 boolean ignoreBlocked) {
1213 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001214 if (ignoreBlocked) {
1215 return false;
1216 }
Robin Lee17e61832016-05-09 13:46:28 +01001217 synchronized (mVpns) {
1218 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001219 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001220 return true;
1221 }
1222 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001223 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001224 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001225 }
1226
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001227 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001228 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1229 return;
1230 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001231 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001232 synchronized (mBlockedAppUids) {
1233 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001234 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001235 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001236 blocked = false;
1237 } else {
1238 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001239 }
1240 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001241 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1242 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1243 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001244 }
1245
junyulai05986c62018-08-07 19:50:45 +08001246 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1247 boolean blocked) {
1248 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1249 return;
1250 }
1251 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1252 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1253 nri.mUid, nri.request.requestId, net.netId));
1254 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1255 }
1256
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001257 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001258 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1259 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001260 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001261 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001262 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001263 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1264
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001265 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001266 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001267 }
Hugo Benichi69744342017-11-27 10:57:16 +09001268 synchronized (mVpns) {
1269 if (mLockdownTracker != null) {
1270 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1271 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001272 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001273 }
1274
1275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 * Return NetworkInfo for the active (i.e., connected) network interface.
1277 * It is assumed that at most one network is active at a time. If more
1278 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001279 * @return the info for the active network, or {@code null} if none is
1280 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001282 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001284 enforceAccessPermission();
1285 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001286 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001287 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001288 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1289 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291
Paul Jensen31a94f42015-02-13 14:18:39 -05001292 @Override
1293 public Network getActiveNetwork() {
1294 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001295 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001296 }
1297
1298 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001299 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001300 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001301 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001302 }
1303
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001304 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001305 final int user = UserHandle.getUserId(uid);
1306 int vpnNetId = NETID_UNSET;
1307 synchronized (mVpns) {
1308 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001309 // TODO : now that capabilities contain the UID, the appliesToUid test should
1310 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001311 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1312 }
1313 NetworkAgentInfo nai;
1314 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001315 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001316 if (nai != null) {
1317 final NetworkCapabilities requiredCaps =
1318 createDefaultNetworkCapabilitiesForUid(uid);
1319 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1320 return nai.network;
1321 }
1322 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001323 }
1324 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001325 if (nai != null
1326 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1327 nai = null;
1328 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001329 return nai != null ? nai.network : null;
1330 }
1331
Lorenzo Colitti18660282016-07-04 12:55:44 +09001332 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001333 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1334 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001335 final int uid = Binder.getCallingUid();
1336 NetworkState state = getUnfilteredActiveNetworkState(uid);
1337 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001338 }
1339
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001340 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001341 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001342 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001343 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001344 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001345 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001346 }
1347
1348 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 public NetworkInfo getNetworkInfo(int networkType) {
1350 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001351 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001352 if (getVpnUnderlyingNetworks(uid) != null) {
1353 // A VPN is active, so we may need to return one of its underlying networks. This
1354 // information is not available in LegacyTypeTracker, so we have to get it from
1355 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001356 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001357 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001358 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001359 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001360 }
1361 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001362 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001363 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001366 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001367 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001368 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001369 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001370 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001371 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001372 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001373 return state.networkInfo;
1374 } else {
1375 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001377 }
1378
1379 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 public NetworkInfo[] getAllNetworkInfo() {
1381 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001382 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001383 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1384 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001385 NetworkInfo info = getNetworkInfo(networkType);
1386 if (info != null) {
1387 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001390 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
1392
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001393 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001394 public Network getNetworkForType(int networkType) {
1395 enforceAccessPermission();
1396 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001397 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001398 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001399 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001400 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001401 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001402 }
1403
1404 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001405 public Network[] getAllNetworks() {
1406 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001407 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001408 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001409 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001410 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001411 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001412 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001413 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001414 }
1415
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001416 @Override
1417 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1418 // The basic principle is: if an app's traffic could possibly go over a
1419 // network, without the app doing anything multinetwork-specific,
1420 // (hence, by "default"), then include that network's capabilities in
1421 // the array.
1422 //
1423 // In the normal case, app traffic only goes over the system's default
1424 // network connection, so that's the only network returned.
1425 //
1426 // With a VPN in force, some app traffic may go into the VPN, and thus
1427 // over whatever underlying networks the VPN specifies, while other app
1428 // traffic may go over the system default network (e.g.: a split-tunnel
1429 // VPN, or an app disallowed by the VPN), so the set of networks
1430 // returned includes the VPN's underlying networks and the system
1431 // default.
1432 enforceAccessPermission();
1433
Chalard Jean4133a122018-06-04 13:33:12 +09001434 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001435
1436 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001437 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001438 if (nc != null) {
1439 result.put(nai.network, nc);
1440 }
1441
Hugo Benichi69744342017-11-27 10:57:16 +09001442 synchronized (mVpns) {
1443 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001444 Vpn vpn = mVpns.get(userId);
1445 if (vpn != null) {
1446 Network[] networks = vpn.getUnderlyingNetworks();
1447 if (networks != null) {
1448 for (Network network : networks) {
1449 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001450 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001451 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001452 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001453 }
1454 }
1455 }
1456 }
1457 }
1458 }
1459
1460 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1461 out = result.values().toArray(out);
1462 return out;
1463 }
1464
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001465 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001466 public boolean isNetworkSupported(int networkType) {
1467 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001468 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001469 }
1470
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001471 /**
1472 * Return LinkProperties for the active (i.e., connected) default
1473 * network interface. It is assumed that at most one default network
1474 * is active at a time. If more than one is active, it is indeterminate
1475 * which will be returned.
1476 * @return the ip properties for the active network, or {@code null} if
1477 * none is active
1478 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001479 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001480 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001481 enforceAccessPermission();
1482 final int uid = Binder.getCallingUid();
1483 NetworkState state = getUnfilteredActiveNetworkState(uid);
1484 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001485 }
1486
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001487 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001488 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001489 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001490 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1491 if (nai != null) {
1492 synchronized (nai) {
1493 return new LinkProperties(nai.linkProperties);
1494 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001495 }
1496 return null;
1497 }
1498
Robert Greenwalt12e67352014-05-13 21:41:06 -07001499 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001500 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001501 public LinkProperties getLinkProperties(Network network) {
1502 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001503 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1504 }
1505
1506 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1507 if (nai == null) {
1508 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001509 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001510 synchronized (nai) {
1511 return new LinkProperties(nai.linkProperties);
1512 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001513 }
1514
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001515 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001516 if (nai != null) {
1517 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001518 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001519 return networkCapabilitiesRestrictedForCallerPermissions(
1520 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001521 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001522 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001523 }
1524 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001525 return null;
1526 }
1527
1528 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001529 public NetworkCapabilities getNetworkCapabilities(Network network) {
1530 enforceAccessPermission();
1531 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1532 }
1533
Chalard Jeanb03a6222018-04-11 21:09:10 +09001534 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001535 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001536 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001537 if (!checkSettingsPermission(callerPid, callerUid)) {
1538 newNc.setUids(null);
1539 newNc.setSSID(null);
1540 }
Etan Cohen836ad572018-12-30 17:59:59 -08001541 if (newNc.getNetworkSpecifier() != null) {
1542 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1543 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001544 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001545 }
1546
Chalard Jeanb552c462018-02-21 18:43:54 +09001547 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1548 if (!checkSettingsPermission()) {
1549 nc.setSingleUid(Binder.getCallingUid());
1550 }
1551 }
1552
Chalard Jean26aa91a2018-03-20 19:13:57 +09001553 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1554 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1555 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1556 }
1557 }
1558
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001559 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001560 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001561 // Require internal since we're handing out IMSI details
1562 enforceConnectivityInternalPermission();
1563
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001564 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001565 for (Network network : getAllNetworks()) {
1566 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1567 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001568 // TODO (b/73321673) : NetworkState contains a copy of the
1569 // NetworkCapabilities, which may contain UIDs of apps to which the
1570 // network applies. Should the UIDs be cleared so as not to leak or
1571 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001572 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001573 }
1574 }
1575 return result.toArray(new NetworkState[result.size()]);
1576 }
1577
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001578 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001579 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001580 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001581 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1582 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1583 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001584 }
1585
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001586 @Override
1587 public boolean isActiveNetworkMetered() {
1588 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001589
Varun Anandc51b06d2019-02-25 17:22:02 -08001590 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001591 if (caps != null) {
1592 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1593 } else {
1594 // Always return the most conservative value
1595 return true;
1596 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001597 }
1598
Jeff Sharkey216c1812012-08-05 14:29:23 -07001599 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1600 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001601 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001602 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001603 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001604 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001605 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001606
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001607 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001608 * Ensures that the system cannot call a particular method.
1609 */
1610 private boolean disallowedBecauseSystemCaller() {
1611 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1612 // requestRouteToHost.
1613 if (isSystem(Binder.getCallingUid())) {
1614 log("This method exists only for app backwards compatibility"
1615 + " and must not be called by system services.");
1616 return true;
1617 }
1618 return false;
1619 }
1620
1621 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 * Ensure that a network route exists to deliver traffic to the specified
1623 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001624 * @param networkType the type of the network over which traffic to the
1625 * specified host is to be routed
1626 * @param hostAddress the IP address of the host to which the route is
1627 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 * @return {@code true} on success, {@code false} on failure
1629 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001630 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001631 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001632 if (disallowedBecauseSystemCaller()) {
1633 return false;
1634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001636 if (mProtectedNetworks.contains(networkType)) {
1637 enforceConnectivityInternalPermission();
1638 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001639
Chad Brubakerc0234532014-02-14 13:24:29 -08001640 InetAddress addr;
1641 try {
1642 addr = InetAddress.getByAddress(hostAddress);
1643 } catch (UnknownHostException e) {
1644 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1645 return false;
1646 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001649 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 return false;
1651 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001652
1653 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1654 if (nai == null) {
1655 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1656 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1657 } else {
1658 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1659 }
1660 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001661 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001662
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001663 DetailedState netState;
1664 synchronized (nai) {
1665 netState = nai.networkInfo.getDetailedState();
1666 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001667
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001668 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001669 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001670 log("requestRouteToHostAddress on down network "
1671 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001672 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001673 }
1674 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001676
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001677 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001678 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001679 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001680 LinkProperties lp;
1681 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001682 synchronized (nai) {
1683 lp = nai.linkProperties;
1684 netId = nai.network.netId;
1685 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001686 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001687 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1688 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001689 } finally {
1690 Binder.restoreCallingIdentity(token);
1691 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001692 }
1693
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001694 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001695 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001696 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001697 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001698 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001699 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001700 if (bestRoute.getGateway().equals(addr)) {
1701 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001702 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001703 } else {
1704 // if we will connect to this through another route, add a direct route
1705 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001706 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001707 }
1708 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001709 if (DBG) log("Adding legacy route " + bestRoute +
1710 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001711 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001712 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001713 } catch (Exception e) {
1714 // never crash - catch them all
1715 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001716 return false;
1717 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001718 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 }
1720
dalyk7301aa42018-03-05 12:42:22 -05001721 @VisibleForTesting
1722 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1723 @Override
1724 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1725 String hostname, boolean validated) {
1726 try {
1727 mHandler.sendMessage(mHandler.obtainMessage(
1728 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1729 new PrivateDnsValidationUpdate(netId,
1730 InetAddress.parseNumericAddress(ipAddress),
1731 hostname, validated)));
1732 } catch (IllegalArgumentException e) {
1733 loge("Error parsing ip address in validation event");
1734 }
1735 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001736
1737 @Override
1738 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1739 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1740 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1741 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1742 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1743 // event callback for certain nai. e.g. cellular. Register here to pass to
1744 // NetworkMonitor instead.
1745 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1746 // registerNetworkAgent to have NetworkMonitor created with system process as design
1747 // expectation. Also, NetdEventListenerService only allow one callback from each
1748 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1749 // NetworkMonitor registrants.
1750 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001751 try {
1752 nai.networkMonitor().notifyDnsResponse(returnCode);
1753 } catch (RemoteException e) {
1754 e.rethrowFromSystemServer();
1755 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001756 }
1757 }
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09001758
1759 @Override
1760 public void onNat64PrefixEvent(int netId, boolean added,
1761 String prefixString, int prefixLength) {
1762 mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
1763 }
dalyk7301aa42018-03-05 12:42:22 -05001764 };
1765
1766 @VisibleForTesting
1767 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001768 final IIpConnectivityMetrics ipConnectivityMetrics =
1769 IIpConnectivityMetrics.Stub.asInterface(
1770 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1771 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001772 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001773 return;
dalyk7301aa42018-03-05 12:42:22 -05001774 }
1775
1776 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001777 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001778 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1779 mNetdEventCallback);
1780 } catch (Exception e) {
1781 loge("Error registering netd callback: " + e);
1782 }
1783 }
1784
Jeff Sharkey75d31892018-01-18 22:01:59 +09001785 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001786 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001787 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001788 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001789 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001790 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001791 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001792 // caller is NPMS, since we only register with them
1793 if (LOGD_BLOCKED_NETWORKINFO) {
1794 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1795 }
1796 mHandler.sendMessage(mHandler.obtainMessage(
1797 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1798
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001799 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001800 if (restrictBackground) {
1801 log("onRestrictBackgroundChanged(true): disabling tethering");
1802 mTethering.untetherAll();
1803 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001804 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001805 };
1806
junyulai05986c62018-08-07 19:50:45 +08001807 void handleUidRulesChanged(int uid, int newRules) {
1808 // skip update when we've already applied rules
1809 final int oldRules = mUidRules.get(uid, RULE_NONE);
1810 if (oldRules == newRules) return;
1811
1812 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1813
1814 if (newRules == RULE_NONE) {
1815 mUidRules.delete(uid);
1816 } else {
1817 mUidRules.put(uid, newRules);
1818 }
1819 }
1820
1821 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1822 if (mRestrictBackground == restrictBackground) return;
1823
1824 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1825 final boolean curMetered = nai.networkCapabilities.isMetered();
1826 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1827 restrictBackground);
1828 }
1829
1830 mRestrictBackground = restrictBackground;
1831 }
1832
1833 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1834 boolean isBackgroundRestricted) {
1835 synchronized (mVpns) {
1836 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1837 // Because the return value of this function depends on the list of UIDs the
1838 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1839 // list all state depending on the return value of this function has to be recomputed.
1840 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1841 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001842 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001843 return true;
1844 }
1845 }
1846
1847 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1848 isNetworkMetered, isBackgroundRestricted);
1849 }
1850
Robin Lee3b3dd942015-05-12 18:14:58 +01001851 /**
1852 * Require that the caller is either in the same user or has appropriate permission to interact
1853 * across users.
1854 *
1855 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1856 */
1857 private void enforceCrossUserPermission(int userId) {
1858 if (userId == UserHandle.getCallingUserId()) {
1859 // Not a cross-user call.
1860 return;
1861 }
1862 mContext.enforceCallingOrSelfPermission(
1863 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1864 "ConnectivityService");
1865 }
1866
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001867 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001868 for (String permission : permissions) {
1869 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001870 return true;
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001871 }
1872 }
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001873 return false;
1874 }
1875
1876 private void enforceAnyPermissionOf(String... permissions) {
1877 if (!checkAnyPermissionOf(permissions)) {
1878 throw new SecurityException("Requires one of the following permissions: "
1879 + String.join(", ", permissions) + ".");
1880 }
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001881 }
1882
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001883 private void enforceInternetPermission() {
1884 mContext.enforceCallingOrSelfPermission(
1885 android.Manifest.permission.INTERNET,
1886 "ConnectivityService");
1887 }
1888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001890 mContext.enforceCallingOrSelfPermission(
1891 android.Manifest.permission.ACCESS_NETWORK_STATE,
1892 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894
1895 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001896 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 }
1898
Charles He36738632017-05-15 17:07:18 +01001899 private void enforceSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001900 enforceAnyPermissionOf(
Charles He36738632017-05-15 17:07:18 +01001901 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001902 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He36738632017-05-15 17:07:18 +01001903 }
1904
Chalard Jeanb552c462018-02-21 18:43:54 +09001905 private boolean checkSettingsPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001906 return checkAnyPermissionOf(
1907 android.Manifest.permission.NETWORK_SETTINGS,
1908 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jeanb552c462018-02-21 18:43:54 +09001909 }
1910
1911 private boolean checkSettingsPermission(int pid, int uid) {
1912 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001913 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
1914 || PERMISSION_GRANTED == mContext.checkPermission(
1915 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jeanb552c462018-02-21 18:43:54 +09001916 }
1917
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001918 private void enforceTetherAccessPermission() {
1919 mContext.enforceCallingOrSelfPermission(
1920 android.Manifest.permission.ACCESS_NETWORK_STATE,
1921 "ConnectivityService");
1922 }
1923
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001924 private void enforceConnectivityInternalPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001925 enforceAnyPermissionOf(
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001926 android.Manifest.permission.CONNECTIVITY_INTERNAL,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001927 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001928 }
1929
Pavel Grafova462bcb2019-01-25 08:50:06 +00001930 private void enforceControlAlwaysOnVpnPermission() {
1931 mContext.enforceCallingOrSelfPermission(
1932 android.Manifest.permission.CONTROL_ALWAYS_ON_VPN,
1933 "ConnectivityService");
1934 }
1935
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001936 private void enforceNetworkStackSettingsOrSetup() {
1937 enforceAnyPermissionOf(
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001938 android.Manifest.permission.NETWORK_SETTINGS,
1939 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafova462bcb2019-01-25 08:50:06 +00001940 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001941 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafova462bcb2019-01-25 08:50:06 +00001942 }
1943
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001944 private boolean checkNetworkStackPermission() {
Remi NGUYEN VANdd29f202019-01-31 16:42:12 +09001945 return checkAnyPermissionOf(
1946 android.Manifest.permission.NETWORK_STACK,
1947 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001948 }
1949
Hugo Benichi514da602016-07-19 15:59:27 +09001950 private void enforceConnectivityRestrictedNetworksPermission() {
1951 try {
1952 mContext.enforceCallingOrSelfPermission(
1953 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1954 "ConnectivityService");
1955 return;
1956 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1957 enforceConnectivityInternalPermission();
1958 }
1959
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001960 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001961 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001962 }
1963
Lorenzo Colitti18660282016-07-04 12:55:44 +09001964 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001965 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001966 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001967 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001968 }
1969
1970 private void sendInetConditionBroadcast(NetworkInfo info) {
1971 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1972 }
1973
Wink Saville628b0852011-08-04 15:01:58 -07001974 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001975 synchronized (mVpns) {
1976 if (mLockdownTracker != null) {
1977 info = new NetworkInfo(info);
1978 mLockdownTracker.augmentNetworkInfo(info);
1979 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001980 }
1981
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001982 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001983 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001984 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 if (info.isFailover()) {
1986 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1987 info.setFailover(false);
1988 }
1989 if (info.getReason() != null) {
1990 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1991 }
1992 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001993 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1994 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001996 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001997 return intent;
1998 }
1999
2000 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2001 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2002 }
2003
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002004 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07002005 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2006 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2007 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07002008 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002009 final long ident = Binder.clearCallingIdentity();
2010 try {
2011 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2012 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2013 } finally {
2014 Binder.restoreCallingIdentity(ident);
2015 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07002016 }
2017
Mike Lockwood0f79b542009-08-14 14:18:49 -04002018 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09002019 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09002020 if (!mSystemReady
2021 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002022 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04002023 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002024 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002025 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07002026 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07002027 }
2028
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002029 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002030 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002031 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002032 final NetworkInfo ni = intent.getParcelableExtra(
2033 ConnectivityManager.EXTRA_NETWORK_INFO);
2034 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
2035 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
2036 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002037 } else {
2038 BroadcastOptions opts = BroadcastOptions.makeBasic();
2039 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2040 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07002041 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002042 final IBatteryStats bs = BatteryStatsService.getService();
2043 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002044 bs.noteConnectivityChanged(intent.getIntExtra(
2045 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09002046 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002047 } catch (RemoteException e) {
2048 }
Chad Brubakerac925012018-03-08 10:37:09 -08002049 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08002050 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002051 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002052 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002053 } finally {
2054 Binder.restoreCallingIdentity(ident);
2055 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002056 }
2057 }
2058
2059 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002060 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002061 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002062 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002063
Hugo Benichi20035e02017-04-26 14:53:28 +09002064 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002065 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002066 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002067 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002068 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002069 }
2070 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002071
Robin Lee244ce8e2016-01-05 18:03:46 +00002072 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2073 // for user to unlock device too.
2074 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002075
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002076 // Create network requests for always-on networks.
2077 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002078
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002079 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002080
2081 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 }
2083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002085 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002086 *
2087 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002088 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002089 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002090 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2091 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002092
2093 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002094 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002095
Robert Greenwalt7b816022014-04-18 15:25:25 -07002096 if (networkAgent.networkCapabilities.hasTransport(
2097 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002098 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2099 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002100 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002101 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002102 } else if (networkAgent.networkCapabilities.hasTransport(
2103 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002104 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2105 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002106 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002107 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002108 } else {
2109 // do not track any other networks
2110 timeout = 0;
2111 }
2112
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002114 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002115 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002116 } catch (Exception e) {
2117 // You shall not crash!
2118 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002119 }
2120 }
2121 }
2122
2123 /**
2124 * Remove data activity tracking when network disconnects.
2125 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002126 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2127 final String iface = networkAgent.linkProperties.getInterfaceName();
2128 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002129
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2131 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002132 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002133 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002134 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002135 } catch (Exception e) {
2136 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002137 }
2138 }
2139 }
2140
2141 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002142 * Update data activity tracking when network state is updated.
2143 */
2144 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2145 NetworkAgentInfo oldNetwork) {
2146 if (newNetwork != null) {
2147 setupDataActivityTracking(newNetwork);
2148 }
2149 if (oldNetwork != null) {
2150 removeDataActivityTracking(oldNetwork);
2151 }
2152 }
2153 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002154 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002155 * and set it on it's iface.
2156 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002157 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2158 final String iface = newLp.getInterfaceName();
2159 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002160 if (oldLp == null && mtu == 0) {
2161 // Silently ignore unset MTU value.
2162 return;
2163 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002164 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2165 if (VDBG) log("identical MTU - not setting");
2166 return;
2167 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002168 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002169 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002170 return;
2171 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002172
w1997615afd812014-08-05 15:18:11 -07002173 // Cannot set MTU without interface name
2174 if (TextUtils.isEmpty(iface)) {
2175 loge("Setting MTU size with null iface.");
2176 return;
2177 }
2178
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002180 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002181 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002182 } catch (Exception e) {
2183 Slog.e(TAG, "exception in setMtu()" + e);
2184 }
2185 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002186
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002187 @VisibleForTesting
2188 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002189 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2190
2191 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002192 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002193 protected MockableSystemProperties getSystemProperties() {
2194 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002195 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002196
lucaslin041a1af2018-11-28 19:27:52 +08002197 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002198 String[] values = null;
2199 if (tcpBufferSizes != null) {
2200 values = tcpBufferSizes.split(",");
2201 }
2202
2203 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002204 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002205 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2206 values = tcpBufferSizes.split(",");
2207 }
2208
2209 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2210
2211 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002212 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002213
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002214 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2215 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2216 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002217 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002218 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002219 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002220 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002221
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002222 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002223 Settings.Global.TCP_DEFAULT_INIT_RWND,
2224 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002225 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2226 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002227 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002228 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002229 }
2230
Robert Greenwalt562cc542014-05-15 18:07:26 -07002231 @Override
2232 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002233 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002234 NETWORK_RESTORE_DELAY_PROP_NAME);
2235 if(restoreDefaultNetworkDelayStr != null &&
2236 restoreDefaultNetworkDelayStr.length() != 0) {
2237 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002238 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002239 } catch (NumberFormatException e) {
2240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002242 // if the system property isn't set, use the value for the apn type
2243 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2244
2245 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2246 (mNetConfigs[networkType] != null)) {
2247 ret = mNetConfigs[networkType].restoreTime;
2248 }
2249 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002252 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2253 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2254 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002255 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002256 // Start gathering diagnostic information.
2257 netDiags.add(new NetworkDiagnostics(
2258 nai.network,
2259 new LinkProperties(nai.linkProperties), // Must be a copy.
2260 DIAG_TIME_MS));
2261 }
2262
2263 for (NetworkDiagnostics netDiag : netDiags) {
2264 pw.println();
2265 netDiag.waitForMeasurements();
2266 netDiag.dump(pw);
2267 }
2268 }
2269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002271 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002272 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2273 }
2274
2275 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002276 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002277 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002278 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002279
Erik Kline3f8306b2018-05-01 16:51:44 +09002280 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002281 dumpNetworkDiagnostics(pw);
2282 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002283 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002284 mTethering.dump(fd, pw, args);
2285 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002286 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2287 dumpNetworks(pw);
2288 return;
2289 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2290 dumpNetworkRequests(pw);
2291 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002292 }
Erik Kline379747a2015-06-05 17:47:34 +09002293
Lorenzo Colittie3805462015-06-03 11:18:24 +09002294 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002295 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002296 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002297 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002298 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002299 pw.println();
2300
Paul Jensen85cf78e2015-06-25 13:25:07 -04002301 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002302 pw.print("Active default network: ");
2303 if (defaultNai == null) {
2304 pw.println("none");
2305 } else {
2306 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002308 pw.println();
2309
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002310 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002311 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002312 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002313 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002314 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002315
junyulai05986c62018-08-07 19:50:45 +08002316 pw.print("Restrict background: ");
2317 pw.println(mRestrictBackground);
2318 pw.println();
2319
2320 pw.println("Status for known UIDs:");
2321 pw.increaseIndent();
2322 final int size = mUidRules.size();
2323 for (int i = 0; i < size; i++) {
2324 // Don't crash if the array is modified while dumping in bugreports.
2325 try {
2326 final int uid = mUidRules.keyAt(i);
2327 final int uidRules = mUidRules.get(uid, RULE_NONE);
2328 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2329 } catch (ArrayIndexOutOfBoundsException e) {
2330 pw.println(" ArrayIndexOutOfBoundsException");
2331 } catch (ConcurrentModificationException e) {
2332 pw.println(" ConcurrentModificationException");
2333 }
2334 }
2335 pw.println();
2336 pw.decreaseIndent();
2337
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002338 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002339 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002340 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002341 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002342 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002343
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002344 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002345
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002346 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002347 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002348
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002349 pw.println();
2350 mKeepaliveTracker.dump(pw);
2351
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002352 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002353 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002354
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002355 pw.println();
2356 mMultipathPolicyTracker.dump(pw);
2357
Erik Kline3f8306b2018-05-01 16:51:44 +09002358 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002359 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002360 pw.println("mNetworkRequestInfoLogs (most recent first):");
2361 pw.increaseIndent();
2362 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2363 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002364
2365 pw.println();
2366 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2367 pw.increaseIndent();
2368 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2369 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002370
2371 pw.println();
2372 pw.println("NetTransition WakeLock activity (most recent first):");
2373 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002374 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2375 pw.println("total releases: " + mTotalWakelockReleases);
2376 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2377 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2378 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2379 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2380 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2381 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002382 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002383
2384 pw.println();
2385 pw.println("bandwidth update requests (by uid):");
2386 pw.increaseIndent();
2387 synchronized (mBandwidthRequests) {
2388 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2389 pw.println("[" + mBandwidthRequests.keyAt(i)
2390 + "]: " + mBandwidthRequests.valueAt(i));
2391 }
2392 }
2393 pw.decreaseIndent();
2394
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002395 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002396 }
Remi NGUYEN VANa25379f2019-02-18 11:20:28 +09002397
2398 pw.println();
2399 pw.println("NetworkStackClient logs:");
2400 pw.increaseIndent();
2401 NetworkStackClient.getInstance().dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 }
2403
Hugo Benichi14683812018-09-03 08:32:56 +09002404 private void dumpNetworks(IndentingPrintWriter pw) {
2405 for (NetworkAgentInfo nai : networksSortedById()) {
2406 pw.println(nai.toString());
2407 pw.increaseIndent();
2408 pw.println(String.format(
2409 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2410 nai.numForegroundNetworkRequests(),
2411 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2412 nai.numBackgroundNetworkRequests(),
2413 nai.numNetworkRequests()));
2414 pw.increaseIndent();
2415 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2416 pw.println(nai.requestAt(i).toString());
2417 }
2418 pw.decreaseIndent();
2419 pw.println("Lingered:");
2420 pw.increaseIndent();
2421 nai.dumpLingerTimers(pw);
2422 pw.decreaseIndent();
2423 pw.decreaseIndent();
2424 }
2425 }
2426
2427 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2428 for (NetworkRequestInfo nri : requestsSortedById()) {
2429 pw.println(nri.toString());
2430 }
2431 }
2432
Hugo Benichia2a917c2018-09-03 08:19:02 +09002433 /**
2434 * Return an array of all current NetworkAgentInfos sorted by network id.
2435 */
2436 private NetworkAgentInfo[] networksSortedById() {
2437 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2438 networks = mNetworkAgentInfos.values().toArray(networks);
2439 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2440 return networks;
2441 }
2442
2443 /**
2444 * Return an array of all current NetworkRequest sorted by request id.
2445 */
2446 private NetworkRequestInfo[] requestsSortedById() {
2447 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2448 requests = mNetworkRequests.values().toArray(requests);
2449 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2450 return requests;
2451 }
2452
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002453 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002454 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002455 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002456 if (officialNai != null && officialNai.equals(nai)) return true;
2457 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002458 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002459 " - " + nai);
2460 }
2461 return false;
2462 }
2463
Robert Greenwalt42acef32009-08-12 16:08:25 -07002464 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002465 private class NetworkStateTrackerHandler extends Handler {
2466 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002467 super(looper);
2468 }
2469
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002470 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002472 default:
2473 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002474 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002475 handleAsyncChannelHalfConnect(msg);
2476 break;
2477 }
2478 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2479 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2480 if (nai != null) nai.asyncChannel.disconnect();
2481 break;
2482 }
2483 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2484 handleAsyncChannelDisconnected(msg);
2485 break;
2486 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002487 }
2488 return true;
2489 }
2490
2491 private void maybeHandleNetworkAgentMessage(Message msg) {
2492 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2493 if (nai == null) {
2494 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002495 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002496 }
2497 return;
2498 }
2499
2500 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002501 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002502 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
lucasline252a742019-03-12 13:08:03 +08002503 if (networkCapabilities.hasConnectivityManagedCapability()) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002504 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002505 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002506 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002507 break;
2508 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002509 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002510 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002511 break;
2512 }
2513 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002514 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002515 updateNetworkInfo(nai, info);
2516 break;
2517 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002518 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002519 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002520 break;
2521 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002522 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002523 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2524 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002525 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002526 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002527 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
lucasline252a742019-03-12 13:08:03 +08002528 // Mark the network as temporarily accepting partial connectivity so that it
2529 // will be validated (and possibly become default) even if it only provides
2530 // partial internet access. Note that if user connects to partial connectivity
2531 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
2532 // out of wifi coverage) and if the same wifi is available again, the device
2533 // will auto connect to this wifi even though the wifi has "no internet".
2534 // TODO: Evaluate using a separate setting in IpMemoryStore.
2535 nai.networkMisc.acceptPartialConnectivity = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002536 break;
2537 }
junyulai06835112019-01-03 18:50:15 +08002538 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
2539 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002540 break;
2541 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002542 }
2543 }
2544
2545 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2546 switch (msg.what) {
2547 default:
2548 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002549 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002550 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002551 if (nai == null) break;
2552
lucasline252a742019-03-12 13:08:03 +08002553 final boolean partialConnectivity =
2554 (msg.arg1 == NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY)
lucasline252a742019-03-12 13:08:03 +08002555 || (nai.networkMisc.acceptPartialConnectivity
2556 && nai.partialConnectivity);
2557 // Once a network is determined to have partial connectivity, it cannot
2558 // go back to full connectivity without a disconnect.
lucaslin43338992019-03-20 18:21:59 +08002559 final boolean partialConnectivityChanged =
lucasline252a742019-03-12 13:08:03 +08002560 (partialConnectivity && !nai.partialConnectivity);
2561
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002562 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002563 final boolean wasValidated = nai.lastValidated;
2564 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002565 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2566 && valid) {
2567 nai.captivePortalLoginNotified = true;
2568 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2569 }
Erik Klinea24d4592018-01-11 21:07:29 +09002570
Erik Klinea24d4592018-01-11 21:07:29 +09002571 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2572
Erik Klinea24d4592018-01-11 21:07:29 +09002573 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002574 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2575 ? " with redirect to " + redirectUrl
2576 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002577 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2578 }
Erik Klinea24d4592018-01-11 21:07:29 +09002579 if (valid != nai.lastValidated) {
2580 if (wasDefault) {
2581 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2582 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002583 }
Erik Klinea24d4592018-01-11 21:07:29 +09002584 final int oldScore = nai.getCurrentScore();
2585 nai.lastValidated = valid;
2586 nai.everValidated |= valid;
2587 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2588 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2589 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002590 if (valid) {
2591 handleFreshlyValidatedNetwork(nai);
2592 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2593 // valid.
2594 mNotifier.clearNotification(nai.network.netId,
2595 NotificationType.NO_INTERNET);
2596 mNotifier.clearNotification(nai.network.netId,
2597 NotificationType.LOST_INTERNET);
2598 }
lucaslin43338992019-03-20 18:21:59 +08002599 } else if (partialConnectivityChanged) {
lucasline252a742019-03-12 13:08:03 +08002600 nai.partialConnectivity = partialConnectivity;
2601 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Erik Klinea24d4592018-01-11 21:07:29 +09002602 }
2603 updateInetCondition(nai);
2604 // Let the NetworkAgent know the state of its network
2605 Bundle redirectUrlBundle = new Bundle();
2606 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2607 nai.asyncChannel.sendMessage(
2608 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2609 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2610 0, redirectUrlBundle);
2611 if (wasValidated && !nai.lastValidated) {
2612 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002613 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002614 break;
2615 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002616 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002617 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002618 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002619 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002620 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002621 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002622 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002623 nai.lastCaptivePortalDetected = visible;
2624 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002625 if (visible) {
2626 nai.captivePortalLoginNotified = false;
2627 }
Calvin Onbe96da12016-10-11 15:10:46 -07002628 if (nai.lastCaptivePortalDetected &&
2629 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2630 if (DBG) log("Avoiding captive portal network: " + nai.name());
2631 nai.asyncChannel.sendMessage(
2632 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2633 teardownUnneededNetwork(nai);
2634 break;
2635 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002636 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002637 }
2638 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002639 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucasline252a742019-03-12 13:08:03 +08002640 // notifications belong to the same network may be cleared unexpectedly.
lucaslind2e045e02019-01-24 15:55:30 +08002641 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2642 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002643 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002644 if (nai == null) {
2645 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2646 break;
2647 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002648 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002649 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002650 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002651 }
Paul Jensen869868be2014-05-15 10:33:05 -04002652 }
Paul Jensen869868be2014-05-15 10:33:05 -04002653 break;
2654 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002655 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002656 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002657 if (nai == null) break;
2658
Erik Kline736353a2018-03-21 07:18:33 -07002659 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002660 break;
2661 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002662 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002663 return true;
2664 }
2665
Calvin Onbe96da12016-10-11 15:10:46 -07002666 private int getCaptivePortalMode() {
2667 return Settings.Global.getInt(mContext.getContentResolver(),
2668 Settings.Global.CAPTIVE_PORTAL_MODE,
2669 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2670 }
2671
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002672 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2673 switch (msg.what) {
2674 default:
2675 return false;
2676 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2677 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2678 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2679 handleLingerComplete(nai);
2680 }
2681 break;
2682 }
2683 }
2684 return true;
2685 }
2686
Etan Cohenddb720a2019-01-08 12:09:18 -08002687 private boolean maybeHandleNetworkFactoryMessage(Message msg) {
2688 switch (msg.what) {
2689 default:
2690 return false;
2691 case android.net.NetworkFactory.EVENT_UNFULFILLABLE_REQUEST: {
2692 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.sendingUid,
2693 /* callOnUnavailable */ true);
2694 break;
2695 }
2696 }
2697 return true;
2698 }
2699
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002700 @Override
2701 public void handleMessage(Message msg) {
Etan Cohenddb720a2019-01-08 12:09:18 -08002702 if (!maybeHandleAsyncChannelMessage(msg)
2703 && !maybeHandleNetworkMonitorMessage(msg)
2704 && !maybeHandleNetworkAgentInfoMessage(msg)
2705 && !maybeHandleNetworkFactoryMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002706 maybeHandleNetworkAgentMessage(msg);
2707 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002708 }
2709 }
2710
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002711 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2712 private final NetworkAgentInfo mNai;
2713
2714 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2715 mNai = nai;
2716 }
2717
2718 @Override
2719 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2721 new Pair<>(mNai, networkMonitor)));
2722 }
2723
2724 @Override
2725 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2726 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2727 testResult, mNai.network.netId, redirectUrl));
2728 }
2729
2730 @Override
2731 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2732 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2733 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2734 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2735 }
2736
2737 @Override
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002738 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002739 final Intent intent = new Intent(action);
Remi NGUYEN VAN9c5d9642019-02-07 21:29:57 +09002740 intent.setPackage(packageName);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002741
2742 final PendingIntent pendingIntent;
2743 // Only the system server can register notifications with package "android"
2744 final long token = Binder.clearCallingIdentity();
2745 try {
2746 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2747 } finally {
2748 Binder.restoreCallingIdentity(token);
2749 }
2750 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2751 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2752 mNai.network.netId,
2753 pendingIntent));
2754 }
2755
2756 @Override
2757 public void hideProvisioningNotification() {
2758 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2759 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2760 mNai.network.netId));
2761 }
2762 }
2763
Erik Kline736353a2018-03-21 07:18:33 -07002764 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002765 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002766 }
2767
Erik Klinec6d00222018-06-26 18:53:43 +09002768 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2769 if (nai == null) return;
2770 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2771 // in order to restart a validation pass from within netd.
2772 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2773 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2774 updateDnses(nai.linkProperties, null, nai.network.netId);
2775 }
2776 }
2777
Erik Klinea24d4592018-01-11 21:07:29 +09002778 private void handlePrivateDnsSettingsChanged() {
2779 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2780
2781 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002782 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002783 if (networkRequiresValidation(nai)) {
2784 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2785 }
Erik Klinea24d4592018-01-11 21:07:29 +09002786 }
2787 }
2788
Erik Kline736353a2018-03-21 07:18:33 -07002789 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2790 // Private DNS only ever applies to networks that might provide
2791 // Internet access and therefore also require validation.
2792 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002793
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002794 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002795 // schedule DNS resolutions. If a DNS resolution is required the
2796 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002797 try {
2798 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2799 } catch (RemoteException e) {
2800 e.rethrowFromSystemServer();
2801 }
Erik Kline736353a2018-03-21 07:18:33 -07002802
2803 // With Private DNS bypass support, we can proceed to update the
2804 // Private DNS config immediately, even if we're in strict mode
2805 // and have not yet resolved the provider name into a set of IPs.
2806 updatePrivateDns(nai, cfg);
2807 }
2808
2809 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2810 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002811 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002812 }
2813
dalyk7301aa42018-03-05 12:42:22 -05002814 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2815 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2816 if (nai == null) {
2817 return;
2818 }
2819 mDnsManager.updatePrivateDnsValidation(update);
2820 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2821 }
2822
Lorenzo Colitti6998fa82019-01-08 10:04:25 +09002823 private void handleNat64PrefixEvent(int netId, boolean added, String prefixString,
2824 int prefixLength) {
2825 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
2826 if (nai == null) return;
2827
2828 log(String.format("NAT64 prefix %s on netId %d: %s/%d",
2829 (added ? "added" : "removed"), netId, prefixString, prefixLength));
2830
2831 IpPrefix prefix = null;
2832 if (added) {
2833 try {
2834 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixString),
2835 prefixLength);
2836 } catch (IllegalArgumentException e) {
2837 loge("Invalid NAT64 prefix " + prefixString + "/" + prefixLength);
2838 return;
2839 }
2840 }
2841
2842 nai.clatd.setNat64Prefix(prefix);
2843 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2844 }
2845
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002846 private void updateLingerState(NetworkAgentInfo nai, long now) {
2847 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2848 // 2. If the network was lingering and there are now requests, unlinger it.
2849 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2850 // one lingered request, start lingering.
2851 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002852 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002853 if (DBG) log("Unlingering " + nai.name());
2854 nai.unlinger();
2855 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002856 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002857 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002858 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002859 nai.linger();
2860 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2861 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2862 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002863 }
2864
Robert Greenwalt7b816022014-04-18 15:25:25 -07002865 private void handleAsyncChannelHalfConnect(Message msg) {
2866 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002867 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002868 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2869 if (VDBG) log("NetworkFactory connected");
Etan Cohenddb720a2019-01-08 12:09:18 -08002870 // Finish setting up the full connection
2871 mNetworkFactoryInfos.get(msg.replyTo).asyncChannel.sendMessage(
2872 AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002873 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002874 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002875 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002876 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09002877 final int score;
2878 final int serial;
2879 if (nai != null) {
2880 score = nai.getCurrentScore();
2881 serial = nai.factorySerialNumber;
2882 } else {
2883 score = 0;
2884 serial = NetworkFactory.SerialNumber.NONE;
2885 }
2886 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, serial,
2887 nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002888 }
2889 } else {
2890 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002891 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002892 }
2893 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2894 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2895 if (VDBG) log("NetworkAgent connected");
2896 // A network agent has requested a connection. Establish the connection.
2897 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2898 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2899 } else {
2900 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002901 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002902 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002903 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002904 synchronized (mNetworkForNetId) {
2905 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002906 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002907 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002908 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002909 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002910 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002911 }
2912 }
2913 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002914
Chalard Jean392971c2018-05-11 20:19:20 +09002915 // This is a no-op if it's called with a message designating a network that has
2916 // already been destroyed, because its reference will not be found in the relevant
2917 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002918 private void handleAsyncChannelDisconnected(Message msg) {
2919 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2920 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002921 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002922 } else {
2923 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2924 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002925 }
2926 }
2927
Chalard Jean392971c2018-05-11 20:19:20 +09002928 // Destroys a network, remove references to it from the internal state managed by
2929 // ConnectivityService, free its interfaces and clean up.
2930 // Must be called on the Handler thread.
2931 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2932 if (DBG) {
2933 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2934 }
lucaslinf80b83b2019-02-12 15:30:13 +08002935 // Clear all notifications of this network.
2936 mNotifier.clearNotification(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002937 // A network agent has disconnected.
2938 // TODO - if we move the logic to the network agent (have them disconnect
2939 // because they lost all their requests or because their score isn't good)
2940 // then they would disconnect organically, report their new state and then
2941 // disconnect the channel.
2942 if (nai.networkInfo.isConnected()) {
2943 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2944 null, null);
2945 }
2946 final boolean wasDefault = isDefaultNetwork(nai);
2947 if (wasDefault) {
2948 mDefaultInetConditionPublished = 0;
2949 // Log default network disconnection before required book-keeping.
2950 // Let rematchAllNetworksAndRequests() below record a new default network event
2951 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2952 // whose timestamps tell how long it takes to recover a default network.
2953 long now = SystemClock.elapsedRealtime();
2954 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2955 }
2956 notifyIfacesChangedForNetworkStats();
2957 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2958 // by other networks that are already connected. Perhaps that can be done by
2959 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2960 // of rematchAllNetworksAndRequests
2961 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai06835112019-01-03 18:50:15 +08002962 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Chalard Jean392971c2018-05-11 20:19:20 +09002963 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2964 // Disable wakeup packet monitoring for each interface.
2965 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2966 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002967 try {
2968 nai.networkMonitor().notifyNetworkDisconnected();
2969 } catch (RemoteException e) {
2970 e.rethrowFromSystemServer();
2971 }
Chalard Jean392971c2018-05-11 20:19:20 +09002972 mNetworkAgentInfos.remove(nai.messenger);
Lorenzo Colittid593e292019-02-19 13:21:56 +09002973 nai.clatd.update();
Chalard Jean392971c2018-05-11 20:19:20 +09002974 synchronized (mNetworkForNetId) {
2975 // Remove the NetworkAgent, but don't mark the netId as
2976 // available until we've told netd to delete it below.
2977 mNetworkForNetId.remove(nai.network.netId);
2978 }
2979 // Remove all previously satisfied requests.
2980 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2981 NetworkRequest request = nai.requestAt(i);
2982 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2983 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2984 clearNetworkForRequest(request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09002985 sendUpdatedScoreToFactories(request, null);
Chalard Jean392971c2018-05-11 20:19:20 +09002986 }
2987 }
2988 nai.clearLingerState();
2989 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002990 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002991 notifyLockdownVpn(nai);
2992 ensureNetworkTransitionWakelock(nai.name());
2993 }
2994 mLegacyTypeTracker.remove(nai, wasDefault);
2995 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2996 updateAllVpnsCapabilities();
2997 }
2998 rematchAllNetworksAndRequests(null, 0);
2999 mLingerMonitor.noteDisconnect(nai);
3000 if (nai.created) {
3001 // Tell netd to clean up the configuration for this network
3002 // (routing rules, DNS, etc).
3003 // This may be slow as it requires a lot of netd shelling out to ip and
3004 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3005 // after we've rematched networks with requests which should make a potential
3006 // fallback network the default or requested a new network from the
3007 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
3008 // long time.
3009 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08003010 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09003011 } catch (Exception e) {
3012 loge("Exception removing network: " + e);
3013 }
3014 mDnsManager.removeNetwork(nai.network);
3015 }
3016 synchronized (mNetworkForNetId) {
3017 mNetIdInUse.delete(nai.network.netId);
3018 }
3019 }
3020
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003021 // If this method proves to be too slow then we can maintain a separate
3022 // pendingIntent => NetworkRequestInfo map.
3023 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3024 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3025 Intent intent = pendingIntent.getIntent();
3026 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3027 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3028 if (existingPendingIntent != null &&
3029 existingPendingIntent.getIntent().filterEquals(intent)) {
3030 return entry.getValue();
3031 }
3032 }
3033 return null;
3034 }
3035
3036 private void handleRegisterNetworkRequestWithIntent(Message msg) {
3037 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3038
3039 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
3040 if (existingRequest != null) { // remove the existing request.
3041 if (DBG) log("Replacing " + existingRequest.request + " with "
3042 + nri.request + " because their intents matched.");
Etan Cohenddb720a2019-01-08 12:09:18 -08003043 handleReleaseNetworkRequest(existingRequest.request, getCallingUid(),
3044 /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003045 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003046 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003047 }
3048
Erik Klineda4bfa82015-04-30 12:58:40 +09003049 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003050 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09003051 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09003052 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003053 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003054 if (nri.request.networkCapabilities.hasSignalStrength() &&
3055 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
3056 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003057 }
3058 }
3059 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003060 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09003061 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Chalard Jean05ab6812018-05-02 21:14:54 +09003062 sendUpdatedScoreToFactories(nri.request, null);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003063 }
3064 }
3065
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003066 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
3067 int callingUid) {
3068 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3069 if (nri != null) {
Etan Cohenddb720a2019-01-08 12:09:18 -08003070 handleReleaseNetworkRequest(nri.request, callingUid, /* callOnUnavailable */ false);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003071 }
3072 }
3073
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003074 // Determines whether the network is the best (or could become the best, if it validated), for
3075 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3076 // on the value of reason:
3077 //
3078 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3079 // then it should be torn down.
3080 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3081 // then it should be lingered.
3082 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3083 final int numRequests;
3084 switch (reason) {
3085 case TEARDOWN:
3086 numRequests = nai.numRequestNetworkRequests();
3087 break;
3088 case LINGER:
3089 numRequests = nai.numForegroundNetworkRequests();
3090 break;
3091 default:
3092 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
3093 return true;
3094 }
3095
3096 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09003097 return false;
3098 }
Paul Jensene0988542015-06-25 15:30:08 -04003099 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003100 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
3101 // Background requests don't affect lingering.
3102 continue;
3103 }
3104
Paul Jensene0988542015-06-25 15:30:08 -04003105 // If this Network is already the highest scoring Network for a request, or if
3106 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003107 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09003108 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04003109 // Note that this catches two important cases:
3110 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
3111 // is currently satisfying the request. This is desirable when
3112 // cellular ends up validating but WiFi does not.
3113 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04003114 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04003115 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09003116 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04003117 nai.getCurrentScoreAsValidated())) {
3118 return false;
Paul Jensen99364842014-12-09 11:43:45 -05003119 }
3120 }
Paul Jensene0988542015-06-25 15:30:08 -04003121 return true;
Paul Jensen99364842014-12-09 11:43:45 -05003122 }
3123
Erik Klineacdd6392016-07-07 16:50:58 +09003124 private NetworkRequestInfo getNriForAppRequest(
3125 NetworkRequest request, int callingUid, String requestedOperation) {
3126 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3127
Robert Greenwalt9258c642014-03-26 16:47:06 -07003128 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003129 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003130 log(String.format("UID %d attempted to %s for unowned request %s",
3131 callingUid, requestedOperation, nri));
3132 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003133 }
Erik Klineacdd6392016-07-07 16:50:58 +09003134 }
3135
3136 return nri;
3137 }
3138
Erik Kline57faba92015-11-25 12:49:38 +09003139 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003140 if (mNetworkRequests.get(nri.request) == null) {
3141 return;
Erik Kline57faba92015-11-25 12:49:38 +09003142 }
Hugo Benichicd952782017-09-20 11:20:14 +09003143 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003144 return;
3145 }
3146 if (VDBG || (DBG && nri.request.isRequest())) {
3147 log("releasing " + nri.request + " (timeout)");
3148 }
3149 handleRemoveNetworkRequest(nri);
3150 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003151 }
3152
Etan Cohenddb720a2019-01-08 12:09:18 -08003153 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid,
3154 boolean callOnUnavailable) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003155 final NetworkRequestInfo nri =
3156 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3157 if (nri == null) {
3158 return;
Erik Kline57faba92015-11-25 12:49:38 +09003159 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003160 if (VDBG || (DBG && nri.request.isRequest())) {
3161 log("releasing " + nri.request + " (release request)");
3162 }
3163 handleRemoveNetworkRequest(nri);
Etan Cohenddb720a2019-01-08 12:09:18 -08003164 if (callOnUnavailable) {
3165 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
3166 }
Erik Kline57faba92015-11-25 12:49:38 +09003167 }
Erik Klineacdd6392016-07-07 16:50:58 +09003168
Hugo Benichidba33db2017-03-23 22:40:44 +09003169 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003170 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003171 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003172
Erik Klineacdd6392016-07-07 16:50:58 +09003173 synchronized (mUidToNetworkRequestCount) {
3174 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3175 if (requests < 1) {
3176 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3177 nri.mUid);
3178 } else if (requests == 1) {
3179 mUidToNetworkRequestCount.removeAt(
3180 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3181 } else {
3182 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3183 }
3184 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003185
Erik Klineacdd6392016-07-07 16:50:58 +09003186 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3187 if (nri.request.isRequest()) {
3188 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003189 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003190 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003191 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003192 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003193 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003194 log(" Removing from current network " + nai.name() +
3195 ", leaving " + nai.numNetworkRequests() + " requests.");
3196 }
3197 // If there are still lingered requests on this network, don't tear it down,
3198 // but resume lingering instead.
3199 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003200 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003201 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3202 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003203 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003204 wasKept = true;
3205 }
Hugo Benichicd952782017-09-20 11:20:14 +09003206 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003207 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3208 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003209 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003210 }
Erik Klineacdd6392016-07-07 16:50:58 +09003211 }
3212
Erik Klineacdd6392016-07-07 16:50:58 +09003213 // Maintain the illusion. When this request arrived, we might have pretended
3214 // that a network connected to serve it, even though the network was already
3215 // connected. Now that this request has gone away, we might have to pretend
3216 // that the network disconnected. LegacyTypeTracker will generate that
3217 // phantom disconnect for this type.
3218 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3219 boolean doRemove = true;
3220 if (wasKept) {
3221 // check if any of the remaining requests for this network are for the
3222 // same legacy type - if so, don't remove the nai
3223 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3224 NetworkRequest otherRequest = nai.requestAt(i);
3225 if (otherRequest.legacyType == nri.request.legacyType &&
3226 otherRequest.isRequest()) {
3227 if (DBG) log(" still have other legacy request - leaving");
3228 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003229 }
3230 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003231 }
3232
Erik Klineacdd6392016-07-07 16:50:58 +09003233 if (doRemove) {
3234 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003235 }
3236 }
Erik Klineacdd6392016-07-07 16:50:58 +09003237
3238 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3239 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3240 nri.request);
3241 }
3242 } else {
3243 // listens don't have a singular affectedNetwork. Check all networks to see
3244 // if this listen request applies and remove it.
3245 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3246 nai.removeRequest(nri.request.requestId);
3247 if (nri.request.networkCapabilities.hasSignalStrength() &&
3248 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3249 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3250 }
3251 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003252 }
3253 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003254
Lorenzo Colitti18660282016-07-04 12:55:44 +09003255 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003256 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucasline252a742019-03-12 13:08:03 +08003257 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003258 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003259 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003260 }
3261
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003262 @Override
lucasline252a742019-03-12 13:08:03 +08003263 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
3264 enforceNetworkStackSettingsOrSetup();
3265 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
3266 encodeBool(accept), encodeBool(always), network));
3267 }
3268
3269 @Override
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003270 public void setAvoidUnvalidated(Network network) {
lucasline252a742019-03-12 13:08:03 +08003271 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003272 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3273 }
3274
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003275 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3276 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3277 " accept=" + accept + " always=" + always);
3278
3279 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3280 if (nai == null) {
3281 // Nothing to do.
3282 return;
3283 }
3284
3285 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003286 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003287 return;
3288 }
3289
3290 if (!nai.networkMisc.explicitlySelected) {
3291 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3292 }
3293
3294 if (accept != nai.networkMisc.acceptUnvalidated) {
3295 int oldScore = nai.getCurrentScore();
3296 nai.networkMisc.acceptUnvalidated = accept;
lucasline252a742019-03-12 13:08:03 +08003297 // If network becomes partial connectivity and user already accepted to use this
3298 // network, we should respect the user's option and don't need to popup the
3299 // PARTIAL_CONNECTIVITY notification to user again.
3300 nai.networkMisc.acceptPartialConnectivity = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003301 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003302 sendUpdatedScoreToFactories(nai);
3303 }
3304
3305 if (always) {
3306 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003307 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003308 }
3309
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003310 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003311 // Tell the NetworkAgent to not automatically reconnect to the network.
3312 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003313 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003314 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003315 }
3316
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003317 }
3318
lucasline252a742019-03-12 13:08:03 +08003319 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
3320 boolean always) {
3321 if (DBG) {
3322 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
3323 + " always=" + always);
3324 }
3325
3326 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3327 if (nai == null) {
3328 // Nothing to do.
3329 return;
3330 }
3331
3332 if (nai.lastValidated) {
3333 // The network validated while the dialog box was up. Take no action.
3334 return;
3335 }
3336
3337 if (accept != nai.networkMisc.acceptPartialConnectivity) {
3338 nai.networkMisc.acceptPartialConnectivity = accept;
3339 }
3340
3341 // TODO: Use the current design or save the user choice into IpMemoryStore.
3342 if (always) {
3343 nai.asyncChannel.sendMessage(
3344 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
3345 }
3346
3347 if (!accept) {
3348 // Tell the NetworkAgent to not automatically reconnect to the network.
3349 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
3350 // Tear down the network.
3351 teardownUnneededNetwork(nai);
3352 } else {
lucaslin43338992019-03-20 18:21:59 +08003353 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
3354 // result in a partial connectivity result which will be processed by
3355 // maybeHandleNetworkMonitorMessage.
lucasline252a742019-03-12 13:08:03 +08003356 try {
lucaslin43338992019-03-20 18:21:59 +08003357 nai.networkMonitor().setAcceptPartialConnectivity();
lucasline252a742019-03-12 13:08:03 +08003358 } catch (RemoteException e) {
3359 e.rethrowFromSystemServer();
3360 }
3361 }
3362 }
3363
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003364 private void handleSetAvoidUnvalidated(Network network) {
3365 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3366 if (nai == null || nai.lastValidated) {
3367 // Nothing to do. The network either disconnected or revalidated.
3368 return;
3369 }
3370 if (!nai.avoidUnvalidated) {
3371 int oldScore = nai.getCurrentScore();
3372 nai.avoidUnvalidated = true;
3373 rematchAllNetworksAndRequests(nai, oldScore);
3374 sendUpdatedScoreToFactories(nai);
3375 }
3376 }
3377
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003378 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003379 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003380 mHandler.sendMessageDelayed(
3381 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3382 PROMPT_UNVALIDATED_DELAY_MS);
3383 }
3384
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003385 @Override
3386 public void startCaptivePortalApp(Network network) {
3387 enforceConnectivityInternalPermission();
3388 mHandler.post(() -> {
3389 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3390 if (nai == null) return;
3391 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003392 try {
3393 nai.networkMonitor().launchCaptivePortalApp();
3394 } catch (RemoteException e) {
3395 e.rethrowFromSystemServer();
3396 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003397 });
3398 }
3399
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003400 /**
3401 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
3402 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003403 * @param network Network on which the captive portal was detected.
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003404 * @param appExtras Bundle to use as intent extras for the captive portal application.
3405 * Must be treated as opaque to avoid preventing the captive portal app to
3406 * update its arguments.
3407 */
3408 @Override
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003409 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003410 mContext.checkCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3411
3412 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
3413 appIntent.putExtras(appExtras);
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003414 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
3415 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VANdc483562019-02-04 11:32:20 +09003416 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
3417
3418 Binder.withCleanCallingIdentity(() ->
3419 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT));
3420 }
3421
Remi NGUYEN VANcfff01e2019-02-13 20:58:59 +09003422 private class CaptivePortalImpl extends ICaptivePortal.Stub {
3423 private final Network mNetwork;
3424
3425 private CaptivePortalImpl(Network network) {
3426 mNetwork = network;
3427 }
3428
3429 @Override
3430 public void appResponse(final int response) throws RemoteException {
3431 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
3432 enforceSettingsPermission();
3433 }
3434
3435 // getNetworkAgentInfoForNetwork is thread-safe
3436 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
3437 if (nai == null) return;
3438
3439 // nai.networkMonitor() is thread-safe
3440 final INetworkMonitor nm = nai.networkMonitor();
3441 if (nm == null) return;
3442
3443 final long token = Binder.clearCallingIdentity();
3444 try {
3445 nm.notifyCaptivePortalAppFinished(response);
3446 } finally {
3447 // Not using Binder.withCleanCallingIdentity() to keep the checked RemoteException
3448 Binder.restoreCallingIdentity(token);
3449 }
3450 }
3451
3452 @Override
3453 public void logEvent(int eventId, String packageName) {
3454 enforceSettingsPermission();
3455
3456 new MetricsLogger().action(eventId, packageName);
3457 }
3458 }
3459
Hugo Benichic8e9e122016-09-14 23:23:08 +00003460 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003461 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003462 }
3463
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003464 @Override
3465 public boolean getAvoidBadWifi() {
3466 if (!checkNetworkStackPermission()) {
3467 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3468 }
3469 return avoidBadWifi();
3470 }
3471
3472
Erik Kline065ab6e2016-10-02 18:02:14 +09003473 private void rematchForAvoidBadWifiUpdate() {
3474 rematchAllNetworksAndRequests(null, 0);
3475 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3476 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3477 sendUpdatedScoreToFactories(nai);
3478 }
3479 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003480 }
3481
Erik Kline065ab6e2016-10-02 18:02:14 +09003482 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003483 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003484 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003485 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003486 if (!configRestrict) {
3487 pw.println("Bad Wi-Fi avoidance: unrestricted");
3488 return;
3489 }
3490
3491 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3492 pw.increaseIndent();
3493 pw.println("Config restrict: " + configRestrict);
3494
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003495 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003496 String description;
3497 // Can't use a switch statement because strings are legal case labels, but null is not.
3498 if ("0".equals(value)) {
3499 description = "get stuck";
3500 } else if (value == null) {
3501 description = "prompt";
3502 } else if ("1".equals(value)) {
3503 description = "avoid";
3504 } else {
3505 description = value + " (?)";
3506 }
3507 pw.println("User setting: " + description);
3508 pw.println("Network overrides:");
3509 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003510 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003511 if (nai.avoidUnvalidated) {
3512 pw.println(nai.name());
3513 }
3514 }
3515 pw.decreaseIndent();
3516 pw.decreaseIndent();
3517 }
3518
lucaslind2e045e02019-01-24 15:55:30 +08003519 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003520 final String action;
3521 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003522 case LOGGED_IN:
3523 action = Settings.ACTION_WIFI_SETTINGS;
3524 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3525 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3526 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3527 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003528 case NO_INTERNET:
3529 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3530 break;
3531 case LOST_INTERNET:
3532 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3533 break;
lucasline252a742019-03-12 13:08:03 +08003534 case PARTIAL_CONNECTIVITY:
3535 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
3536 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003537 default:
3538 Slog.wtf(TAG, "Unknown notification type " + type);
3539 return;
3540 }
3541
3542 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003543 if (type != NotificationType.LOGGED_IN) {
3544 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3545 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3546 intent.setClassName("com.android.settings",
3547 "com.android.settings.wifi.WifiNoInternetDialog");
3548 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003549
3550 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3551 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3552 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3553 }
3554
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003555 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003556 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003557 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3558
lucasline252a742019-03-12 13:08:03 +08003559 // Only prompt if the network is unvalidated or network has partial internet connectivity
3560 // and was explicitly selected by the user, and if we haven't already been told to switch
3561 // to it regardless of whether it validated or not. Also don't prompt on captive portals
3562 // because we're already prompting the user to sign in.
3563 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected
3564 || !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated
lucaslin43338992019-03-20 18:21:59 +08003565 // TODO: Once the value of acceptPartialConnectivity is moved to IpMemoryStore,
3566 // we should reevaluate how to handle acceptPartialConnectivity when network just
3567 // connected.
lucasline252a742019-03-12 13:08:03 +08003568 || nai.networkMisc.acceptPartialConnectivity) {
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003569 return;
3570 }
lucasline252a742019-03-12 13:08:03 +08003571 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
3572 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
3573 // popup the notification immediately when the network is partial connectivity.
3574 if (nai.partialConnectivity) {
3575 // Treat PARTIAL_CONNECTIVITY as NO_INTERNET temporary until Settings has been updated.
3576 // TODO: Need to change back to PARTIAL_CONNECTIVITY when Settings part is merged.
3577 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3578 } else {
3579 showNetworkNotification(nai, NotificationType.NO_INTERNET);
3580 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003581 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003582
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003583 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3584 NetworkCapabilities nc = nai.networkCapabilities;
3585 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003586
lucasline252a742019-03-12 13:08:03 +08003587 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3588 return;
3589 }
3590
3591 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003592 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003593 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003594 }
3595
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003596 @Override
3597 public int getMultipathPreference(Network network) {
3598 enforceAccessPermission();
3599
3600 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003601 if (nai != null && nai.networkCapabilities
3602 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003603 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3604 }
3605
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003606 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3607 if (networkPreference != null) {
3608 return networkPreference;
3609 }
3610
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003611 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3612 }
3613
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003614 @Override
3615 public NetworkRequest getDefaultRequest() {
3616 return mDefaultRequest;
3617 }
3618
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003619 private class InternalHandler extends Handler {
3620 public InternalHandler(Looper looper) {
3621 super(looper);
3622 }
3623
3624 @Override
3625 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003626 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003627 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003628 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003629 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003630 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003631 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003632 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003633 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003634 break;
3635 }
Jason Monkdecd2952013-10-10 14:02:51 -04003636 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003637 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003638 break;
3639 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003640 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003641 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3642 break;
3643 }
3644 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3645 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003646 break;
3647 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003648 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003649 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3650 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3651 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003652 break;
3653 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003654 case EVENT_REGISTER_NETWORK_REQUEST:
3655 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003656 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003657 break;
3658 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003659 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3660 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003661 handleRegisterNetworkRequestWithIntent(msg);
3662 break;
3663 }
Erik Kline57faba92015-11-25 12:49:38 +09003664 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3665 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3666 handleTimedOutNetworkRequest(nri);
3667 break;
3668 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003669 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3670 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3671 break;
3672 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003673 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenddb720a2019-01-08 12:09:18 -08003674 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
3675 /* callOnUnavailable */ false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003676 break;
3677 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003678 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003679 Network network = (Network) msg.obj;
3680 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003681 break;
3682 }
lucasline252a742019-03-12 13:08:03 +08003683 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
3684 Network network = (Network) msg.obj;
3685 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
3686 toBool(msg.arg2));
3687 break;
3688 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003689 case EVENT_SET_AVOID_UNVALIDATED: {
3690 handleSetAvoidUnvalidated((Network) msg.obj);
3691 break;
3692 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003693 case EVENT_PROMPT_UNVALIDATED: {
3694 handlePromptUnvalidated((Network) msg.obj);
3695 break;
3696 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003697 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3698 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003699 break;
3700 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003701 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003702 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003703 mKeepaliveTracker.handleStartKeepalive(msg);
3704 break;
3705 }
3706 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai06835112019-01-03 18:50:15 +08003707 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003708 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3709 int slot = msg.arg1;
3710 int reason = msg.arg2;
3711 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3712 break;
3713 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003714 case EVENT_SYSTEM_READY: {
3715 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003716 // Might have been called already in handleRegisterNetworkAgent since
3717 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3718 // this several times is fine.
3719 try {
3720 nai.networkMonitor().notifySystemReady();
3721 } catch (RemoteException e) {
3722 e.rethrowFromSystemServer();
3723 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003724 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003725 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003726 break;
3727 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003728 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003729 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003730 break;
3731 }
Erik Klinea24d4592018-01-11 21:07:29 +09003732 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3733 handlePrivateDnsSettingsChanged();
3734 break;
dalyk7301aa42018-03-05 12:42:22 -05003735 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3736 handlePrivateDnsValidationUpdate(
3737 (PrivateDnsValidationUpdate) msg.obj);
3738 break;
junyulai05986c62018-08-07 19:50:45 +08003739 case EVENT_UID_RULES_CHANGED:
3740 handleUidRulesChanged(msg.arg1, msg.arg2);
3741 break;
3742 case EVENT_DATA_SAVER_CHANGED:
3743 handleRestrictBackgroundChanged(toBool(msg.arg1));
3744 break;
lucaslind2e045e02019-01-24 15:55:30 +08003745 case EVENT_TIMEOUT_NOTIFICATION:
3746 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3747 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 }
3749 }
3750 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003751
3752 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003753 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003754 public int tether(String iface, String callerPkg) {
3755 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003756 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003757 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003758 } else {
3759 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3760 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003761 }
3762
3763 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003764 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003765 public int untether(String iface, String callerPkg) {
3766 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003767
3768 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003769 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003770 } else {
3771 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3772 }
3773 }
3774
3775 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003776 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003777 public int getLastTetherError(String iface) {
3778 enforceTetherAccessPermission();
3779
3780 if (isTetheringSupported()) {
3781 return mTethering.getLastTetherError(iface);
3782 } else {
3783 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3784 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003785 }
3786
3787 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003788 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003789 public String[] getTetherableUsbRegexs() {
3790 enforceTetherAccessPermission();
3791 if (isTetheringSupported()) {
3792 return mTethering.getTetherableUsbRegexs();
3793 } else {
3794 return new String[0];
3795 }
3796 }
3797
Lorenzo Colitti18660282016-07-04 12:55:44 +09003798 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003799 public String[] getTetherableWifiRegexs() {
3800 enforceTetherAccessPermission();
3801 if (isTetheringSupported()) {
3802 return mTethering.getTetherableWifiRegexs();
3803 } else {
3804 return new String[0];
3805 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003806 }
3807
Lorenzo Colitti18660282016-07-04 12:55:44 +09003808 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003809 public String[] getTetherableBluetoothRegexs() {
3810 enforceTetherAccessPermission();
3811 if (isTetheringSupported()) {
3812 return mTethering.getTetherableBluetoothRegexs();
3813 } else {
3814 return new String[0];
3815 }
3816 }
3817
Lorenzo Colitti18660282016-07-04 12:55:44 +09003818 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003819 public int setUsbTethering(boolean enable, String callerPkg) {
3820 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003821 if (isTetheringSupported()) {
3822 return mTethering.setUsbTethering(enable);
3823 } else {
3824 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3825 }
3826 }
3827
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003828 // TODO - move iface listing, queries, etc to new module
3829 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003830 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003831 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003832 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003833 return mTethering.getTetherableIfaces();
3834 }
3835
Lorenzo Colitti18660282016-07-04 12:55:44 +09003836 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003837 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003838 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003839 return mTethering.getTetheredIfaces();
3840 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003841
Lorenzo Colitti18660282016-07-04 12:55:44 +09003842 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003843 public String[] getTetheringErroredIfaces() {
3844 enforceTetherAccessPermission();
3845 return mTethering.getErroredIfaces();
3846 }
3847
Lorenzo Colitti18660282016-07-04 12:55:44 +09003848 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003849 public String[] getTetheredDhcpRanges() {
3850 enforceConnectivityInternalPermission();
3851 return mTethering.getTetheredDhcpRanges();
3852 }
3853
Udam Saini0e94c362017-06-07 12:06:28 -07003854 @Override
3855 public boolean isTetheringSupported(String callerPkg) {
3856 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3857 return isTetheringSupported();
3858 }
3859
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003860 // if ro.tether.denied = true we default to no tethering
3861 // gservices could set the secure setting to 1 though to enable it on a build where it
3862 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003863 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003864 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3865 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3866 Settings.Global.TETHER_SUPPORTED, defaultVal));
3867 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003868 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003869
3870 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3871 boolean adminUser = false;
3872 final long token = Binder.clearCallingIdentity();
3873 try {
3874 adminUser = mUserManager.isAdminUser();
3875 } finally {
3876 Binder.restoreCallingIdentity(token);
3877 }
3878
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003879 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003880 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003881
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003882 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003883 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3884 String callerPkg) {
3885 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003886 if (!isTetheringSupported()) {
3887 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3888 return;
3889 }
3890 mTethering.startTethering(type, receiver, showProvisioningUi);
3891 }
3892
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003893 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003894 public void stopTethering(int type, String callerPkg) {
3895 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003896 mTethering.stopTethering(type);
3897 }
3898
markchienf2731272019-01-16 17:44:13 +08003899 /**
3900 * Get the latest value of the tethering entitlement check.
3901 *
3902 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3903 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3904 * if it's really needed.
3905 */
3906 @Override
markchien9554abf2019-03-06 16:25:00 +08003907 public void getLatestTetheringEntitlementResult(int type, ResultReceiver receiver,
markchienf2731272019-01-16 17:44:13 +08003908 boolean showEntitlementUi, String callerPkg) {
3909 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
markchien9554abf2019-03-06 16:25:00 +08003910 mTethering.getLatestTetheringEntitlementResult(type, receiver, showEntitlementUi);
markchienf2731272019-01-16 17:44:13 +08003911 }
3912
markchien26299ed2019-02-27 14:56:11 +08003913 /** Register tethering event callback. */
3914 @Override
3915 public void registerTetheringEventCallback(ITetheringEventCallback callback,
3916 String callerPkg) {
3917 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3918 mTethering.registerTetheringEventCallback(callback);
3919 }
3920
3921 /** Unregister tethering event callback. */
3922 @Override
3923 public void unregisterTetheringEventCallback(ITetheringEventCallback callback,
3924 String callerPkg) {
3925 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3926 mTethering.unregisterTetheringEventCallback(callback);
3927 }
3928
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003929 // Called when we lose the default network and have no replacement yet.
3930 // This will automatically be cleared after X seconds or a new default network
3931 // becomes CONNECTED, whichever happens first. The timer is started by the
3932 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003933 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003934 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003935 if (mNetTransitionWakeLock.isHeld()) {
3936 return;
3937 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003938 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003939 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3940 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003941 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003942 mWakelockLogs.log("ACQUIRE for " + forWhom);
3943 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3944 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003945 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003946
Hugo Benichi4c31b342017-03-30 23:18:10 +09003947 // Called when we gain a new default network to release the network transition wakelock in a
3948 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3949 // message is cancelled.
3950 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003951 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003952 if (!mNetTransitionWakeLock.isHeld()) {
3953 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003954 }
3955 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003956 // Cancel self timeout on wakelock hold.
3957 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3958 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3959 mHandler.sendMessageDelayed(msg, 1000);
3960 }
3961
3962 // Called when either message of ensureNetworkTransitionWakelock or
3963 // scheduleReleaseNetworkTransitionWakelock is processed.
3964 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3965 String event = eventName(eventId);
3966 synchronized (this) {
3967 if (!mNetTransitionWakeLock.isHeld()) {
3968 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3969 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3970 return;
3971 }
3972 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003973 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3974 mTotalWakelockDurationMs += lockDuration;
3975 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3976 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003977 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003978 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003979 }
3980
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003981 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003982 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003983 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003984 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003985 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003986 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003987 }
3988
Lorenzo Colitti18660282016-07-04 12:55:44 +09003989 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003990 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003991 enforceAccessPermission();
3992 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003993 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003994 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003995 mHandler.sendMessage(
3996 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3997 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003998
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003999 private void handleReportNetworkConnectivity(
4000 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004001 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04004002 if (network == null) {
4003 nai = getDefaultNetwork();
4004 } else {
4005 nai = getNetworkAgentInfoForNetwork(network);
4006 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04004007 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4008 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4009 return;
4010 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004011 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004012 if (hasConnectivity == nai.lastValidated) {
4013 return;
4014 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04004015 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09004016 int netid = nai.network.netId;
4017 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04004018 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004019 // Validating a network that has not yet connected could result in a call to
4020 // rematchNetworkAndRequests() which is not meant to work on such networks.
4021 if (!nai.everConnected) {
4022 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04004023 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09004024 LinkProperties lp = getLinkProperties(nai);
4025 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
4026 return;
4027 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004028 try {
4029 nai.networkMonitor().forceReevaluation(uid);
4030 } catch (RemoteException e) {
4031 e.rethrowFromSystemServer();
4032 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004033 }
4034
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004035 /**
4036 * Returns information about the proxy a certain network is using. If given a null network, it
4037 * it will return the proxy for the bound network for the caller app or the default proxy if
4038 * none.
4039 *
4040 * @param network the network we want to get the proxy information for.
4041 * @return Proxy information if a network has a proxy configured, or otherwise null.
4042 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09004043 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04004044 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09004045 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04004046 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004047 if (network == null) {
4048 // Get the network associated with the calling UID.
4049 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
4050 true);
4051 if (activeNetwork == null) {
4052 return null;
4053 }
4054 return getLinkPropertiesProxyInfo(activeNetwork);
4055 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
4056 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
4057 // caller may not have.
4058 return getLinkPropertiesProxyInfo(network);
4059 }
4060 // No proxy info available if the calling UID does not have network access.
4061 return null;
4062 }
4063
4064 @VisibleForTesting
4065 protected boolean queryUserAccess(int uid, int netId) {
4066 return NetworkUtils.queryUserAccess(uid, netId);
4067 }
4068
4069 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04004070 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4071 if (nai == null) return null;
4072 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004073 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
4074 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04004075 }
4076 }
4077
Chalard Jean3c443fc2018-06-07 18:37:59 +09004078 @Override
4079 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07004080 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09004081 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004082 }
4083
Chalard Jean5afbc832018-06-07 18:02:37 +09004084 @Override
4085 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04004086 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09004087 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07004088 }
4089
Jason Monk207900c2014-04-25 15:00:09 -04004090 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04004091 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05004092 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07004093 proxy = null;
4094 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09004095 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004096 }
4097
Irina Dumitrescu044a4362018-12-05 16:19:47 +00004098 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
4099 // when any network changes proxy.
4100 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
4101 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09004102 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05004103 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
4104 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
4105
Chalard Jean4949dd72018-06-07 17:41:29 +09004106 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09004107 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05004108 }
4109 }
4110
Robert Greenwalt434203a2010-10-11 16:00:27 -07004111 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09004112 final private HashMap<Uri, Integer> mUriEventMap;
4113 final private Context mContext;
4114 final private Handler mHandler;
4115
4116 SettingsObserver(Context context, Handler handler) {
4117 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09004118 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09004119 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004120 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07004121 }
4122
Erik Klineda4bfa82015-04-30 12:58:40 +09004123 void observe(Uri uri, int what) {
4124 mUriEventMap.put(uri, what);
4125 final ContentResolver resolver = mContext.getContentResolver();
4126 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07004127 }
4128
4129 @Override
4130 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09004131 Slog.wtf(TAG, "Should never be reached.");
4132 }
4133
4134 @Override
4135 public void onChange(boolean selfChange, Uri uri) {
4136 final Integer what = mUriEventMap.get(uri);
4137 if (what != null) {
4138 mHandler.obtainMessage(what.intValue()).sendToTarget();
4139 } else {
4140 loge("No matching event to send for URI=" + uri);
4141 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07004142 }
4143 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08004144
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004145 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004146 Slog.d(TAG, s);
4147 }
4148
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07004149 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08004150 Slog.e(TAG, s);
4151 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004152
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004153 private static void loge(String s, Throwable t) {
4154 Slog.e(TAG, s, t);
4155 }
4156
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004157 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08004158 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01004159 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4160 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4161 *
4162 * @param oldPackage Package name of the application which currently controls VPN, which will
4163 * be replaced. If there is no such application, this should should either be
4164 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
4165 * @param newPackage Package name of the application which should gain control of VPN, or
4166 * {@code null} to disable.
4167 * @param userId User for whom to prepare the new VPN.
4168 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004169 * @hide
4170 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004171 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004172 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
4173 int userId) {
4174 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01004175
Hugo Benichi20035e02017-04-26 14:53:28 +09004176 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004177 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07004178 Vpn vpn = mVpns.get(userId);
4179 if (vpn != null) {
4180 return vpn.prepare(oldPackage, newPackage);
4181 } else {
4182 return false;
4183 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004184 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004185 }
4186
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004187 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004188 * Set whether the VPN package has the ability to launch VPNs without user intervention.
4189 * This method is used by system-privileged apps.
4190 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
4191 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
4192 *
4193 * @param packageName The package for which authorization state should change.
4194 * @param userId User for whom {@code packageName} is installed.
4195 * @param authorized {@code true} if this app should be able to start a VPN connection without
4196 * explicit user approval, {@code false} if not.
4197 *
Jeff Davidson05542602014-08-11 14:07:27 -07004198 * @hide
4199 */
4200 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004201 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
4202 enforceCrossUserPermission(userId);
4203
Hugo Benichi20035e02017-04-26 14:53:28 +09004204 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004205 Vpn vpn = mVpns.get(userId);
4206 if (vpn != null) {
4207 vpn.setPackageAuthorization(packageName, authorized);
4208 }
Jeff Davidson05542602014-08-11 14:07:27 -07004209 }
4210 }
4211
4212 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004213 * Configure a TUN interface and return its file descriptor. Parameters
4214 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004215 * and not available in ConnectivityManager. Permissions are checked in
4216 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004217 * @hide
4218 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004219 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07004220 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004221 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09004222 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004223 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004224 return mVpns.get(user).establish(config);
4225 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004226 }
4227
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004228 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07004229 * Start legacy VPN, controlling native daemons as needed. Creates a
4230 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004231 */
4232 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07004233 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09004234 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07004235 final LinkProperties egress = getActiveLinkProperties();
4236 if (egress == null) {
4237 throw new IllegalStateException("Missing active network connection");
4238 }
Hugo Benichi20035e02017-04-26 14:53:28 +09004239 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004240 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004241 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4242 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004243 }
4244
4245 /**
4246 * Return the information of the ongoing legacy VPN. This method is used
4247 * by VpnSettings and not available in ConnectivityManager. Permissions
4248 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07004249 */
4250 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07004251 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
4252 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08004253
Hugo Benichi20035e02017-04-26 14:53:28 +09004254 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07004255 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004256 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07004257 }
4258
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07004259 /**
Varun Anandd33cbc62019-02-07 14:13:13 -08004260 * Return the information of all ongoing VPNs.
4261 *
4262 * <p>This method is used to update NetworkStatsService.
4263 *
4264 * <p>Must be called on the handler thread.
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004265 */
Varun Anandd33cbc62019-02-07 14:13:13 -08004266 private VpnInfo[] getAllVpnInfo() {
4267 ensureRunningOnConnectivityServiceThread();
Hugo Benichi20035e02017-04-26 14:53:28 +09004268 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004269 if (mLockdownEnabled) {
4270 return new VpnInfo[0];
4271 }
4272
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004273 List<VpnInfo> infoList = new ArrayList<>();
4274 for (int i = 0; i < mVpns.size(); i++) {
4275 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
4276 if (info != null) {
4277 infoList.add(info);
4278 }
4279 }
4280 return infoList.toArray(new VpnInfo[infoList.size()]);
4281 }
4282 }
4283
4284 /**
4285 * @return VPN information for accounting, or null if we can't retrieve all required
4286 * information, e.g primary underlying iface.
4287 */
4288 @Nullable
4289 private VpnInfo createVpnInfo(Vpn vpn) {
4290 VpnInfo info = vpn.getVpnInfo();
4291 if (info == null) {
4292 return null;
4293 }
4294 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4295 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4296 // the underlyingNetworks list.
4297 if (underlyingNetworks == null) {
4298 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4299 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4300 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4301 }
4302 } else if (underlyingNetworks.length > 0) {
4303 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4304 if (linkProperties != null) {
4305 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4306 }
4307 }
4308 return info.primaryUnderlyingIface == null ? null : info;
4309 }
4310
4311 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004312 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4313 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004314 * Permissions are checked in Vpn class.
4315 * @hide
4316 */
4317 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004318 public VpnConfig getVpnConfig(int userId) {
4319 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004320 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004321 Vpn vpn = mVpns.get(userId);
4322 if (vpn != null) {
4323 return vpn.getVpnConfig();
4324 } else {
4325 return null;
4326 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004327 }
4328 }
4329
Chalard Jean6b65ec72018-05-18 22:02:56 +09004330 /**
4331 * Ask all VPN objects to recompute and update their capabilities.
4332 *
4333 * When underlying networks change, VPNs may have to update capabilities to reflect things
4334 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4335 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4336 * handler thread through their agent, this is asynchronous. When the capabilities objects
4337 * are computed they will be up-to-date as they are computed synchronously from here and
4338 * this is running on the ConnectivityService thread.
Chalard Jean6b65ec72018-05-18 22:02:56 +09004339 */
4340 private void updateAllVpnsCapabilities() {
Varun Anand4fa80e82019-02-06 10:13:38 -08004341 Network defaultNetwork = getNetwork(getDefaultNetwork());
Chalard Jean6b65ec72018-05-18 22:02:56 +09004342 synchronized (mVpns) {
4343 for (int i = 0; i < mVpns.size(); i++) {
4344 final Vpn vpn = mVpns.valueAt(i);
Varun Anand4fa80e82019-02-06 10:13:38 -08004345 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4346 updateVpnCapabilities(vpn, nc);
Chalard Jean6b65ec72018-05-18 22:02:56 +09004347 }
4348 }
4349 }
4350
Varun Anand4fa80e82019-02-06 10:13:38 -08004351 private void updateVpnCapabilities(Vpn vpn, @Nullable NetworkCapabilities nc) {
4352 ensureRunningOnConnectivityServiceThread();
4353 NetworkAgentInfo vpnNai = getNetworkAgentInfoForNetId(vpn.getNetId());
4354 if (vpnNai == null || nc == null) {
4355 return;
4356 }
4357 updateCapabilities(vpnNai.getCurrentScore(), vpnNai, nc);
4358 }
4359
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004360 @Override
4361 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004362 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4363 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4364 return false;
4365 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004366
Hugo Benichi69744342017-11-27 10:57:16 +09004367 synchronized (mVpns) {
4368 // Tear down existing lockdown if profile was removed
4369 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4370 if (mLockdownEnabled) {
4371 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4372 if (profileTag == null) {
4373 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4374 return false;
4375 }
4376 String profileName = new String(profileTag);
4377 final VpnProfile profile = VpnProfile.decode(
4378 profileName, mKeyStore.get(Credentials.VPN + profileName));
4379 if (profile == null) {
4380 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4381 setLockdownTracker(null);
4382 return true;
4383 }
4384 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004385 Vpn vpn = mVpns.get(user);
4386 if (vpn == null) {
4387 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4388 return false;
4389 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004390 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004391 } else {
4392 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004393 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004394 }
4395
4396 return true;
4397 }
4398
4399 /**
4400 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4401 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4402 */
Hugo Benichi69744342017-11-27 10:57:16 +09004403 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004404 private void setLockdownTracker(LockdownVpnTracker tracker) {
4405 // Shutdown any existing tracker
4406 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004407 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4408 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004409 mLockdownTracker = null;
4410 if (existing != null) {
4411 existing.shutdown();
4412 }
4413
Robin Leec3736bc2017-03-10 16:19:54 +00004414 if (tracker != null) {
4415 mLockdownTracker = tracker;
4416 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004417 }
4418 }
4419
Hugo Benichi69744342017-11-27 10:57:16 +09004420 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004421 private void throwIfLockdownEnabled() {
4422 if (mLockdownEnabled) {
4423 throw new IllegalStateException("Unavailable in lockdown mode");
4424 }
4425 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004426
Robin Lee244ce8e2016-01-05 18:03:46 +00004427 /**
Robin Lee17e61832016-05-09 13:46:28 +01004428 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4429 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004430 *
Robin Lee17e61832016-05-09 13:46:28 +01004431 * @return {@code true} if the service was started, the service was already connected, or there
4432 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004433 */
Robin Lee17e61832016-05-09 13:46:28 +01004434 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004435 synchronized (mVpns) {
4436 Vpn vpn = mVpns.get(userId);
4437 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004438 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004439 // exists already.
4440 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4441 return false;
4442 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004443
Robin Lee812800c2016-05-13 15:38:08 +01004444 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004445 }
4446 }
4447
4448 @Override
Charles He36738632017-05-15 17:07:18 +01004449 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4450 enforceSettingsPermission();
4451 enforceCrossUserPermission(userId);
4452
4453 synchronized (mVpns) {
4454 Vpn vpn = mVpns.get(userId);
4455 if (vpn == null) {
4456 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4457 return false;
4458 }
4459 return vpn.isAlwaysOnPackageSupported(packageName);
4460 }
4461 }
4462
4463 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004464 public boolean setAlwaysOnVpnPackage(
4465 int userId, String packageName, boolean lockdown, List<String> lockdownWhitelist) {
4466 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004467 enforceCrossUserPermission(userId);
4468
Robin Lee244ce8e2016-01-05 18:03:46 +00004469 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004470 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4471 if (LockdownVpnTracker.isEnabled()) {
4472 return false;
4473 }
4474
Robin Lee244ce8e2016-01-05 18:03:46 +00004475 Vpn vpn = mVpns.get(userId);
4476 if (vpn == null) {
4477 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4478 return false;
4479 }
Pavel Grafova462bcb2019-01-25 08:50:06 +00004480 if (!vpn.setAlwaysOnPackage(packageName, lockdown, lockdownWhitelist)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004481 return false;
4482 }
Robin Lee17e61832016-05-09 13:46:28 +01004483 if (!startAlwaysOnVpn(userId)) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004484 vpn.setAlwaysOnPackage(null, false, null);
Robin Lee244ce8e2016-01-05 18:03:46 +00004485 return false;
4486 }
4487 }
4488 return true;
4489 }
4490
4491 @Override
4492 public String getAlwaysOnVpnPackage(int userId) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00004493 enforceControlAlwaysOnVpnPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004494 enforceCrossUserPermission(userId);
4495
4496 synchronized (mVpns) {
4497 Vpn vpn = mVpns.get(userId);
4498 if (vpn == null) {
4499 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4500 return null;
4501 }
4502 return vpn.getAlwaysOnPackage();
4503 }
4504 }
4505
Wink Savilleab9321d2013-06-29 21:10:57 -07004506 @Override
Pavel Grafova462bcb2019-01-25 08:50:06 +00004507 public boolean isVpnLockdownEnabled(int userId) {
4508 enforceControlAlwaysOnVpnPermission();
4509 enforceCrossUserPermission(userId);
4510
4511 synchronized (mVpns) {
4512 Vpn vpn = mVpns.get(userId);
4513 if (vpn == null) {
4514 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4515 return false;
4516 }
4517 return vpn.getLockdown();
4518 }
4519 }
4520
4521 @Override
4522 public List<String> getVpnLockdownWhitelist(int userId) {
4523 enforceControlAlwaysOnVpnPermission();
4524 enforceCrossUserPermission(userId);
4525
4526 synchronized (mVpns) {
4527 Vpn vpn = mVpns.get(userId);
4528 if (vpn == null) {
4529 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4530 return null;
4531 }
4532 return vpn.getLockdownWhitelist();
4533 }
4534 }
4535
4536 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004537 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004538 // TODO: Remove? Any reason to trigger a provisioning check?
4539 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004540 }
4541
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004542 /** Location to an updatable file listing carrier provisioning urls.
4543 * An example:
4544 *
4545 * <?xml version="1.0" encoding="utf-8"?>
4546 * <provisioningUrls>
4547 * <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 -07004548 * </provisioningUrls>
4549 */
4550 private static final String PROVISIONING_URL_PATH =
4551 "/data/misc/radio/provisioning_urls.xml";
4552 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004553
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004554 /** XML tag for root element. */
4555 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4556 /** XML tag for individual url */
4557 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004558 /** XML attribute for mcc */
4559 private static final String ATTR_MCC = "mcc";
4560 /** XML attribute for mnc */
4561 private static final String ATTR_MNC = "mnc";
4562
Paul Jensen434dde82015-06-11 09:43:30 -04004563 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004564 FileReader fileReader = null;
4565 XmlPullParser parser = null;
4566 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004567
4568 try {
4569 fileReader = new FileReader(mProvisioningUrlFile);
4570 parser = Xml.newPullParser();
4571 parser.setInput(fileReader);
4572 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4573
4574 while (true) {
4575 XmlUtils.nextElement(parser);
4576
4577 String element = parser.getName();
4578 if (element == null) break;
4579
Paul Jensen434dde82015-06-11 09:43:30 -04004580 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004581 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4582 try {
4583 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4584 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4585 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4586 parser.next();
4587 if (parser.getEventType() == XmlPullParser.TEXT) {
4588 return parser.getText();
4589 }
4590 }
4591 }
4592 } catch (NumberFormatException e) {
4593 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4594 }
4595 }
4596 }
4597 return null;
4598 } catch (FileNotFoundException e) {
4599 loge("Carrier Provisioning Urls file not found");
4600 } catch (XmlPullParserException e) {
4601 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4602 } catch (IOException e) {
4603 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4604 } finally {
4605 if (fileReader != null) {
4606 try {
4607 fileReader.close();
4608 } catch (IOException e) {}
4609 }
4610 }
4611 return null;
4612 }
4613
Wink Saville42d4f082013-07-20 20:31:59 -07004614 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004615 public String getMobileProvisioningUrl() {
4616 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004617 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004618 if (TextUtils.isEmpty(url)) {
4619 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004620 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004621 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004622 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004623 }
Wink Saville8cf35602013-07-10 23:00:07 -07004624 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004625 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004626 String phoneNumber = mTelephonyManager.getLine1Number();
4627 if (TextUtils.isEmpty(phoneNumber)) {
4628 phoneNumber = "0000000000";
4629 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004630 url = String.format(url,
4631 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4632 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004633 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004634 }
4635
Wink Savilleab9321d2013-06-29 21:10:57 -07004636 return url;
4637 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004638
Wink Saville948282b2013-08-29 08:55:16 -07004639 @Override
4640 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004641 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004642 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004643 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4644 return;
4645 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004646 final long ident = Binder.clearCallingIdentity();
4647 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004648 // Concatenate the range of types onto the range of NetIDs.
4649 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4650 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004651 } finally {
4652 Binder.restoreCallingIdentity(ident);
4653 }
Wink Saville948282b2013-08-29 08:55:16 -07004654 }
Wink Saville7788c612013-08-29 14:57:08 -07004655
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004656 @Override
4657 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004658 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004659 final long ident = Binder.clearCallingIdentity();
4660 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004661 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004662 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004663 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4664 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004665 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004666 } finally {
4667 Binder.restoreCallingIdentity(ident);
4668 }
4669 }
4670
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004671 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004672 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004673 Vpn userVpn = mVpns.get(userId);
4674 if (userVpn != null) {
4675 loge("Starting user already has a VPN");
4676 return;
4677 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004678 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004679 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004680 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4681 updateLockdownVpn();
4682 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004683 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004684 }
4685
4686 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004687 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004688 Vpn userVpn = mVpns.get(userId);
4689 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004690 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004691 return;
4692 }
Robin Lee17e61832016-05-09 13:46:28 +01004693 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004694 mVpns.delete(userId);
4695 }
4696 }
4697
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004698 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004699 mPermissionMonitor.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004700 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004701 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004702 final int vpnsSize = mVpns.size();
4703 for (int i = 0; i < vpnsSize; i++) {
4704 Vpn vpn = mVpns.valueAt(i);
4705 vpn.onUserAdded(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004706 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4707 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004708 }
4709 }
4710 }
4711
4712 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004713 mPermissionMonitor.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004714 Network defaultNetwork = getNetwork(getDefaultNetwork());
Hugo Benichi20035e02017-04-26 14:53:28 +09004715 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004716 final int vpnsSize = mVpns.size();
4717 for (int i = 0; i < vpnsSize; i++) {
4718 Vpn vpn = mVpns.valueAt(i);
4719 vpn.onUserRemoved(userId);
Varun Anand4fa80e82019-02-06 10:13:38 -08004720 NetworkCapabilities nc = vpn.updateCapabilities(defaultNetwork);
4721 updateVpnCapabilities(vpn, nc);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004722 }
4723 }
4724 }
4725
junyulai2454b692018-11-01 17:16:31 +08004726 private void onPackageAdded(String packageName, int uid) {
4727 if (TextUtils.isEmpty(packageName) || uid < 0) {
4728 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4729 return;
4730 }
4731 mPermissionMonitor.onPackageAdded(packageName, uid);
4732 }
4733
junyulaiefb04d32018-11-12 22:39:30 +08004734 private void onPackageReplaced(String packageName, int uid) {
4735 if (TextUtils.isEmpty(packageName) || uid < 0) {
4736 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4737 return;
4738 }
4739 final int userId = UserHandle.getUserId(uid);
4740 synchronized (mVpns) {
4741 final Vpn vpn = mVpns.get(userId);
4742 if (vpn == null) {
4743 return;
4744 }
4745 // Legacy always-on VPN won't be affected since the package name is not set.
4746 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4747 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4748 + userId);
4749 vpn.startAlwaysOnVpn();
4750 }
4751 }
4752 }
4753
4754 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004755 if (TextUtils.isEmpty(packageName) || uid < 0) {
4756 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4757 return;
4758 }
4759 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004760
4761 final int userId = UserHandle.getUserId(uid);
4762 synchronized (mVpns) {
4763 final Vpn vpn = mVpns.get(userId);
4764 if (vpn == null) {
4765 return;
4766 }
4767 // Legacy always-on VPN won't be affected since the package name is not set.
4768 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4769 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4770 + userId);
Pavel Grafova462bcb2019-01-25 08:50:06 +00004771 vpn.setAlwaysOnPackage(null, false, null);
junyulaiefb04d32018-11-12 22:39:30 +08004772 }
4773 }
junyulai2454b692018-11-01 17:16:31 +08004774 }
4775
Robin Lee89e7a692016-02-29 14:38:17 +00004776 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004777 synchronized (mVpns) {
4778 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4779 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4780 updateLockdownVpn();
4781 } else {
4782 startAlwaysOnVpn(userId);
4783 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004784 }
4785 }
4786
junyulai2454b692018-11-01 17:16:31 +08004787 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004788 @Override
4789 public void onReceive(Context context, Intent intent) {
Varun Anand4fa80e82019-02-06 10:13:38 -08004790 ensureRunningOnConnectivityServiceThread();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004791 final String action = intent.getAction();
4792 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004793 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4794 final Uri packageData = intent.getData();
4795 final String packageName =
4796 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004797 if (userId == UserHandle.USER_NULL) return;
4798
Robin Lee323f29d2016-05-04 16:38:06 +01004799 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004800 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004801 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004802 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004803 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4804 onUserAdded(userId);
4805 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4806 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004807 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4808 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004809 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4810 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004811 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4812 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004813 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004814 final boolean isReplacing = intent.getBooleanExtra(
4815 Intent.EXTRA_REPLACING, false);
4816 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004817 }
4818 }
4819 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004820
Robin Lee95204e02017-01-27 11:59:22 +00004821 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4822 @Override
4823 public void onReceive(Context context, Intent intent) {
4824 // Try creating lockdown tracker, since user present usually means
4825 // unlocked keystore.
4826 updateLockdownVpn();
4827 mContext.unregisterReceiver(this);
4828 }
4829 };
4830
Chalard Jean4133a122018-06-04 13:33:12 +09004831 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4832 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004833
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004834 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4835 // Map from UID to number of NetworkRequests that UID has filed.
4836 @GuardedBy("mUidToNetworkRequestCount")
4837 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4838
Robert Greenwalta67be032014-05-16 15:49:14 -07004839 private static class NetworkFactoryInfo {
4840 public final String name;
4841 public final Messenger messenger;
4842 public final AsyncChannel asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004843 public final int factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004844
Chalard Jean05ab6812018-05-02 21:14:54 +09004845 NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel,
4846 int factorySerialNumber) {
Robert Greenwalta67be032014-05-16 15:49:14 -07004847 this.name = name;
4848 this.messenger = messenger;
4849 this.asyncChannel = asyncChannel;
Chalard Jean05ab6812018-05-02 21:14:54 +09004850 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalta67be032014-05-16 15:49:14 -07004851 }
4852 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004853
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004854 private void ensureNetworkRequestHasType(NetworkRequest request) {
4855 if (request.type == NetworkRequest.Type.NONE) {
4856 throw new IllegalArgumentException(
4857 "All NetworkRequests in ConnectivityService must have a type");
4858 }
4859 }
4860
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004861 /**
4862 * Tracks info about the requester.
4863 * Also used to notice when the calling process dies so we can self-expire
4864 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004865 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004866 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004867 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004868 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004869 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004870 final int mPid;
4871 final int mUid;
4872 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004873
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004874 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004875 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004876 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004877 mPendingIntent = pi;
4878 messenger = null;
4879 mBinder = null;
4880 mPid = getCallingPid();
4881 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004882 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004883 }
4884
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004885 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004886 super();
4887 messenger = m;
4888 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004889 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004890 mBinder = binder;
4891 mPid = getCallingPid();
4892 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004893 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004894 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004895
4896 try {
4897 mBinder.linkToDeath(this, 0);
4898 } catch (RemoteException e) {
4899 binderDied();
4900 }
4901 }
4902
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004903 private void enforceRequestCountLimit() {
4904 synchronized (mUidToNetworkRequestCount) {
4905 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4906 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004907 throw new ServiceSpecificException(
4908 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004909 }
4910 mUidToNetworkRequestCount.put(mUid, networkRequests);
4911 }
4912 }
4913
Robert Greenwalt9258c642014-03-26 16:47:06 -07004914 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004915 if (mBinder != null) {
4916 mBinder.unlinkToDeath(this, 0);
4917 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004918 }
4919
4920 public void binderDied() {
4921 log("ConnectivityService NetworkRequestInfo binderDied(" +
4922 request + ", " + mBinder + ")");
4923 releaseNetworkRequest(request);
4924 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004925
4926 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004927 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004928 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004929 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004930 }
4931
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004932 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4933 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4934 if (badCapability != null) {
4935 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004936 }
4937 }
4938
Chalard Jeanb03a6222018-04-11 21:09:10 +09004939 // This checks that the passed capabilities either do not request a specific SSID, or the
4940 // calling app has permission to do so.
4941 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4942 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004943 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004944 throw new SecurityException("Insufficient permissions to request a specific SSID");
4945 }
4946 }
4947
Erik Kline9d598e12015-07-13 16:37:51 +09004948 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004949 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004950 synchronized (nai) {
4951 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4952 if (nri.request.networkCapabilities.hasSignalStrength() &&
4953 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4954 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4955 }
4956 }
4957 }
Chalard Jean4133a122018-06-04 13:33:12 +09004958 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004959 }
4960
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004961 private void updateSignalStrengthThresholds(
4962 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4963 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004964 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004965 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4966
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004967 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004968 String detail;
4969 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4970 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4971 } else {
4972 detail = reason;
4973 }
4974 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4975 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4976 }
4977
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004978 nai.asyncChannel.sendMessage(
4979 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004980 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004981 }
4982
Etan Cohen859748f2017-04-03 17:42:34 -07004983 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4984 if (nc == null) {
4985 return;
4986 }
4987 NetworkSpecifier ns = nc.getNetworkSpecifier();
4988 if (ns == null) {
4989 return;
4990 }
4991 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4992 ns.assertValidFromUid(Binder.getCallingUid());
4993 }
4994
Robert Greenwalt9258c642014-03-26 16:47:06 -07004995 @Override
4996 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004997 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004998 final NetworkRequest.Type type = (networkCapabilities == null)
4999 ? NetworkRequest.Type.TRACK_DEFAULT
5000 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09005001 // If the requested networkCapabilities is null, take them instead from
5002 // the default network request. This allows callers to keep track of
5003 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005004 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09005005 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09005006 enforceAccessPermission();
5007 } else {
5008 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5009 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09005010 // TODO: this is incorrect. We mark the request as metered or not depending on the state
5011 // of the app when the request is filed, but we never change the request if the app
5012 // changes network state. http://b/29964605
5013 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09005014 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005015 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005016 ensureSufficientPermissionsForRequest(networkCapabilities,
5017 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005018 // Set the UID range for this request to the single UID of the requester, or to an empty
5019 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09005020 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5021 // are no visible methods to set the UIDs, an app could use reflection to try and get
5022 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09005023 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005024
Etan Cohenba07c8c2017-02-05 10:42:27 -08005025 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005026 throw new IllegalArgumentException("Bad timeout specified");
5027 }
Etan Cohen859748f2017-04-03 17:42:34 -07005028 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08005029
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07005030 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005031 nextNetworkRequestId(), type);
5032 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09005033 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005034
5035 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07005036 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005037 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07005038 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005039 }
5040 return networkRequest;
5041 }
5042
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005043 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09005044 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09005045 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005046 } else {
5047 enforceChangePermission();
5048 }
5049 }
5050
fenglub15e72b2015-03-20 11:29:56 -07005051 @Override
fengludb571472015-04-21 17:12:05 -07005052 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07005053 enforceAccessPermission();
5054 NetworkAgentInfo nai = null;
5055 if (network == null) {
5056 return false;
5057 }
5058 synchronized (mNetworkForNetId) {
5059 nai = mNetworkForNetId.get(network.netId);
5060 }
5061 if (nai != null) {
5062 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07005063 synchronized (mBandwidthRequests) {
5064 final int uid = Binder.getCallingUid();
5065 Integer uidReqs = mBandwidthRequests.get(uid);
5066 if (uidReqs == null) {
5067 uidReqs = new Integer(0);
5068 }
5069 mBandwidthRequests.put(uid, ++uidReqs);
5070 }
fenglub15e72b2015-03-20 11:29:56 -07005071 return true;
5072 }
5073 return false;
5074 }
5075
Felipe Lemeee27cab2016-06-20 16:36:29 -07005076 private boolean isSystem(int uid) {
5077 return uid < Process.FIRST_APPLICATION_UID;
5078 }
fenglub15e72b2015-03-20 11:29:56 -07005079
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005080 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07005081 final int uid = Binder.getCallingUid();
5082 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005083 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07005084 return;
5085 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005086 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
5087 // Policy already enforced.
5088 return;
5089 }
5090 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
5091 // If UID is restricted, don't allow them to bring up metered APNs.
5092 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005093 }
5094 }
5095
Robert Greenwalt9258c642014-03-26 16:47:06 -07005096 @Override
5097 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5098 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005099 checkNotNull(operation, "PendingIntent cannot be null.");
5100 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5101 enforceNetworkRequestPermissions(networkCapabilities);
5102 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09005103 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005104 ensureSufficientPermissionsForRequest(networkCapabilities,
5105 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07005106 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005107 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07005108
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005109 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005110 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
5111 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09005112 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005113 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
5114 nri));
5115 return networkRequest;
5116 }
5117
Jeremy Joslin79294842014-12-03 17:15:28 -08005118 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
5119 mHandler.sendMessageDelayed(
5120 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5121 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
5122 }
5123
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005124 @Override
5125 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04005126 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
5128 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005129 }
5130
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005131 // In order to implement the compatibility measure for pre-M apps that call
5132 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
5133 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
5134 // This ensures it has permission to do so.
5135 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
5136 if (nc == null) {
5137 return false;
5138 }
5139 int[] transportTypes = nc.getTransportTypes();
5140 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
5141 return false;
5142 }
5143 try {
5144 mContext.enforceCallingOrSelfPermission(
5145 android.Manifest.permission.ACCESS_WIFI_STATE,
5146 "ConnectivityService");
5147 } catch (SecurityException e) {
5148 return false;
5149 }
5150 return true;
5151 }
5152
Robert Greenwalt9258c642014-03-26 16:47:06 -07005153 @Override
5154 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5155 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09005156 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5157 enforceAccessPermission();
5158 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005159
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005160 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005161 ensureSufficientPermissionsForRequest(networkCapabilities,
5162 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09005163 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09005164 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
5165 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
5166 // onLost and onAvailable callbacks when networks move in and out of the background.
5167 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
5168 // can't request networks.
5169 restrictBackgroundRequestForCaller(nc);
5170 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07005171
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005172 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005173 NetworkRequest.Type.LISTEN);
5174 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005175 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005176
5177 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5178 return networkRequest;
5179 }
5180
5181 @Override
5182 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5183 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04005184 checkNotNull(operation, "PendingIntent cannot be null.");
5185 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
5186 enforceAccessPermission();
5187 }
Etan Cohen859748f2017-04-03 17:42:34 -07005188 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09005189 ensureSufficientPermissionsForRequest(networkCapabilities,
5190 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07005191
Chalard Jeandda156a2018-01-10 21:19:32 +09005192 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09005193 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09005194
5195 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005196 NetworkRequest.Type.LISTEN);
5197 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005198 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04005199
5200 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005201 }
5202
Erik Klineacdd6392016-07-07 16:50:58 +09005203 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07005204 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09005205 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09005206 mHandler.sendMessage(mHandler.obtainMessage(
5207 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005208 }
5209
5210 @Override
Chalard Jean05ab6812018-05-02 21:14:54 +09005211 public int registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07005212 enforceConnectivityInternalPermission();
Chalard Jean05ab6812018-05-02 21:14:54 +09005213 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel(),
5214 NetworkFactory.SerialNumber.nextSerialNumber());
Robert Greenwalta67be032014-05-16 15:49:14 -07005215 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Chalard Jean05ab6812018-05-02 21:14:54 +09005216 return nfi.factorySerialNumber;
Robert Greenwalte049c232014-04-11 15:53:27 -07005217 }
5218
Robert Greenwalta67be032014-05-16 15:49:14 -07005219 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005220 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07005221 mNetworkFactoryInfos.put(nfi.messenger, nfi);
5222 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5223 }
5224
5225 @Override
5226 public void unregisterNetworkFactory(Messenger messenger) {
5227 enforceConnectivityInternalPermission();
5228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5229 }
5230
5231 private void handleUnregisterNetworkFactory(Messenger messenger) {
5232 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5233 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005234 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07005235 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07005236 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005237 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07005238 }
5239
Robert Greenwalt7b816022014-04-18 15:25:25 -07005240 /**
5241 * NetworkAgentInfo supporting a request by requestId.
5242 * These have already been vetted (their Capabilities satisfy the request)
5243 * and the are the highest scored network available.
5244 * the are keyed off the Requests requestId.
5245 */
Hugo Benichicd952782017-09-20 11:20:14 +09005246 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5247 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09005248 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005249
Paul Jensen31a94f42015-02-13 14:18:39 -05005250 // NOTE: Accessed on multiple threads, must be synchronized on itself.
5251 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09005252 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05005253 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
5254 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
5255 // there may not be a strict 1:1 correlation between the two.
5256 @GuardedBy("mNetworkForNetId")
5257 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07005258
Robert Greenwalt7b816022014-04-18 15:25:25 -07005259 // NetworkAgentInfo keyed off its connecting messenger
5260 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05005261 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09005262 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005263
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005264 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09005265 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09005266
Paul Jensen2c311d62014-11-17 12:34:51 -05005267 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005268 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09005269
Erik Klineda4bfa82015-04-30 12:58:40 +09005270 // Request used to optionally keep mobile data active even when higher
5271 // priority networks like Wi-Fi are active.
5272 private final NetworkRequest mDefaultMobileDataRequest;
5273
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07005274 // Request used to optionally keep wifi data active even when higher
5275 // priority networks like ethernet are active.
5276 private final NetworkRequest mDefaultWifiRequest;
5277
Hugo Benichicd952782017-09-20 11:20:14 +09005278 private NetworkAgentInfo getNetworkForRequest(int requestId) {
5279 synchronized (mNetworkForRequestId) {
5280 return mNetworkForRequestId.get(requestId);
5281 }
5282 }
5283
5284 private void clearNetworkForRequest(int requestId) {
5285 synchronized (mNetworkForRequestId) {
5286 mNetworkForRequestId.remove(requestId);
5287 }
5288 }
5289
5290 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
5291 synchronized (mNetworkForRequestId) {
5292 mNetworkForRequestId.put(requestId, nai);
5293 }
5294 }
5295
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005296 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09005297 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005298 }
5299
Varun Anand4fa80e82019-02-06 10:13:38 -08005300 @Nullable
5301 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
5302 return nai != null ? nai.network : null;
5303 }
5304
5305 private void ensureRunningOnConnectivityServiceThread() {
5306 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
5307 throw new IllegalStateException(
5308 "Not running on ConnectivityService thread: "
5309 + Thread.currentThread().getName());
5310 }
5311 }
5312
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005313 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09005314 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07005315 }
5316
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005317 private boolean isDefaultRequest(NetworkRequestInfo nri) {
5318 return nri.request.requestId == mDefaultRequest.requestId;
5319 }
5320
Chalard Jean05ab6812018-05-02 21:14:54 +09005321 // TODO : remove this method. It's a stopgap measure to help sheperding a number of dependent
5322 // changes that would conflict throughout the automerger graph. Having this method temporarily
5323 // helps with the process of going through with all these dependent changes across the entire
5324 // tree.
Paul Jensen31a94f42015-02-13 14:18:39 -05005325 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07005326 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005327 int currentScore, NetworkMisc networkMisc) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005328 return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
5329 currentScore, networkMisc, NetworkFactory.SerialNumber.NONE);
5330 }
5331
5332 /**
5333 * Register a new agent with ConnectivityService to handle a network.
5334 *
5335 * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
5336 * @param networkInfo the initial info associated with this network. It can be updated later :
5337 * see {@link #updateNetworkInfo}.
5338 * @param linkProperties the initial link properties of this network. They can be updated
5339 * later : see {@link #updateLinkProperties}.
5340 * @param networkCapabilities the initial capabilites of this network. They can be updated
5341 * later : see {@link #updateNetworkCapabilities}.
5342 * @param currentScore the initial score of the network. See
5343 * {@link NetworkAgentInfo#getCurrentScore}.
5344 * @param networkMisc metadata about the network. This is never updated.
5345 * @param factorySerialNumber the serial number of the factory owning this NetworkAgent.
5346 */
5347 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5348 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5349 int currentScore, NetworkMisc networkMisc, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005350 enforceConnectivityInternalPermission();
5351
Rubin Xu1bb5c082017-09-05 18:40:49 +01005352 LinkProperties lp = new LinkProperties(linkProperties);
5353 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05005354 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
5355 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09005356 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005357 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09005358 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Chalard Jean05ab6812018-05-02 21:14:54 +09005359 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS,
5360 factorySerialNumber);
Chalard Jean804b8fb2018-01-30 22:41:41 +09005361 // Make sure the network capabilities reflect what the agent info says.
5362 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09005363 final String extraInfo = networkInfo.getExtraInfo();
5364 final String name = TextUtils.isEmpty(extraInfo)
5365 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005366 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005367 final long token = Binder.clearCallingIdentity();
5368 try {
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005369 getNetworkStack().makeNetworkMonitor(
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +09005370 toStableParcelable(nai.network), name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005371 } finally {
5372 Binder.restoreCallingIdentity(token);
5373 }
5374 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
5375 // If the network disconnects or sends any other event before that, messages are deferred by
5376 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
5377 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05005378 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005379 }
5380
Remi NGUYEN VAN5db454c2019-02-14 18:04:20 +09005381 @VisibleForTesting
5382 protected NetworkStackClient getNetworkStack() {
5383 return NetworkStackClient.getInstance();
5384 }
5385
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005386 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
5387 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005388 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005389 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005390 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005391 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005392 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005393 synchronized (this) {
5394 if (mSystemReady) {
5395 try {
5396 networkMonitor.notifySystemReady();
5397 } catch (RemoteException e) {
5398 e.rethrowFromSystemServer();
5399 }
5400 }
5401 }
5402
5403 try {
5404 networkMonitor.start();
5405 } catch (RemoteException e) {
5406 e.rethrowFromSystemServer();
5407 }
Erik Klinee5dac902018-03-04 21:01:01 +09005408 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5409 NetworkInfo networkInfo = nai.networkInfo;
5410 nai.networkInfo = null;
5411 updateNetworkInfo(nai, networkInfo);
5412 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005413 }
5414
lucaslin25a4ec32018-11-28 12:51:55 +08005415 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5416 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005417 int netId = networkAgent.network.netId;
5418
Lorenzo Colittidf595632019-01-08 14:43:37 +09005419 // The NetworkAgentInfo does not know whether clatd is running on its network or not, or
5420 // whether there is a NAT64 prefix. Before we do anything else, make sure its LinkProperties
5421 // are accurate.
5422 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005423
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005424 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005425 updateMtu(newLp, oldLp);
5426 // TODO - figure out what to do for clat
5427// for (LinkProperties lp : newLp.getStackedLinks()) {
5428// updateMtu(lp, null);
5429// }
lucaslin041a1af2018-11-28 19:27:52 +08005430 if (isDefaultNetwork(networkAgent)) {
5431 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5432 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005433
Erik Kline94887872016-04-05 13:30:49 +09005434 updateRoutes(newLp, oldLp, netId);
5435 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005436 // Make sure LinkProperties represents the latest private DNS status.
5437 // This does not need to be done before updateDnses because the
5438 // LinkProperties are not the source of the private DNS configuration.
5439 // updateDnses will fetch the private DNS configuration from DnsManager.
5440 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005441
Paul Jensene0bef712014-12-10 15:12:18 -05005442 if (isDefaultNetwork(networkAgent)) {
5443 handleApplyDefaultProxy(newLp.getHttpProxy());
5444 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005445 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005446 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005447 // TODO - move this check to cover the whole function
5448 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005449 synchronized (networkAgent) {
5450 networkAgent.linkProperties = newLp;
5451 }
Lorenzo Colittid593e292019-02-19 13:21:56 +09005452 // Start or stop DNS64 detection and 464xlat according to network state.
5453 networkAgent.clatd.update();
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005454 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005455 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005456 try {
5457 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5458 } catch (RemoteException e) {
5459 e.rethrowFromSystemServer();
5460 }
lucaslin25a4ec32018-11-28 12:51:55 +08005461 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5462 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005463 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005464
5465 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005466 }
5467
Joel Scherpelz668370b2017-06-08 15:35:21 +09005468 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005469 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005470 // marks on unsupported interfaces is harmless.
5471 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5472 return;
5473 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005474
Joel Scherpelz668370b2017-06-08 15:35:21 +09005475 int mark = mContext.getResources().getInteger(
5476 com.android.internal.R.integer.config_networkWakeupPacketMark);
5477 int mask = mContext.getResources().getInteger(
5478 com.android.internal.R.integer.config_networkWakeupPacketMask);
5479
5480 // Mask/mark of zero will not detect anything interesting.
5481 // Don't install rules unless both values are nonzero.
5482 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005483 return;
5484 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005485
5486 final String prefix = "iface:" + iface;
5487 try {
5488 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005489 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005490 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005491 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005492 }
5493 } catch (Exception e) {
5494 loge("Exception modifying wakeup packet monitoring: " + e);
5495 }
5496
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005497 }
5498
5499 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5500 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005501 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005502 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5503 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005504 for (String iface : interfaceDiff.added) {
5505 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005506 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005507 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005508 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005509 } catch (Exception e) {
5510 loge("Exception adding interface: " + e);
5511 }
5512 }
5513 for (String iface : interfaceDiff.removed) {
5514 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005515 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005516 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005517 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005518 } catch (Exception e) {
5519 loge("Exception removing interface: " + e);
5520 }
5521 }
5522 }
5523
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005524 /**
5525 * Have netd update routes from oldLp to newLp.
5526 * @return true if routes changed between oldLp and newLp
5527 */
5528 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005529 // Compare the route diff to determine which routes should be added and removed.
5530 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5531 oldLp != null ? oldLp.getAllRoutes() : null,
5532 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005533
5534 // add routes before removing old in case it helps with continuous connectivity
5535
Chalard Jean4d660112018-06-04 16:52:49 +09005536 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005537 for (RouteInfo route : routeDiff.added) {
5538 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005539 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005540 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005541 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005542 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005543 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5544 loge("Exception in addRoute for non-gateway: " + e);
5545 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005546 }
5547 }
5548 for (RouteInfo route : routeDiff.added) {
5549 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005550 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005551 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005552 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005553 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005554 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5555 loge("Exception in addRoute for gateway: " + e);
5556 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005557 }
5558 }
5559
5560 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005561 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005562 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005563 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005564 } catch (Exception e) {
5565 loge("Exception in removeRoute: " + e);
5566 }
5567 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005568 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005569 }
Erik Kline41368502015-06-17 13:19:54 +09005570
Erik Kline94887872016-04-05 13:30:49 +09005571 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5572 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5573 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005574 }
Erik Kline94887872016-04-05 13:30:49 +09005575
Erik Kline1742fe12017-12-13 19:40:49 +09005576 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5577 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5578
Erik Klinea24d4592018-01-11 21:07:29 +09005579 if (DBG) {
5580 final Collection<InetAddress> dnses = newLp.getDnsServers();
5581 log("Setting DNS servers for network " + netId + " to " + dnses);
5582 }
Erik Kline94887872016-04-05 13:30:49 +09005583 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005584 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005585 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005586 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005587 }
Erik Kline4edba012017-04-07 15:29:29 +09005588 }
5589
Luke Huang8a462ec2018-08-24 20:33:16 +08005590 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005591 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005592 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005593 }
5594 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005595 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005596 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005597 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005598 }
5599
Paul Jensen3d194ea2015-06-16 14:27:36 -04005600 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005601 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5602 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5603 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005604 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005605 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005606 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005607 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5608 // causing a connect/teardown loop.
5609 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5610 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005611 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005612 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005613 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5614 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005615 // does not cause any request (that is not a listen) currently matching that agent to
5616 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005617 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005618 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005619 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005620 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005621 }
5622
Paul Jensen3d194ea2015-06-16 14:27:36 -04005623 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005624 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005625 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005626 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005627 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005628 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005629 }
Paul Jensene0988542015-06-25 15:30:08 -04005630 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005631 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005632 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005633 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005634 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005635 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005636 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005637 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005638 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005639 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005640 if (nai.isSuspended()) {
5641 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5642 } else {
5643 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5644 }
lucasline252a742019-03-12 13:08:03 +08005645 if (nai.partialConnectivity) {
5646 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5647 } else {
5648 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
5649 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005650
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005651 return newNc;
5652 }
5653
5654 /**
5655 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5656 *
5657 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5658 * capabilities we manage and store in {@code nai}, such as validated status and captive
5659 * portal status)
5660 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5661 * potentially triggers rematches.
5662 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5663 * change.)
5664 *
5665 * @param oldScore score of the network before any of the changes that prompted us
5666 * to call this function.
5667 * @param nai the network having its capabilities updated.
5668 * @param nc the new network capabilities.
5669 */
5670 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5671 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5672
5673 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005674
Luke Huang8a462ec2018-08-24 20:33:16 +08005675 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5676 final int newPermission = getNetworkPermission(newNc);
5677 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005678 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005679 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005680 } catch (RemoteException e) {
5681 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005682 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005683 }
5684
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005685 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005686 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005687 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005688 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005689 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005690
Chalard Jeanf213ca12018-01-16 18:43:05 +09005691 updateUids(nai, prevNc, newNc);
5692
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005693 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005694 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5695 // the change we're processing can't affect any requests, it can only affect the listens
5696 // on this network. We might have been called by rematchNetworkAndRequests when a
5697 // network changed foreground state.
5698 processListenRequests(nai, true);
5699 } else {
5700 // If the requestable capabilities have changed or the score changed, we can't have been
5701 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005702 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005703 try {
5704 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5705 } catch (RemoteException e) {
5706 e.rethrowFromSystemServer();
5707 }
Paul Jensene0988542015-06-25 15:30:08 -04005708 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005709 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005710
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005711 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005712 final boolean oldMetered = prevNc.isMetered();
5713 final boolean newMetered = newNc.isMetered();
5714 final boolean meteredChanged = oldMetered != newMetered;
5715
5716 if (meteredChanged) {
5717 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5718 mRestrictBackground);
5719 }
5720
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005721 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005722 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005723
5724 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005725 if (meteredChanged || roamingChanged) {
5726 notifyIfacesChangedForNetworkStats();
5727 }
5728 }
5729
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005730 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005731 // Tell VPNs about updated capabilities, since they may need to
5732 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005733 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005734 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005735 }
5736
Chalard Jeanf213ca12018-01-16 18:43:05 +09005737 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5738 NetworkCapabilities newNc) {
5739 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5740 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5741 if (null == prevRanges) prevRanges = new ArraySet<>();
5742 if (null == newRanges) newRanges = new ArraySet<>();
5743 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5744
5745 prevRanges.removeAll(newRanges);
5746 newRanges.removeAll(prevRangesCopy);
5747
5748 try {
5749 if (!newRanges.isEmpty()) {
5750 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5751 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005752 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005753 }
5754 if (!prevRanges.isEmpty()) {
5755 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5756 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005757 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005758 }
5759 } catch (Exception e) {
5760 // Never crash!
5761 loge("Exception in updateUids: " + e);
5762 }
5763 }
5764
Hugo Benichief502882017-09-01 01:23:32 +00005765 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colitti94229b32019-02-20 21:34:01 +09005766 ensureRunningOnConnectivityServiceThread();
5767
Erik Kline736353a2018-03-21 07:18:33 -07005768 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005769 // Ignore updates for disconnected networks
5770 return;
5771 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005772 // newLp is already a defensive copy.
5773 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005774 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005775 log("Update of LinkProperties for " + nai.name() +
5776 "; created=" + nai.created +
5777 "; everConnected=" + nai.everConnected);
5778 }
lucaslin25a4ec32018-11-28 12:51:55 +08005779 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005780 }
5781
Paul Jensenc8b9a742014-09-30 15:37:41 -04005782 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005783 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5784 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005785 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005786 if (nr.isListen()) continue;
Chalard Jean05ab6812018-05-02 21:14:54 +09005787 sendUpdatedScoreToFactories(nr, nai);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005788 }
5789 }
5790
Chalard Jean05ab6812018-05-02 21:14:54 +09005791 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, NetworkAgentInfo nai) {
5792 int score = 0;
5793 int serial = 0;
5794 if (nai != null) {
5795 score = nai.getCurrentScore();
5796 serial = nai.factorySerialNumber;
5797 }
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005798 if (VDBG || DDBG){
5799 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5800 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005801 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Chalard Jean05ab6812018-05-02 21:14:54 +09005802 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
5803 serial, networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005804 }
5805 }
5806
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005807 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5808 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005809 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005810 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005811 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5812 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005813 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005814 sendIntent(nri.mPendingIntent, intent);
5815 }
5816 // else not handled
5817 }
5818
5819 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5820 mPendingIntentWakeLock.acquire();
5821 try {
5822 if (DBG) log("Sending " + pendingIntent);
5823 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5824 } catch (PendingIntent.CanceledException e) {
5825 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5826 mPendingIntentWakeLock.release();
5827 releasePendingNetworkRequest(pendingIntent);
5828 }
5829 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5830 }
5831
5832 @Override
5833 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5834 String resultData, Bundle resultExtras) {
5835 if (DBG) log("Finished sending " + pendingIntent);
5836 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005837 // Release with a delay so the receiving client has an opportunity to put in its
5838 // own request.
5839 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005840 }
5841
Chalard Jeanf19db372018-01-26 19:24:40 +09005842 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005843 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005844 if (nri.messenger == null) {
5845 return; // Default request has no msgr
5846 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005847 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005848 // TODO: check if defensive copies of data is needed.
5849 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005850 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005851 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5852 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005853 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005854 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005855 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005856 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5857 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005858 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005859 // For this notification, arg1 contains the blocked status.
5860 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005861 break;
5862 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005863 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005864 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005865 break;
5866 }
5867 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005868 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005869 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005870 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005871 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005872 break;
5873 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005874 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005875 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005876 break;
5877 }
junyulai05986c62018-08-07 19:50:45 +08005878 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005879 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005880 msg.arg1 = arg1;
5881 break;
5882 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005883 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005884 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005885 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005886 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005887 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005888 String notification = ConnectivityManager.getCallbackName(notificationType);
5889 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005890 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005891 nri.messenger.send(msg);
5892 } catch (RemoteException e) {
5893 // may occur naturally in the race of binder death.
5894 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5895 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005896 }
5897
Hugo Benichidba33db2017-03-23 22:40:44 +09005898 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5899 bundle.putParcelable(t.getClass().getSimpleName(), t);
5900 }
5901
Paul Jensenc8b9a742014-09-30 15:37:41 -04005902 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005903 if (nai.numRequestNetworkRequests() != 0) {
5904 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5905 NetworkRequest nr = nai.requestAt(i);
5906 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005907 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005908 loge("Dead network still had at least " + nr);
5909 break;
5910 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005911 }
5912 nai.asyncChannel.disconnect();
5913 }
5914
Robert Greenwalt7b816022014-04-18 15:25:25 -07005915 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5916 if (oldNetwork == null) {
5917 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5918 return;
5919 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005920 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005921
5922 // If we get here it means that the last linger timeout for this network expired. So there
5923 // must be no other active linger timers, and we must stop lingering.
5924 oldNetwork.clearLingerState();
5925
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005926 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005927 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005928 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005929 } else {
5930 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005931 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5932 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005933 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005934 }
5935
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005936 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005937 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005938
Paul Jensen27b02b72014-07-14 12:03:33 -04005939 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005940 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005941 } catch (Exception e) {
5942 loge("Exception setting default network :" + e);
5943 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005944
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005945 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005946 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005947 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005948 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005949 notifyIfacesChangedForNetworkStats();
Varun Anand4fa80e82019-02-06 10:13:38 -08005950 // Fix up the NetworkCapabilities of any VPNs that don't specify underlying networks.
5951 updateAllVpnsCapabilities();
Paul Jensen27b02b72014-07-14 12:03:33 -04005952 }
5953
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005954 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005955 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5956 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5957 NetworkRequest nr = nri.request;
5958 if (!nr.isListen()) continue;
5959 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5960 nai.removeRequest(nri.request.requestId);
5961 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5962 }
5963 }
5964
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005965 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005966 try {
5967 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5968 } catch (RemoteException e) {
5969 e.rethrowFromSystemServer();
5970 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005971 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5972 }
5973
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005974 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5975 NetworkRequest nr = nri.request;
5976 if (!nr.isListen()) continue;
5977 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5978 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005979 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005980 }
5981 }
5982 }
5983
Paul Jensen2161a8e2014-09-11 11:00:39 -04005984 // Handles a network appearing or improving its score.
5985 //
5986 // - Evaluates all current NetworkRequests that can be
5987 // satisfied by newNetwork, and reassigns to newNetwork
5988 // any such requests for which newNetwork is the best.
5989 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005990 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005991 // needed. A network is needed if it is the best network for
5992 // one or more NetworkRequests, or if it is a VPN.
5993 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005994 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005995 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005996 //
5997 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5998 // networks that have no chance (i.e. even if validated)
5999 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006000 //
6001 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
6002 // it does not remove NetworkRequests that other Networks could better satisfy.
6003 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
6004 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
6005 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04006006 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05006007 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05006008 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
6009 // performed to tear down unvalidated networks that have no chance (i.e. even if
6010 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006011 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006012 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01006013 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006014 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07006015 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006016 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006017
6018 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
6019 final int score = newNetwork.getCurrentScore();
6020
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006021 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006022
Paul Jensen2161a8e2014-09-11 11:00:39 -04006023 // Find and migrate to this Network any NetworkRequests for
6024 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09006025 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
6026 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006027 NetworkCapabilities nc = newNetwork.networkCapabilities;
6028 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006029 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006030 // Process requests in the first pass and listens in the second pass. This allows us to
6031 // change a network's capabilities depending on which requests it has. This is only
6032 // correct if the change in capabilities doesn't affect whether the network satisfies
6033 // requests or not, and doesn't affect the network's score.
6034 if (nri.request.isListen()) continue;
6035
Hugo Benichicd952782017-09-20 11:20:14 +09006036 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006037 final boolean satisfies = newNetwork.satisfies(nri.request);
6038 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006039 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07006040 log("Network " + newNetwork.name() + " was already satisfying" +
6041 " request " + nri.request.requestId + ". No change.");
6042 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09006043 keep = true;
6044 continue;
6045 }
6046
6047 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07006048 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006049 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006050 // next check if it's better than any current network we're using for
6051 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006052 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006053 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04006054 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006055 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006056 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006057 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09006058 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07006059 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006060 if (VDBG || DDBG){
6061 log(" accepting network in place of " + currentNetwork.name());
6062 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006063 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006064 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006065 affectedNetworks.add(currentNetwork);
6066 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006067 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07006068 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006069 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09006070 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04006071 if (!newNetwork.addRequest(nri.request)) {
6072 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
6073 }
6074 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006075 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04006076 // Tell NetworkFactories about the new score, so they can stop
6077 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09006078 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07006079 // network. Think about if there is a way to reduce this. Push
6080 // netid->request mapping to each factory?
Chalard Jean05ab6812018-05-02 21:14:54 +09006081 sendUpdatedScoreToFactories(nri.request, newNetwork);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09006082 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006083 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05006084 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09006085 if (currentNetwork != null) {
6086 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
6087 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006088 }
6089 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006090 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04006091 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
6092 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006093 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04006094 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
6095 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
6096 // This means this code doesn't have to handle the case where "currentNetwork" no
6097 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
6098 if (DBG) {
6099 log("Network " + newNetwork.name() + " stopped satisfying" +
6100 " request " + nri.request.requestId);
6101 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006102 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006103 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09006104 clearNetworkForRequest(nri.request.requestId);
Chalard Jean05ab6812018-05-02 21:14:54 +09006105 sendUpdatedScoreToFactories(nri.request, null);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006106 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006107 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
6108 newNetwork.name() +
6109 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04006110 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006111 // TODO: Technically, sending CALLBACK_LOST here is
6112 // incorrect if there is a replacement network currently
6113 // connected that can satisfy nri, which is a request
6114 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04006115 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
6116 // so this code is only incorrect for a network that loses
6117 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006118 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006119 }
6120 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006121 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08006122 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006123 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09006124 makeDefault(newNetwork);
6125 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09006126 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09006127 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09006128 // Have a new default network, release the transition wakelock in
6129 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04006130 }
6131
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006132 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
6133 Slog.wtf(TAG, String.format(
6134 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07006135 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006136 }
6137 if (newNetwork.getCurrentScore() != score) {
6138 Slog.wtf(TAG, String.format(
6139 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08006140 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006141 }
6142
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006143 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006144 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
6145 // If the network went from background to foreground or vice versa, we need to update
6146 // its foreground state. It is safe to do this after rematching the requests because
6147 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
6148 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09006149 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006150 } else {
6151 processListenRequests(newNetwork, false);
6152 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09006153
Paul Jensencf4c2c62015-07-01 14:16:32 -04006154 // do this after the default net is switched, but
6155 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09006156 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04006157
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006158 // Linger any networks that are no longer needed. This should be done after sending the
6159 // available callback for newNetwork.
6160 for (NetworkAgentInfo nai : affectedNetworks) {
6161 updateLingerState(nai, now);
6162 }
6163 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
6164 // does not need to be done in any particular order.
6165 updateLingerState(newNetwork, now);
6166
Paul Jensencf4c2c62015-07-01 14:16:32 -04006167 if (isNewDefault) {
6168 // Maintain the illusion: since the legacy API only
6169 // understands one network at a time, we must pretend
6170 // that the current default network disconnected before
6171 // the new one connected.
6172 if (oldDefaultNetwork != null) {
6173 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
6174 oldDefaultNetwork, true);
6175 }
6176 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
6177 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
6178 notifyLockdownVpn(newNetwork);
6179 }
6180
Robert Greenwalt7b816022014-04-18 15:25:25 -07006181 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006182 // Notify battery stats service about this network, both the normal
6183 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006184 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07006185 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006186 final IBatteryStats bs = BatteryStatsService.getService();
6187 final int type = newNetwork.networkInfo.getType();
6188
6189 final String baseIface = newNetwork.linkProperties.getInterfaceName();
6190 bs.noteNetworkInterfaceType(baseIface, type);
6191 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
6192 final String stackedIface = stacked.getInterfaceName();
6193 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07006194 }
6195 } catch (RemoteException ignored) {
6196 }
6197
Robert Greenwalt152ed372014-12-17 17:19:53 -08006198 // This has to happen after the notifyNetworkCallbacks as that tickles each
6199 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09006200 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08006201 // and will generally do a dns request so they can ensureRouteToHost and if
6202 // they do that before the callbacks happen they'll use the default network.
6203 //
6204 // TODO: Is there still a race here? We send the broadcast
6205 // after sending the callback, but if the app can receive the
6206 // broadcast before the callback, it might still break.
6207 //
6208 // This *does* introduce a race where if the user uses the new api
6209 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
6210 // they may get old info. Reverse this after the old startUsing api is removed.
6211 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006212 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
6213 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09006214 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08006215 // legacy type tracker filters out repeat adds
6216 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
6217 }
6218 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07006219
6220 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
6221 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
6222 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
6223 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
6224 if (newNetwork.isVPN()) {
6225 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
6226 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006227 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006228 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
6229 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09006230 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006231 if (nai.getLingerExpiry() > 0) {
6232 // This network has active linger timers and no requests, but is not
6233 // lingering. Linger it.
6234 //
6235 // One way (the only way?) this can happen if this network is unvalidated
6236 // and became unneeded due to another network improving its score to the
6237 // point where this network will no longer be able to satisfy any requests
6238 // even if it validates.
6239 updateLingerState(nai, now);
6240 } else {
6241 if (DBG) log("Reaping " + nai.name());
6242 teardownUnneededNetwork(nai);
6243 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05006244 }
6245 }
6246 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006247 }
6248
Paul Jensen1c7ba022015-06-16 14:27:36 -04006249 /**
6250 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
6251 * being disconnected.
6252 * @param changed If only one Network's score or capabilities have been modified since the last
6253 * time this function was called, pass this Network in this argument, otherwise pass
6254 * null.
6255 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
6256 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
6257 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
6258 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
6259 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04006260 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04006261 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04006262 // TODO: This may get slow. The "changed" parameter is provided for future optimization
6263 // to avoid the slowness. It is not simply enough to process just "changed", for
6264 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09006265 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04006266
6267 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
6268 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
6269 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006270 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04006271 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006272 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006273 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006274 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
6275 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
6276 // Rematch higher scoring networks first to prevent requests first matching a lower
6277 // scoring network and then a higher scoring network, which could produce multiple
6278 // callbacks and inadvertently unlinger networks.
6279 Arrays.sort(nais);
6280 for (NetworkAgentInfo nai : nais) {
6281 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05006282 // Only reap the last time through the loop. Reaping before all rematching
6283 // is complete could incorrectly teardown a network that hasn't yet been
6284 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04006285 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006286 : ReapUnvalidatedNetworks.REAP,
6287 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006288 }
6289 }
6290 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006291
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006292 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04006293 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09006294 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006295 // For now only update icons for default connection.
6296 // TODO: Update WiFi and cellular icons separately. b/17237507
6297 if (!isDefaultNetwork(nai)) return;
6298
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09006299 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04006300 // Don't repeat publish.
6301 if (newInetCondition == mDefaultInetConditionPublished) return;
6302
6303 mDefaultInetConditionPublished = newInetCondition;
6304 sendInetConditionBroadcast(nai.networkInfo);
6305 }
6306
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006307 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09006308 synchronized (mVpns) {
6309 if (mLockdownTracker != null) {
6310 if (nai != null && nai.isVPN()) {
6311 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
6312 } else {
6313 mLockdownTracker.onNetworkInfoChanged();
6314 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006315 }
6316 }
6317 }
6318
Robert Greenwalt7b816022014-04-18 15:25:25 -07006319 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09006320 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006321 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07006322 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07006323 synchronized (networkAgent) {
6324 oldInfo = networkAgent.networkInfo;
6325 networkAgent.networkInfo = newInfo;
6326 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09006327 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006328
Robert Greenwalt7b816022014-04-18 15:25:25 -07006329 if (DBG) {
6330 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
6331 (oldInfo == null ? "null" : oldInfo.getState()) +
6332 " to " + state);
6333 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006334
Robin Lee585e2482016-05-01 23:00:00 +01006335 if (!networkAgent.created
6336 && (state == NetworkInfo.State.CONNECTED
6337 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006338
6339 // A network that has just connected has zero requests and is thus a foreground network.
6340 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
6341
Robert Greenwalt7b816022014-04-18 15:25:25 -07006342 try {
Paul Jenseneec75412014-08-04 12:21:19 -04006343 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006344 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08006345 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07006346 (networkAgent.networkMisc == null ||
6347 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006348 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08006349 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09006350 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006351 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006352 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09006353 loge("Error creating network " + networkAgent.network.netId + ": "
6354 + e.getMessage());
6355 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07006356 }
Paul Jenseneec75412014-08-04 12:21:19 -04006357 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01006358 }
6359
6360 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
6361 networkAgent.everConnected = true;
6362
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09006363 if (networkAgent.linkProperties == null) {
6364 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
6365 }
6366
Erik Kline736353a2018-03-21 07:18:33 -07006367 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08006368 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
6369 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006370
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006371 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
6372 // command must be sent after updating LinkProperties to maximize chances of
6373 // NetworkMonitor seeing the correct LinkProperties when starting.
6374 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
6375 try {
lucaslin43338992019-03-20 18:21:59 +08006376 if (networkAgent.networkMisc.acceptPartialConnectivity) {
6377 networkAgent.networkMonitor().setAcceptPartialConnectivity();
6378 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006379 networkAgent.networkMonitor().notifyNetworkConnected();
6380 } catch (RemoteException e) {
6381 e.rethrowFromSystemServer();
6382 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09006383 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006384
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006385 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
6386 // be communicated to a particular NetworkAgent depends only on the network's immutable,
6387 // capabilities, so it only needs to be done once on initial connect, not every time the
6388 // network's capabilities change. Note that we do this before rematching the network,
6389 // so we could decide to tear it down immediately afterwards. That's fine though - on
6390 // disconnection NetworkAgents should stop any signal strength monitoring they have been
6391 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09006392 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09006393
Varun Anand4fa80e82019-02-06 10:13:38 -08006394 if (networkAgent.isVPN()) {
6395 updateAllVpnsCapabilities();
6396 }
6397
Paul Jensen2161a8e2014-09-11 11:00:39 -04006398 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006399 final long now = SystemClock.elapsedRealtime();
6400 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09006401
6402 // This has to happen after matching the requests, because callbacks are just requests.
6403 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006404 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07006405 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006406 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09006407 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04006408 }
Chalard Jean392971c2018-05-11 20:19:20 +09006409 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006410 if (networkAgent.isVPN()) {
6411 // As the active or bound network changes for apps, broadcast the default proxy, as
6412 // apps may need to update their proxy data. This is called after disconnecting from
6413 // VPN to make sure we do not broadcast the old proxy data.
6414 // TODO(b/122649188): send the broadcast only to VPN users.
6415 mProxyTracker.sendProxyBroadcast();
6416 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006417 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6418 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006419 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006420 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006421 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006422 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006423 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6424 networkAgent.networkCapabilities);
6425 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6426 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006427 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6428 ConnectivityManager.CALLBACK_SUSPENDED :
6429 ConnectivityManager.CALLBACK_RESUMED));
6430 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006431 }
6432 }
6433
Robert Greenwaltac96c522014-06-03 16:43:57 -07006434 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006435 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006436 if (score < 0) {
6437 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6438 "). Bumping score to min of 0");
6439 score = 0;
6440 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006441
Paul Jensen2161a8e2014-09-11 11:00:39 -04006442 final int oldScore = nai.getCurrentScore();
6443 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006444
Paul Jensen85cf78e2015-06-25 13:25:07 -04006445 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006446
Paul Jensenc8b9a742014-09-30 15:37:41 -04006447 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006448 }
6449
Erik Klinec75d4fa2017-02-15 19:59:17 +09006450 // Notify only this one new request of the current state. Transfer all the
6451 // current state by calling NetworkCapabilities and LinkProperties callbacks
6452 // so that callers can be guaranteed to have as close to atomicity in state
6453 // transfer as can be supported by this current API.
6454 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006455 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006456 if (nri.mPendingIntent != null) {
6457 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6458 // Attempt no subsequent state pushes where intents are involved.
6459 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006460 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006461
junyulai05986c62018-08-07 19:50:45 +08006462 final boolean metered = nai.networkCapabilities.isMetered();
6463 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6464 metered, mRestrictBackground);
6465 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6466 }
6467
6468 /**
6469 * Notify of the blocked state apps with a registered callback matching a given NAI.
6470 *
6471 * Unlike other callbacks, blocked status is different between each individual uid. So for
6472 * any given nai, all requests need to be considered according to the uid who filed it.
6473 *
6474 * @param nai The target NetworkAgentInfo.
6475 * @param oldMetered True if the previous network capabilities is metered.
6476 * @param newRestrictBackground True if data saver is enabled.
6477 */
6478 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6479 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6480
6481 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6482 NetworkRequest nr = nai.requestAt(i);
6483 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6484 final int uidRules = mUidRules.get(nri.mUid);
6485 final boolean oldBlocked, newBlocked;
6486 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6487 // between these two calls.
6488 synchronized (mVpns) {
6489 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6490 oldRestrictBackground);
6491 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6492 newRestrictBackground);
6493 }
6494 if (oldBlocked != newBlocked) {
6495 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6496 encodeBool(newBlocked));
6497 }
6498 }
6499 }
6500
6501 /**
6502 * Notify apps with a given UID of the new blocked state according to new uid rules.
6503 * @param uid The uid for which the rules changed.
6504 * @param newRules The new rules to apply.
6505 */
6506 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6507 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6508 final boolean metered = nai.networkCapabilities.isMetered();
6509 final boolean oldBlocked, newBlocked;
6510 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6511 // rules changed event. And this function actually loop through all connected nai and
6512 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6513 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6514 synchronized (mVpns) {
6515 oldBlocked = isUidNetworkingWithVpnBlocked(
6516 uid, mUidRules.get(uid), metered, mRestrictBackground);
6517 newBlocked = isUidNetworkingWithVpnBlocked(
6518 uid, newRules, metered, mRestrictBackground);
6519 }
6520 if (oldBlocked == newBlocked) {
6521 return;
6522 }
6523 final int arg = encodeBool(newBlocked);
6524 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6525 NetworkRequest nr = nai.requestAt(i);
6526 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6527 if (nri != null && nri.mUid == uid) {
6528 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6529 }
6530 }
6531 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006532 }
6533
Robert Greenwalt8d482522015-06-24 13:23:42 -07006534 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006535 // The NetworkInfo we actually send out has no bearing on the real
6536 // state of affairs. For example, if the default connection is mobile,
6537 // and a request for HIPRI has just gone away, we need to pretend that
6538 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6539 // the state to DISCONNECTED, even though the network is of type MOBILE
6540 // and is still connected.
6541 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6542 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006543 if (state != DetailedState.DISCONNECTED) {
6544 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006545 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006546 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006547 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006548 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6549 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6550 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6551 if (info.isFailover()) {
6552 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6553 nai.networkInfo.setFailover(false);
6554 }
6555 if (info.getReason() != null) {
6556 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6557 }
6558 if (info.getExtraInfo() != null) {
6559 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6560 }
6561 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006562 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006563 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006564 if (newDefaultAgent != null) {
6565 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6566 newDefaultAgent.networkInfo);
6567 } else {
6568 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6569 }
6570 }
6571 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6572 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006573 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006574 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006575 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006576 }
6577 }
6578 }
6579
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006580 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006581 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006582 String notification = ConnectivityManager.getCallbackName(notifyType);
6583 log("notifyType " + notification + " for " + networkAgent.name());
6584 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006585 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6586 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006587 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6588 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006589 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6590 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006591 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006592 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006593 } else {
6594 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6595 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006596 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006597 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006598
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006599 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6600 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6601 }
6602
Jeff Sharkey69736342014-12-08 14:50:12 -08006603 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006604 * Returns the list of all interfaces that could be used by network traffic that does not
6605 * explicitly specify a network. This includes the default network, but also all VPNs that are
6606 * currently connected.
6607 *
6608 * Must be called on the handler thread.
6609 */
6610 private Network[] getDefaultNetworks() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006611 ensureRunningOnConnectivityServiceThread();
Lorenzo Colittic78da292018-01-19 00:50:48 +09006612 ArrayList<Network> defaultNetworks = new ArrayList<>();
6613 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6614 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6615 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6616 defaultNetworks.add(nai.network);
6617 }
6618 }
6619 return defaultNetworks.toArray(new Network[0]);
6620 }
6621
6622 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006623 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6624 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006625 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006626 private void notifyIfacesChangedForNetworkStats() {
Varun Anandd33cbc62019-02-07 14:13:13 -08006627 ensureRunningOnConnectivityServiceThread();
6628 String activeIface = null;
6629 LinkProperties activeLinkProperties = getActiveLinkProperties();
6630 if (activeLinkProperties != null) {
6631 activeIface = activeLinkProperties.getInterfaceName();
6632 }
Jeff Sharkey69736342014-12-08 14:50:12 -08006633 try {
Varun Anandd33cbc62019-02-07 14:13:13 -08006634 mStatsService.forceUpdateIfaces(
6635 getDefaultNetworks(), getAllVpnInfo(), getAllNetworkState(), activeIface);
Jeff Sharkey69736342014-12-08 14:50:12 -08006636 } catch (Exception ignored) {
6637 }
6638 }
6639
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006640 @Override
6641 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006642 int user = UserHandle.getUserId(Binder.getCallingUid());
6643 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006644 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006645 return mVpns.get(user).addAddress(address, prefixLength);
6646 }
6647 }
6648
6649 @Override
6650 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006651 int user = UserHandle.getUserId(Binder.getCallingUid());
6652 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006653 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006654 return mVpns.get(user).removeAddress(address, prefixLength);
6655 }
6656 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006657
6658 @Override
6659 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006660 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006661 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006662 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006663 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006664 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006665 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006666 if (success) {
Varun Anand4fa80e82019-02-06 10:13:38 -08006667 mHandler.post(() -> {
6668 // Update VPN's capabilities based on updated underlying network set.
6669 updateAllVpnsCapabilities();
6670 notifyIfacesChangedForNetworkStats();
6671 });
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006672 }
6673 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006674 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006675
6676 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006677 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006678 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006679 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006680 }
6681
6682 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006683 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
6684 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
6685 enforceKeepalivePermission();
6686 mKeepaliveTracker.startNattKeepalive(
6687 getNetworkAgentInfoForNetwork(network),
6688 intervalSeconds, messenger, binder,
junyulai06835112019-01-03 18:50:15 +08006689 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006690 }
6691
6692 @Override
junyulai215b8772019-01-15 11:32:44 +08006693 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
6694 int intervalSeconds, Messenger messenger, IBinder binder, String srcAddr,
6695 String dstAddr) {
6696 enforceKeepalivePermission();
6697 mKeepaliveTracker.startNattKeepalive(
6698 getNetworkAgentInfoForNetwork(network), fd, resourceId,
6699 intervalSeconds, messenger, binder,
6700 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6701 }
6702
6703 @Override
junyulai352dc2f2019-01-08 20:04:33 +08006704 public void startTcpKeepalive(Network network, FileDescriptor fd, int intervalSeconds,
6705 Messenger messenger, IBinder binder) {
6706 enforceKeepalivePermission();
6707 mKeepaliveTracker.startTcpKeepalive(
6708 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, messenger, binder);
6709 }
6710
6711 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006712 public void stopKeepalive(Network network, int slot) {
6713 mHandler.sendMessage(mHandler.obtainMessage(
junyulai06835112019-01-03 18:50:15 +08006714 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006715 }
6716
6717 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006718 public void factoryReset() {
6719 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006720
6721 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6722 return;
6723 }
6724
Robin Lee3b3dd942015-05-12 18:14:58 +01006725 final int userId = UserHandle.getCallingUserId();
6726
Stuart Scottf1fb3972015-04-02 18:00:02 -07006727 // Turn airplane mode off
6728 setAirplaneMode(false);
6729
Stuart Scotte3e314d2015-04-20 14:07:45 -07006730 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6731 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006732 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006733 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006734 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006735 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006736 }
6737
Stuart Scotte3e314d2015-04-20 14:07:45 -07006738 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006739 // Remove always-on package
6740 synchronized (mVpns) {
6741 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6742 if (alwaysOnPackage != null) {
Pavel Grafova462bcb2019-01-25 08:50:06 +00006743 setAlwaysOnVpnPackage(userId, null, false, null);
Victor Changb04a5ea2016-05-30 20:36:30 +01006744 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6745 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006746
Hugo Benichi69744342017-11-27 10:57:16 +09006747 // Turn Always-on VPN off
6748 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6749 final long ident = Binder.clearCallingIdentity();
6750 try {
6751 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6752 mLockdownEnabled = false;
6753 setLockdownTracker(null);
6754 } finally {
6755 Binder.restoreCallingIdentity(ident);
6756 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006757 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006758
Hugo Benichi69744342017-11-27 10:57:16 +09006759 // Turn VPN off
6760 VpnConfig vpnConfig = getVpnConfig(userId);
6761 if (vpnConfig != null) {
6762 if (vpnConfig.legacy) {
6763 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6764 } else {
6765 // Prevent this app (packagename = vpnConfig.user) from initiating
6766 // VPN connections in the future without user intervention.
6767 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006768
Hugo Benichi69744342017-11-27 10:57:16 +09006769 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6770 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006771 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006772 }
6773 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006774
6775 Settings.Global.putString(mContext.getContentResolver(),
6776 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006777 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006778
Ricky Wai44dcbde2018-01-23 04:09:45 +00006779 @Override
6780 public byte[] getNetworkWatchlistConfigHash() {
6781 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6782 if (nwm == null) {
6783 loge("Unable to get NetworkWatchlistManager");
6784 return null;
6785 }
6786 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6787 return nwm.getWatchlistConfigHash();
6788 }
6789
Paul Jensencf4c2c62015-07-01 14:16:32 -04006790 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006791 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6792 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006793 }
6794
6795 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006796 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6797 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6798 }
6799
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006800 @VisibleForTesting
6801 public boolean hasService(String name) {
6802 return ServiceManager.checkService(name) != null;
6803 }
6804
Hugo Benichi64901e52017-10-19 14:42:40 +09006805 @VisibleForTesting
6806 protected IpConnectivityMetrics.Logger metricsLogger() {
6807 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6808 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006809 }
6810
6811 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006812 int[] transports = nai.networkCapabilities.getTransportTypes();
6813 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006814 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006815
6816 private static boolean toBool(int encodedBoolean) {
6817 return encodedBoolean != 0; // Only 0 means false.
6818 }
6819
6820 private static int encodeBool(boolean b) {
6821 return b ? 1 : 0;
6822 }
mswest46386886f2018-03-12 10:34:34 -07006823
6824 @Override
6825 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6826 FileDescriptor err, String[] args, ShellCallback callback,
6827 ResultReceiver resultReceiver) {
6828 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6829 }
6830
6831 private class ShellCmd extends ShellCommand {
6832
6833 @Override
6834 public int onCommand(String cmd) {
6835 if (cmd == null) {
6836 return handleDefaultCommands(cmd);
6837 }
6838 final PrintWriter pw = getOutPrintWriter();
6839 try {
6840 switch (cmd) {
6841 case "airplane-mode":
6842 final String action = getNextArg();
6843 if ("enable".equals(action)) {
6844 setAirplaneMode(true);
6845 return 0;
6846 } else if ("disable".equals(action)) {
6847 setAirplaneMode(false);
6848 return 0;
6849 } else if (action == null) {
6850 final ContentResolver cr = mContext.getContentResolver();
6851 final int enabled = Settings.Global.getInt(cr,
6852 Settings.Global.AIRPLANE_MODE_ON);
6853 pw.println(enabled == 0 ? "disabled" : "enabled");
6854 return 0;
6855 } else {
6856 onHelp();
6857 return -1;
6858 }
6859 default:
6860 return handleDefaultCommands(cmd);
6861 }
6862 } catch (Exception e) {
6863 pw.println(e);
6864 }
6865 return -1;
6866 }
6867
6868 @Override
6869 public void onHelp() {
6870 PrintWriter pw = getOutPrintWriter();
6871 pw.println("Connectivity service commands:");
6872 pw.println(" help");
6873 pw.println(" Print this help text.");
6874 pw.println(" airplane-mode [enable|disable]");
6875 pw.println(" Turn airplane mode on or off.");
6876 pw.println(" airplane-mode");
6877 pw.println(" Get airplane mode.");
6878 }
6879 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006880
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006881 @GuardedBy("mVpns")
6882 private Vpn getVpnIfOwner() {
6883 final int uid = Binder.getCallingUid();
6884 final int user = UserHandle.getUserId(uid);
6885
6886 final Vpn vpn = mVpns.get(user);
6887 if (vpn == null) {
6888 return null;
6889 } else {
6890 final VpnInfo info = vpn.getVpnInfo();
6891 return (info == null || info.ownerUid != uid) ? null : vpn;
6892 }
6893 }
6894
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006895 /**
6896 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6897 * for testing.
6898 */
6899 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6900 if (checkNetworkStackPermission()) {
6901 return null;
6902 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006903 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006904 Vpn vpn = getVpnIfOwner();
6905 if (vpn != null) {
6906 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006907 }
6908 }
6909 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6910 + "permission");
6911 }
6912
6913 /**
6914 * @param connectionInfo the connection to resolve.
6915 * @return {@code uid} if the connection is found and the app has permission to observe it
6916 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6917 * connection is not found.
6918 */
6919 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6920 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6921 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6922 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6923 }
6924
6925 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6926 connectionInfo.local, connectionInfo.remote);
6927
6928 /* Filter out Uids not associated with the VPN. */
6929 if (vpn != null && !vpn.appliesToUid(uid)) {
6930 return INVALID_UID;
6931 }
6932
6933 return uid;
6934 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006935
6936 @Override
6937 public boolean isCallerCurrentAlwaysOnVpnApp() {
6938 synchronized (mVpns) {
6939 Vpn vpn = getVpnIfOwner();
6940 return vpn != null && vpn.getAlwaysOn();
6941 }
6942 }
6943
6944 @Override
6945 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6946 synchronized (mVpns) {
6947 Vpn vpn = getVpnIfOwner();
6948 return vpn != null && vpn.getLockdown();
6949 }
6950 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006951}