blob: bc9f9e3f5a4156855b881c88cfee0cf088246262 [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;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090028import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID;
Paul Jensen3d194ea2015-06-16 14:27:36 -040029import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090031import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
33import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090037import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060038import static android.net.NetworkCapabilities.TRANSPORT_VPN;
junyulai05986c62018-08-07 19:50:45 +080039import static android.net.NetworkPolicyManager.RULE_NONE;
40import static android.net.NetworkPolicyManager.uidRulesToString;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090041import static android.net.NetworkStack.NETWORKSTACK_PACKAGE_NAME;
42import static android.net.shared.NetworkMonitorUtils.isValidationRequired;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070043import static android.os.Process.INVALID_UID;
44import static android.system.OsConstants.IPPROTO_TCP;
45import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060046
Hugo Benichia0385682017-03-22 17:07:57 +090047import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060048
Wenchao Tongf5ea3402015-03-04 13:26:38 -080049import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080050import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090051import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070052import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070053import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.ContentResolver;
55import android.content.Context;
56import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070057import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070058import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070059import android.database.ContentObserver;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -070060import android.net.ConnectionInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090062import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.IConnectivityManager;
dalyk7301aa42018-03-05 12:42:22 -050064import android.net.IIpConnectivityMetrics;
Luke Huang674660f2018-09-27 19:33:11 +080065import android.net.INetd;
dalyk7301aa42018-03-05 12:42:22 -050066import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070067import android.net.INetworkManagementEventObserver;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090068import android.net.INetworkMonitor;
69import android.net.INetworkMonitorCallbacks;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070070import android.net.INetworkPolicyListener;
71import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070072import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080073import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070074import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010075import android.net.MatchAllNetworkSpecifier;
junyulai215b8772019-01-15 11:32:44 +080076import android.net.NattSocketKeepalive;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070077import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070078import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070079import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070080import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070082import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070083import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090084import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070085import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070086import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070087import android.net.NetworkSpecifier;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090088import android.net.NetworkStack;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070089import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070090import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000091import android.net.NetworkWatchlistManager;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090092import android.net.PrivateDnsConfigParcel;
Jason Monk207900c2014-04-25 15:00:09 -040093import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070094import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040095import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040096import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060097import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090098import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090099import android.net.metrics.NetworkEvent;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -0700100import android.net.netlink.InetDiagMessage;
lucaslind2e045e02019-01-24 15:55:30 +0800101import android.net.shared.NetdService;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900102import android.net.shared.NetworkMonitorUtils;
103import android.net.shared.PrivateDnsConfig;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900104import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -0800106import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700107import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -0700109import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700110import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -0700111import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.Looper;
113import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -0700114import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700115import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +0900116import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700117import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700118import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800120import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900121import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900122import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700123import android.os.ShellCallback;
124import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900125import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700126import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400127import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700129import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700130import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700131import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700132import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900133import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700134import android.util.LocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600135import android.util.Log;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900136import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800137import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700138import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500139import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700140import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700141import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
Wink Savilleab9321d2013-06-29 21:10:57 -0700143import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400144import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400145import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700146import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700147import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700148import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800149import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700150import com.android.internal.net.VpnProfile;
Erik Kline3f8306b2018-05-01 16:51:44 +0900151import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700152import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600153import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700154import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900155import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900156import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700157import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700158import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400159import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900160import com.android.server.connectivity.DnsManager;
dalyk7301aa42018-03-05 12:42:22 -0500161import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900162import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900163import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100164import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700165import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900166import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700167import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600168import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900169import com.android.server.connectivity.NetworkNotificationManager;
170import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700171import com.android.server.connectivity.PermissionMonitor;
Chalard Jean52c2aa72018-06-07 16:44:04 +0900172import com.android.server.connectivity.ProxyTracker;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800173import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700174import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100175import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500176import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700177import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700178import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900179import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700180import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600181
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700182import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700183
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700184import org.xmlpull.v1.XmlPullParser;
185import org.xmlpull.v1.XmlPullParserException;
186
187import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700189import java.io.FileNotFoundException;
190import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700191import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700193import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700194import java.net.InetAddress;
195import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700196import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700197import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700198import java.util.Collection;
Hugo Benichia2a917c2018-09-03 08:19:02 +0900199import java.util.Comparator;
junyulai05986c62018-08-07 19:50:45 +0800200import java.util.ConcurrentModificationException;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700201import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700202import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700203import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700204import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700205import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900206import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600207import java.util.SortedSet;
208import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
210/**
211 * @hide
212 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800213public class ConnectivityService extends IConnectivityManager.Stub
214 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900215 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Chalard Jean4133a122018-06-04 13:33:12 +0900217 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900218 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900219 private static final String TETHERING_ARG = "tethering";
Hugo Benichi14683812018-09-03 08:32:56 +0900220 private static final String NETWORK_ARG = "networks";
221 private static final String REQUEST_ARG = "requests";
Erik Kline7747fd42017-05-12 16:52:48 +0900222
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900223 private static final boolean DBG = true;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +0900224 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
225 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900227 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700228
Jeff Sharkey899223b2012-08-04 15:24:58 -0700229 // TODO: create better separation between radio types and network types
230
Robert Greenwalt42acef32009-08-12 16:08:25 -0700231 // how long to wait before switching back to a radio's default network
232 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
233 // system property that can override the above value
234 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
235 "android.telephony.apn-restore";
236
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900237 // How long to wait before putting up a "This network doesn't have an Internet connection,
238 // connect anyway?" dialog after the user selects a network that doesn't validate.
239 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
240
lucaslind2e045e02019-01-24 15:55:30 +0800241 // How long to dismiss network notification.
242 private static final int TIMEOUT_NOTIFICATION_DELAY_MS = 20 * 1000;
243
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900244 // Default to 30s linger time-out. Modifiable only for testing.
245 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
246 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
247 @VisibleForTesting
248 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
249
Jeremy Joslin79294842014-12-03 17:15:28 -0800250 // How long to delay to removal of a pending intent based request.
251 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
252 private final int mReleasePendingIntentDelayMs;
253
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900254 private MockableSystemProperties mSystemProperties;
255
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800256 private Tethering mTethering;
257
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700258 private final PermissionMonitor mPermissionMonitor;
259
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700260 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700261
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900262 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700263 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900264 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700265
Hugo Benichi69744342017-11-27 10:57:16 +0900266 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
267 // a direct call to LockdownVpnTracker.isEnabled().
268 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700269 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900270 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700271 private LockdownVpnTracker mLockdownTracker;
272
junyulai05986c62018-08-07 19:50:45 +0800273 /**
274 * Stale copy of uid rules provided by NPMS. As long as they are accessed only in internal
275 * handler thread, they don't need a lock.
276 */
277 private SparseIntArray mUidRules = new SparseIntArray();
278 /** Flag indicating if background data is restricted. */
279 private boolean mRestrictBackground;
280
Erik Klineda4bfa82015-04-30 12:58:40 +0900281 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700282 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700283 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284
Luke Huang4e25ec62018-09-27 16:58:23 +0800285 private INetworkManagementService mNMS;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -0800286 @VisibleForTesting
287 protected INetd mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800288 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700289 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900290 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700291
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700292 private String mCurrentTcpBufferSizes;
293
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900294 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900295 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
296 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900297
Paul Jensenb10e37f2014-11-25 12:33:08 -0500298 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400299 // Tear down networks that have no chance (e.g. even if validated) of becoming
300 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500301 // all networks have been rematched against all NetworkRequests.
302 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400303 // Don't reap networks. This should be passed when some networks have not yet been
304 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500305 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900306 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500307
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900308 private enum UnneededFor {
309 LINGER, // Determine whether this network is unneeded and should be lingered.
310 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
311 }
312
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700313 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700314 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700315 * from one net to another. Clear happens when we get a new
316 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
317 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700318 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700319 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700320
Robert Greenwalt434203a2010-10-11 16:00:27 -0700321 /**
322 * used internally to reload global proxy settings
323 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700324 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700325
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700326 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400327 * PAC manager has received new port.
328 */
329 private static final int EVENT_PROXY_HAS_CHANGED = 16;
330
Robert Greenwalte049c232014-04-11 15:53:27 -0700331 /**
332 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700333 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700334 */
335 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
336
Robert Greenwalt7b816022014-04-18 15:25:25 -0700337 /**
338 * used internally when registering NetworkAgents
339 * obj = Messenger
340 */
341 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
342
Robert Greenwalt9258c642014-03-26 16:47:06 -0700343 /**
344 * used to add a network request
345 * includes a NetworkRequestInfo
346 */
347 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
348
349 /**
350 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900351 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700352 * cancel it.
353 * includes a NetworkRequestInfo
354 */
355 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
356
357 /**
358 * used to add a network listener - no request
359 * includes a NetworkRequestInfo
360 */
361 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
362
363 /**
364 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400365 * arg1 = UID of caller
366 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700367 */
368 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
369
Robert Greenwalta67be032014-05-16 15:49:14 -0700370 /**
371 * used internally when registering NetworkFactories
372 * obj = Messenger
373 */
374 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
375
Robert Greenwalt27711812014-06-25 16:45:57 -0700376 /**
377 * used internally to expire a wakelock when transitioning
378 * from one net to another. Expire happens when we fail to find
379 * a new network (typically after 1 minute) -
380 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
381 * a replacement network.
382 */
383 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
384
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700385 /**
386 * Used internally to indicate the system is ready.
387 */
388 private static final int EVENT_SYSTEM_READY = 25;
389
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800390 /**
391 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400392 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800393 */
394 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
395
396 /**
397 * used to remove a pending intent and its associated network request.
398 * arg1 = UID of caller
399 * obj = PendingIntent
400 */
401 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
402
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900403 /**
404 * used to specify whether a network should be used even if unvalidated.
405 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
406 * arg2 = whether to remember this choice in the future (1 or 0)
407 * obj = network
408 */
409 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
410
411 /**
412 * used to ask the user to confirm a connection to an unvalidated network.
413 * obj = network
414 */
415 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700416
Erik Klineda4bfa82015-04-30 12:58:40 +0900417 /**
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700418 * used internally to (re)configure always-on networks.
Erik Klineda4bfa82015-04-30 12:58:40 +0900419 */
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700420 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Klineda4bfa82015-04-30 12:58:40 +0900421
Paul Jensen694f2b82015-06-17 14:15:39 -0400422 /**
423 * used to add a network listener with a pending intent
424 * obj = NetworkRequestInfo
425 */
426 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
427
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900428 /**
429 * used to specify whether a network should not be penalized when it becomes unvalidated.
430 */
431 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
432
433 /**
434 * used to trigger revalidation of a network.
435 */
436 private static final int EVENT_REVALIDATE_NETWORK = 36;
437
Erik Klinea24d4592018-01-11 21:07:29 +0900438 // Handle changes in Private DNS settings.
439 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
440
dalyk7301aa42018-03-05 12:42:22 -0500441 // Handle private DNS validation status updates.
442 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
443
junyulai05986c62018-08-07 19:50:45 +0800444 /**
445 * Used to handle onUidRulesChanged event from NetworkPolicyManagerService.
446 */
447 private static final int EVENT_UID_RULES_CHANGED = 39;
448
449 /**
450 * Used to handle onRestrictBackgroundChanged event from NetworkPolicyManagerService.
451 */
452 private static final int EVENT_DATA_SAVER_CHANGED = 40;
453
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900454 /**
455 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
456 * been tested.
457 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
458 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
459 * arg2 = NetID.
460 */
461 public static final int EVENT_NETWORK_TESTED = 41;
462
463 /**
464 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
465 * config was resolved.
466 * obj = PrivateDnsConfig
467 * arg2 = netid
468 */
469 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
470
471 /**
472 * Request ConnectivityService display provisioning notification.
473 * arg1 = Whether to make the notification visible.
474 * arg2 = NetID.
475 * obj = Intent to be launched when notification selected by user, null if !arg1.
476 */
477 public static final int EVENT_PROVISIONING_NOTIFICATION = 43;
478
479 /**
lucaslind2e045e02019-01-24 15:55:30 +0800480 * This event can handle dismissing notification by given network id.
481 */
482 public static final int EVENT_TIMEOUT_NOTIFICATION = 44;
483
484 /**
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900485 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
486 * should be shown.
487 */
488 public static final int PROVISIONING_NOTIFICATION_SHOW = 1;
489
490 /**
491 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
492 * should be hidden.
493 */
494 public static final int PROVISIONING_NOTIFICATION_HIDE = 0;
495
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900496 private static String eventName(int what) {
497 return sMagicDecoderRing.get(what, Integer.toString(what));
498 }
499
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900500 /** Handler thread used for both of the handlers below. */
501 @VisibleForTesting
502 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700503 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700504 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700505 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700506 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900507 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700508
Mike Lockwood0f79b542009-08-14 14:18:49 -0400509 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800510 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400511
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700512 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700513 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800514 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700515
Chalard Jean52c2aa72018-06-07 16:44:04 +0900516 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
517 // the world when it changes.
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000518 @VisibleForTesting
519 protected final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400520
Erik Klineda4bfa82015-04-30 12:58:40 +0900521 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700522
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400523 private UserManager mUserManager;
524
Chalard Jean4133a122018-06-04 13:33:12 +0900525 private NetworkConfig[] mNetConfigs;
526 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700527
Robert Greenwalt50393202011-06-21 17:26:14 -0700528 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900529 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700530
Chalard Jean4133a122018-06-04 13:33:12 +0900531 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400532
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900533 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900534 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900535 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900536
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700537 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800538 private static final int MIN_NET_ID = 100; // some reserved marks
539 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700540 private int mNextNetId = MIN_NET_ID;
541
Robert Greenwalt34524f02014-05-18 16:22:10 -0700542 // sequence number of NetworkRequests
543 private int mNextNetworkRequestId = 1;
544
Erik Kline7523eb32015-07-09 18:24:03 +0900545 // NetworkRequest activity String log entries.
546 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
547 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
548
Hugo Benichic2ae2872016-07-11 11:05:12 +0900549 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900550 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900551 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
552
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900553 private static final int MAX_WAKELOCK_LOGS = 20;
554 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900555 private int mTotalWakelockAcquisitions = 0;
556 private int mTotalWakelockReleases = 0;
557 private long mTotalWakelockDurationMs = 0;
558 private long mMaxWakelockDurationMs = 0;
559 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900560
Hugo Benichif9fdf872016-07-28 17:53:06 +0900561 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900562
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700563 @GuardedBy("mBandwidthRequests")
564 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
565
Erik Kline065ab6e2016-10-02 18:02:14 +0900566 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900567 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900568
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900569 @VisibleForTesting
570 final MultipathPolicyTracker mMultipathPolicyTracker;
571
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 /**
573 * Implements support for the legacy "one network per network type" model.
574 *
575 * We used to have a static array of NetworkStateTrackers, one for each
576 * network type, but that doesn't work any more now that we can have,
577 * for example, more that one wifi network. This class stores all the
578 * NetworkAgentInfo objects that support a given type, but the legacy
579 * API will only see the first one.
580 *
581 * It serves two main purposes:
582 *
583 * 1. Provide information about "the network for a given type" (since this
584 * API only supports one).
585 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
586 * the first network for a given type changes, or if the default network
587 * changes.
588 */
589 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900590
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900591 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900593
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 /**
595 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
596 * Each list holds references to all NetworkAgentInfos that are used to
597 * satisfy requests for that network type.
598 *
599 * This array is built out at startup such that an unsupported network
600 * doesn't get an ArrayList instance, making this a tristate:
601 * unsupported, supported but not active and active.
602 *
603 * The actual lists are populated when we scan the network types that
604 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900605 *
606 * Threading model:
607 * - addSupportedType() is only called in the constructor
608 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
609 * They are therefore not thread-safe with respect to each other.
610 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
611 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
612 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700613 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700615
616 public LegacyTypeTracker() {
617 mTypeLists = (ArrayList<NetworkAgentInfo>[])
618 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
619 }
620
621 public void addSupportedType(int type) {
622 if (mTypeLists[type] != null) {
623 throw new IllegalStateException(
624 "legacy list for type " + type + "already initialized");
625 }
Chalard Jean4133a122018-06-04 13:33:12 +0900626 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700627 }
628
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 public boolean isTypeSupported(int type) {
630 return isNetworkTypeValid(type) && mTypeLists[type] != null;
631 }
632
633 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900634 synchronized (mTypeLists) {
635 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
636 return mTypeLists[type].get(0);
637 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700638 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900639 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700640 }
641
Robert Greenwalt8d482522015-06-24 13:23:42 -0700642 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900643 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900644 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900646 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900647 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900648 }
649 }
650
651 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700652 public void add(int type, NetworkAgentInfo nai) {
653 if (!isTypeSupported(type)) {
654 return; // Invalid network type.
655 }
656 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
657
658 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
659 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700660 return;
661 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900662 synchronized (mTypeLists) {
663 list.add(nai);
664 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900665
666 // 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 +0900667 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900668 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700669 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
670 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700671 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700672 }
673
Lorenzo Colittia793a672014-07-31 23:20:17 +0900674 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900675 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900676 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
677 if (list == null || list.isEmpty()) {
678 return;
679 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900680 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900681
Hugo Benichi78caa2582016-06-21 09:48:07 +0900682 synchronized (mTypeLists) {
683 if (!list.remove(nai)) {
684 return;
685 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900686 }
687
Robert Greenwalt8d482522015-06-24 13:23:42 -0700688 final DetailedState state = DetailedState.DISCONNECTED;
689
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900690 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700691 maybeLogBroadcast(nai, state, type, wasDefault);
692 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900693 }
694
695 if (!list.isEmpty() && wasFirstNetwork) {
696 if (DBG) log("Other network available for type " + type +
697 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900698 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700699 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
700 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900701 }
702 }
703
704 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900705 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
706 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700707 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900708 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700709 }
710 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700711
Robert Greenwalt8d482522015-06-24 13:23:42 -0700712 // send out another legacy broadcast - currently only used for suspend/unsuspend
713 // toggle
714 public void update(NetworkAgentInfo nai) {
715 final boolean isDefault = isDefaultNetwork(nai);
716 final DetailedState state = nai.networkInfo.getDetailedState();
717 for (int type = 0; type < mTypeLists.length; type++) {
718 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700719 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900720 final boolean isFirst = contains && (nai == list.get(0));
721 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700722 maybeLogBroadcast(nai, state, type, isDefault);
723 sendLegacyNetworkBroadcast(nai, state, type);
724 }
725 }
726 }
727
Lorenzo Colittia793a672014-07-31 23:20:17 +0900728 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900729 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900730 String state = (nai.networkInfo != null) ?
731 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
732 "???/???";
733 return name + " " + state;
734 }
735
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700736 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900737 pw.println("mLegacyTypeTracker:");
738 pw.increaseIndent();
739 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700740 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900741 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700742 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900743 pw.println();
744 pw.println("Current state:");
745 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900746 synchronized (mTypeLists) {
747 for (int type = 0; type < mTypeLists.length; type++) {
748 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
749 for (NetworkAgentInfo nai : mTypeLists[type]) {
750 pw.println(type + " " + naiToString(nai));
751 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900752 }
753 }
754 pw.decreaseIndent();
755 pw.decreaseIndent();
756 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700757 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700758 }
759 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
760
Vishnu Nair5c010902017-10-26 10:08:50 -0700761 /**
762 * Helper class which parses out priority arguments and dumps sections according to their
763 * priority. If priority arguments are omitted, function calls the legacy dump command.
764 */
765 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
766 @Override
767 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
768 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
769 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
770 }
771
772 @Override
773 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
774 doDump(fd, pw, args, asProto);
775 }
776
777 @Override
778 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
779 doDump(fd, pw, args, asProto);
780 }
781 };
782
Jeff Sharkey899223b2012-08-04 15:24:58 -0700783 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700784 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900785 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
786 }
787
788 @VisibleForTesting
789 protected ConnectivityService(Context context, INetworkManagementService netManager,
790 INetworkStatsService statsService, INetworkPolicyManager policyManager,
791 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800792 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800793
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900794 mSystemProperties = getSystemProperties();
795
Hugo Benichif9fdf872016-07-28 17:53:06 +0900796 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900797 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900798 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900799 mNetworkRequests.put(mDefaultRequest, defaultNRI);
800 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900801
Chalard Jeandda156a2018-01-10 21:19:32 +0900802 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900803 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700804
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700805 // The default WiFi request is a background request so that apps using WiFi are
806 // migrated to a better network (typically ethernet) when one comes up, instead
807 // of staying on WiFi forever.
808 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
809 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
810
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900811 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900812 mHandlerThread.start();
813 mHandler = new InternalHandler(mHandlerThread.getLooper());
814 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700815
Jeremy Joslin79294842014-12-03 17:15:28 -0800816 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
817 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
818
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900819 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900820
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700821 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800822 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800823 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700824 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900825 mPolicyManagerInternal = checkNotNull(
826 LocalServices.getService(NetworkPolicyManagerInternal.class),
827 "missing NetworkPolicyManagerInternal");
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000828 mProxyTracker = makeProxyTracker();
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900829
Luke Huang674660f2018-09-27 19:33:11 +0800830 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700831 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700832 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700833
junyulai05986c62018-08-07 19:50:45 +0800834 // To ensure uid rules are synchronized with Network Policy, register for
835 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
836 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700837 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900838 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700839 } catch (RemoteException e) {
840 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700841 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700842 }
843
844 final PowerManager powerManager = (PowerManager) context.getSystemService(
845 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700846 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
847 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
848 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800849 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700850
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700851 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700852
Wink Saville51f456f2013-04-23 14:26:51 -0700853 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900854 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700855 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700856 String[] naStrings = context.getResources().getStringArray(
857 com.android.internal.R.array.networkAttributes);
858 for (String naString : naStrings) {
859 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700860 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700861 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700862 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800863 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700864 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700865 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700866 }
Wink Saville51f456f2013-04-23 14:26:51 -0700867 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
868 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
869 n.type);
870 continue;
871 }
Wink Saville975c8482011-04-07 14:23:45 -0700872 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800873 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700874 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700875 continue;
876 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700877 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700878
Wink Saville975c8482011-04-07 14:23:45 -0700879 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700880 mNetworksDefined++;
881 } catch(Exception e) {
882 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700883 }
884 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700885
886 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
887 if (mNetConfigs[TYPE_VPN] == null) {
888 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
889 // don't need to add TYPE_VPN to mNetConfigs.
890 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
891 mNetworksDefined++; // used only in the log() statement below.
892 }
893
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900894 // Do the same for Ethernet, since it's often not specified in the configs, although many
895 // devices can use it via USB host adapters.
896 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
897 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
898 mNetworksDefined++;
899 }
900
Wink Saville5e56bc52013-07-29 15:00:57 -0700901 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700902
Robert Greenwalt50393202011-06-21 17:26:14 -0700903 mProtectedNetworks = new ArrayList<Integer>();
904 int[] protectedNetworks = context.getResources().getIntArray(
905 com.android.internal.R.array.config_protectedNetworks);
906 for (int p : protectedNetworks) {
907 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
908 mProtectedNetworks.add(p);
909 } else {
910 if (DBG) loge("Ignoring protectedNetwork " + p);
911 }
912 }
913
Erik Kline47222fc2017-04-30 19:36:15 +0900914 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800915
Luke Huang4e25ec62018-09-27 16:58:23 +0800916 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700917
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700918 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700919 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100920 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700921 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700922 intentFilter.addAction(Intent.ACTION_USER_ADDED);
923 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000924 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700925 mContext.registerReceiverAsUser(
junyulai2454b692018-11-01 17:16:31 +0800926 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000927 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
928 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900929
junyulai2454b692018-11-01 17:16:31 +0800930 // Listen to package add and removal events for all users.
931 intentFilter = new IntentFilter();
932 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800933 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800934 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
935 intentFilter.addDataScheme("package");
936 mContext.registerReceiverAsUser(
937 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
938
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700939 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800940 mNMS.registerObserver(mTethering);
941 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700942 } catch (RemoteException e) {
943 loge("Error registering observer :" + e);
944 }
945
Erik Klineda4bfa82015-04-30 12:58:40 +0900946 mSettingsObserver = new SettingsObserver(mContext, mHandler);
947 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800948
Chalard Jean4133a122018-06-04 13:33:12 +0900949 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
950 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400951
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400952 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900953
954 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900955 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
956 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900957
958 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
959 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
960 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
961 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
962 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
963 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
964 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900965
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900966 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900967 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900968 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900969
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900970 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
971
Luke Huang4e25ec62018-09-27 16:58:23 +0800972 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900973 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700975
Mike Yuf9729752018-08-17 15:22:05 +0800976 @VisibleForTesting
977 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +0900978 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900979 final TetheringDependencies deps = new TetheringDependencies() {
980 @Override
981 public boolean isTetheringSupported() {
982 return ConnectivityService.this.isTetheringSupported();
983 }
Erik Kline72302902018-06-14 17:36:40 +0900984 @Override
985 public NetworkRequest getDefaultNetworkRequest() {
986 return mDefaultRequest;
987 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900988 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800989 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900990 IoThread.get().getLooper(), new MockableSystemProperties(),
991 deps);
992 }
993
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000994 @VisibleForTesting
995 protected ProxyTracker makeProxyTracker() {
996 return new ProxyTracker(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
997 }
998
Chalard Jean26400492018-04-18 20:18:38 +0900999 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1000 final NetworkCapabilities netCap = new NetworkCapabilities();
1001 netCap.addCapability(NET_CAPABILITY_INTERNET);
1002 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
1003 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1004 netCap.setSingleUid(uid);
1005 return netCap;
1006 }
1007
Chalard Jeandda156a2018-01-10 21:19:32 +09001008 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001009 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001010 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001011 netCap.addCapability(NET_CAPABILITY_INTERNET);
1012 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001013 if (transportType > -1) {
1014 netCap.addTransportType(transportType);
1015 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001016 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001017 }
1018
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001019 // Used only for testing.
1020 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001021 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001022 // changing ContentResolver to make registerContentObserver non-final).
1023 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1024 // by subclassing SettingsObserver.
1025 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001026 void updateAlwaysOnNetworks() {
1027 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001028 }
1029
Erik Kline736353a2018-03-21 07:18:33 -07001030 // See FakeSettingsProvider comment above.
1031 @VisibleForTesting
1032 void updatePrivateDnsSettings() {
1033 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1034 }
1035
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001036 private void handleAlwaysOnNetworkRequest(
1037 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001038 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001039 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1040 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001041 if (enable == isEnabled) {
1042 return; // Nothing to do.
1043 }
1044
1045 if (enable) {
1046 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001047 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001048 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001049 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +09001050 }
1051 }
1052
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001053 private void handleConfigureAlwaysOnNetworks() {
1054 handleAlwaysOnNetworkRequest(
1055 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1056 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1057 false);
1058 }
1059
Erik Klineda4bfa82015-04-30 12:58:40 +09001060 private void registerSettingsCallbacks() {
1061 // Watch for global HTTP proxy changes.
1062 mSettingsObserver.observe(
1063 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1064 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1065
1066 // Watch for whether or not to keep mobile data always on.
1067 mSettingsObserver.observe(
1068 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001069 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1070
1071 // Watch for whether or not to keep wifi always on.
1072 mSettingsObserver.observe(
1073 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1074 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001075 }
1076
Erik Klinea24d4592018-01-11 21:07:29 +09001077 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001078 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1079 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001080 }
1081 }
1082
Robert Greenwalt34524f02014-05-18 16:22:10 -07001083 private synchronized int nextNetworkRequestId() {
1084 return mNextNetworkRequestId++;
1085 }
1086
Paul Jensen67b0b072015-06-10 11:22:17 -04001087 @VisibleForTesting
1088 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001089 synchronized (mNetworkForNetId) {
1090 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1091 int netId = mNextNetId;
1092 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1093 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001094 if (!mNetIdInUse.get(netId)) {
1095 mNetIdInUse.put(netId, true);
1096 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001097 }
1098 }
1099 }
1100 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001101 }
1102
Chalard Jeanc0982912018-06-07 16:11:34 +09001103 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001104 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001105 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1106 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001108 state = nai.getNetworkState();
1109 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001110 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001111 final NetworkInfo info = new NetworkInfo(networkType, 0,
1112 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001113 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1114 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001115 final NetworkCapabilities capabilities = new NetworkCapabilities();
1116 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1117 !info.isRoaming());
1118 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001119 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001120 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001121 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001122 return state;
1123 } else {
1124 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001125 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001126 }
1127
junyulai4a192e22018-06-13 15:00:37 +08001128 @VisibleForTesting
1129 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001130 if (network == null) {
1131 return null;
1132 }
Erik Kline736353a2018-03-21 07:18:33 -07001133 return getNetworkAgentInfoForNetId(network.netId);
1134 }
1135
1136 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001138 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001141
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001142 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001143 synchronized (mVpns) {
1144 if (!mLockdownEnabled) {
1145 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001146 Vpn vpn = mVpns.get(user);
1147 if (vpn != null && vpn.appliesToUid(uid)) {
1148 return vpn.getUnderlyingNetworks();
1149 }
1150 }
1151 }
1152 return null;
1153 }
1154
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001156 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001157
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001158 final Network[] networks = getVpnUnderlyingNetworks(uid);
1159 if (networks != null) {
1160 // getUnderlyingNetworks() returns:
1161 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1162 // empty array => the VPN explicitly said "no default network".
1163 // non-empty array => the VPN specified one or more default networks; we use the
1164 // first one.
1165 if (networks.length > 0) {
1166 nai = getNetworkAgentInfoForNetwork(networks[0]);
1167 } else {
1168 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001169 }
1170 }
1171
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 return nai.getNetworkState();
1174 } else {
1175 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001176 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001177 }
1178
1179 /**
1180 * Check if UID should be blocked from using the network with the given LinkProperties.
1181 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1183 boolean ignoreBlocked) {
1184 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001185 if (ignoreBlocked) {
1186 return false;
1187 }
Robin Lee17e61832016-05-09 13:46:28 +01001188 synchronized (mVpns) {
1189 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001190 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001191 return true;
1192 }
1193 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001194 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001195 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001196 }
1197
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001198 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001199 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1200 return;
1201 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001202 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001203 synchronized (mBlockedAppUids) {
1204 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001205 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001206 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001207 blocked = false;
1208 } else {
1209 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001210 }
1211 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001212 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1213 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1214 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001215 }
1216
junyulai05986c62018-08-07 19:50:45 +08001217 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1218 boolean blocked) {
1219 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1220 return;
1221 }
1222 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1223 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1224 nri.mUid, nri.request.requestId, net.netId));
1225 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1226 }
1227
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001228 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001229 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1230 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001231 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001232 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001233 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001234 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1235
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001236 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001237 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001238 }
Hugo Benichi69744342017-11-27 10:57:16 +09001239 synchronized (mVpns) {
1240 if (mLockdownTracker != null) {
1241 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1242 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001243 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 }
1245
1246 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 * Return NetworkInfo for the active (i.e., connected) network interface.
1248 * It is assumed that at most one network is active at a time. If more
1249 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001250 * @return the info for the active network, or {@code null} if none is
1251 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001253 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001255 enforceAccessPermission();
1256 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001257 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001258 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001259 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1260 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
1262
Paul Jensen31a94f42015-02-13 14:18:39 -05001263 @Override
1264 public Network getActiveNetwork() {
1265 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001266 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001267 }
1268
1269 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001270 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001271 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001272 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001273 }
1274
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001275 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001276 final int user = UserHandle.getUserId(uid);
1277 int vpnNetId = NETID_UNSET;
1278 synchronized (mVpns) {
1279 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001280 // TODO : now that capabilities contain the UID, the appliesToUid test should
1281 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001282 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1283 }
1284 NetworkAgentInfo nai;
1285 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001286 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001287 if (nai != null) {
1288 final NetworkCapabilities requiredCaps =
1289 createDefaultNetworkCapabilitiesForUid(uid);
1290 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1291 return nai.network;
1292 }
1293 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001294 }
1295 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001296 if (nai != null
1297 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1298 nai = null;
1299 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001300 return nai != null ? nai.network : null;
1301 }
1302
Lorenzo Colitti18660282016-07-04 12:55:44 +09001303 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001304 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1305 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001306 final int uid = Binder.getCallingUid();
1307 NetworkState state = getUnfilteredActiveNetworkState(uid);
1308 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001309 }
1310
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001311 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001312 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001313 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001314 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001315 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001316 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001317 }
1318
1319 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 public NetworkInfo getNetworkInfo(int networkType) {
1321 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001322 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001323 if (getVpnUnderlyingNetworks(uid) != null) {
1324 // A VPN is active, so we may need to return one of its underlying networks. This
1325 // information is not available in LegacyTypeTracker, so we have to get it from
1326 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001327 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001328 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001329 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001330 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001331 }
1332 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001333 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001334 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001337 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001338 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001339 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001340 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001341 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001342 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001343 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001344 return state.networkInfo;
1345 } else {
1346 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001347 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001348 }
1349
1350 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 public NetworkInfo[] getAllNetworkInfo() {
1352 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001353 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001354 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1355 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001356 NetworkInfo info = getNetworkInfo(networkType);
1357 if (info != null) {
1358 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001361 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001364 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001365 public Network getNetworkForType(int networkType) {
1366 enforceAccessPermission();
1367 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001368 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001369 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001370 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001371 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001372 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001373 }
1374
1375 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001376 public Network[] getAllNetworks() {
1377 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001378 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001379 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001380 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001381 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001382 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001383 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001384 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001385 }
1386
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001387 @Override
1388 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1389 // The basic principle is: if an app's traffic could possibly go over a
1390 // network, without the app doing anything multinetwork-specific,
1391 // (hence, by "default"), then include that network's capabilities in
1392 // the array.
1393 //
1394 // In the normal case, app traffic only goes over the system's default
1395 // network connection, so that's the only network returned.
1396 //
1397 // With a VPN in force, some app traffic may go into the VPN, and thus
1398 // over whatever underlying networks the VPN specifies, while other app
1399 // traffic may go over the system default network (e.g.: a split-tunnel
1400 // VPN, or an app disallowed by the VPN), so the set of networks
1401 // returned includes the VPN's underlying networks and the system
1402 // default.
1403 enforceAccessPermission();
1404
Chalard Jean4133a122018-06-04 13:33:12 +09001405 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001406
1407 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001408 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001409 if (nc != null) {
1410 result.put(nai.network, nc);
1411 }
1412
Hugo Benichi69744342017-11-27 10:57:16 +09001413 synchronized (mVpns) {
1414 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001415 Vpn vpn = mVpns.get(userId);
1416 if (vpn != null) {
1417 Network[] networks = vpn.getUnderlyingNetworks();
1418 if (networks != null) {
1419 for (Network network : networks) {
1420 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001421 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001422 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001423 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001424 }
1425 }
1426 }
1427 }
1428 }
1429 }
1430
1431 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1432 out = result.values().toArray(out);
1433 return out;
1434 }
1435
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001436 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001437 public boolean isNetworkSupported(int networkType) {
1438 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001439 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001440 }
1441
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001442 /**
1443 * Return LinkProperties for the active (i.e., connected) default
1444 * network interface. It is assumed that at most one default network
1445 * is active at a time. If more than one is active, it is indeterminate
1446 * which will be returned.
1447 * @return the ip properties for the active network, or {@code null} if
1448 * none is active
1449 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001450 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001451 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001452 enforceAccessPermission();
1453 final int uid = Binder.getCallingUid();
1454 NetworkState state = getUnfilteredActiveNetworkState(uid);
1455 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001456 }
1457
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001458 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001459 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001460 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001461 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1462 if (nai != null) {
1463 synchronized (nai) {
1464 return new LinkProperties(nai.linkProperties);
1465 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001466 }
1467 return null;
1468 }
1469
Robert Greenwalt12e67352014-05-13 21:41:06 -07001470 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001471 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001472 public LinkProperties getLinkProperties(Network network) {
1473 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001474 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1475 }
1476
1477 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1478 if (nai == null) {
1479 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001480 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001481 synchronized (nai) {
1482 return new LinkProperties(nai.linkProperties);
1483 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001484 }
1485
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001486 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001487 if (nai != null) {
1488 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001489 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001490 return networkCapabilitiesRestrictedForCallerPermissions(
1491 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001492 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001493 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001494 }
1495 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001496 return null;
1497 }
1498
1499 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001500 public NetworkCapabilities getNetworkCapabilities(Network network) {
1501 enforceAccessPermission();
1502 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1503 }
1504
Chalard Jeanb03a6222018-04-11 21:09:10 +09001505 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001506 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001507 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001508 if (!checkSettingsPermission(callerPid, callerUid)) {
1509 newNc.setUids(null);
1510 newNc.setSSID(null);
1511 }
Etan Cohen836ad572018-12-30 17:59:59 -08001512 if (newNc.getNetworkSpecifier() != null) {
1513 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1514 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001515 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001516 }
1517
Chalard Jeanb552c462018-02-21 18:43:54 +09001518 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1519 if (!checkSettingsPermission()) {
1520 nc.setSingleUid(Binder.getCallingUid());
1521 }
1522 }
1523
Chalard Jean26aa91a2018-03-20 19:13:57 +09001524 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1525 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1526 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1527 }
1528 }
1529
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001530 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001531 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001532 // Require internal since we're handing out IMSI details
1533 enforceConnectivityInternalPermission();
1534
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001535 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001536 for (Network network : getAllNetworks()) {
1537 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1538 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001539 // TODO (b/73321673) : NetworkState contains a copy of the
1540 // NetworkCapabilities, which may contain UIDs of apps to which the
1541 // network applies. Should the UIDs be cleared so as not to leak or
1542 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001543 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001544 }
1545 }
1546 return result.toArray(new NetworkState[result.size()]);
1547 }
1548
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001549 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001550 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001551 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001552 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1553 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1554 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001555 }
1556
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001557 @Override
1558 public boolean isActiveNetworkMetered() {
1559 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001560
Eric Enslenc81ef192018-02-07 18:03:53 -08001561 final int uid = Binder.getCallingUid();
1562 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001563 if (caps != null) {
1564 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1565 } else {
1566 // Always return the most conservative value
1567 return true;
1568 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001569 }
1570
Jeff Sharkey216c1812012-08-05 14:29:23 -07001571 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1572 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001573 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001574 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001575 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001576 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001577 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001578
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001579 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001580 * Ensures that the system cannot call a particular method.
1581 */
1582 private boolean disallowedBecauseSystemCaller() {
1583 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1584 // requestRouteToHost.
1585 if (isSystem(Binder.getCallingUid())) {
1586 log("This method exists only for app backwards compatibility"
1587 + " and must not be called by system services.");
1588 return true;
1589 }
1590 return false;
1591 }
1592
1593 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 * Ensure that a network route exists to deliver traffic to the specified
1595 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001596 * @param networkType the type of the network over which traffic to the
1597 * specified host is to be routed
1598 * @param hostAddress the IP address of the host to which the route is
1599 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 * @return {@code true} on success, {@code false} on failure
1601 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001602 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001603 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001604 if (disallowedBecauseSystemCaller()) {
1605 return false;
1606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001608 if (mProtectedNetworks.contains(networkType)) {
1609 enforceConnectivityInternalPermission();
1610 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001611
Chad Brubakerc0234532014-02-14 13:24:29 -08001612 InetAddress addr;
1613 try {
1614 addr = InetAddress.getByAddress(hostAddress);
1615 } catch (UnknownHostException e) {
1616 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1617 return false;
1618 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001621 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 return false;
1623 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001624
1625 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1626 if (nai == null) {
1627 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1628 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1629 } else {
1630 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1631 }
1632 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001633 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001634
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001635 DetailedState netState;
1636 synchronized (nai) {
1637 netState = nai.networkInfo.getDetailedState();
1638 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001639
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001640 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001641 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001642 log("requestRouteToHostAddress on down network "
1643 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001644 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001645 }
1646 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001648
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001649 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001650 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001651 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001652 LinkProperties lp;
1653 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001654 synchronized (nai) {
1655 lp = nai.linkProperties;
1656 netId = nai.network.netId;
1657 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001658 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001659 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1660 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001661 } finally {
1662 Binder.restoreCallingIdentity(token);
1663 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001664 }
1665
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001666 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001667 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001668 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001669 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001670 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001671 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001672 if (bestRoute.getGateway().equals(addr)) {
1673 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001674 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001675 } else {
1676 // if we will connect to this through another route, add a direct route
1677 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001678 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001679 }
1680 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001681 if (DBG) log("Adding legacy route " + bestRoute +
1682 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001683 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001684 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001685 } catch (Exception e) {
1686 // never crash - catch them all
1687 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001688 return false;
1689 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001690 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692
dalyk7301aa42018-03-05 12:42:22 -05001693 @VisibleForTesting
1694 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1695 @Override
1696 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1697 String hostname, boolean validated) {
1698 try {
1699 mHandler.sendMessage(mHandler.obtainMessage(
1700 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1701 new PrivateDnsValidationUpdate(netId,
1702 InetAddress.parseNumericAddress(ipAddress),
1703 hostname, validated)));
1704 } catch (IllegalArgumentException e) {
1705 loge("Error parsing ip address in validation event");
1706 }
1707 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001708
1709 @Override
1710 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1711 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1712 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1713 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1714 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1715 // event callback for certain nai. e.g. cellular. Register here to pass to
1716 // NetworkMonitor instead.
1717 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1718 // registerNetworkAgent to have NetworkMonitor created with system process as design
1719 // expectation. Also, NetdEventListenerService only allow one callback from each
1720 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1721 // NetworkMonitor registrants.
1722 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001723 try {
1724 nai.networkMonitor().notifyDnsResponse(returnCode);
1725 } catch (RemoteException e) {
1726 e.rethrowFromSystemServer();
1727 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001728 }
1729 }
dalyk7301aa42018-03-05 12:42:22 -05001730 };
1731
1732 @VisibleForTesting
1733 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001734 final IIpConnectivityMetrics ipConnectivityMetrics =
1735 IIpConnectivityMetrics.Stub.asInterface(
1736 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1737 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001738 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001739 return;
dalyk7301aa42018-03-05 12:42:22 -05001740 }
1741
1742 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001743 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001744 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1745 mNetdEventCallback);
1746 } catch (Exception e) {
1747 loge("Error registering netd callback: " + e);
1748 }
1749 }
1750
Jeff Sharkey75d31892018-01-18 22:01:59 +09001751 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001752 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001753 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001754 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001755 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001756 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001757 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001758 // caller is NPMS, since we only register with them
1759 if (LOGD_BLOCKED_NETWORKINFO) {
1760 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1761 }
1762 mHandler.sendMessage(mHandler.obtainMessage(
1763 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1764
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001765 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001766 if (restrictBackground) {
1767 log("onRestrictBackgroundChanged(true): disabling tethering");
1768 mTethering.untetherAll();
1769 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001770 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001771 };
1772
junyulai05986c62018-08-07 19:50:45 +08001773 void handleUidRulesChanged(int uid, int newRules) {
1774 // skip update when we've already applied rules
1775 final int oldRules = mUidRules.get(uid, RULE_NONE);
1776 if (oldRules == newRules) return;
1777
1778 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1779
1780 if (newRules == RULE_NONE) {
1781 mUidRules.delete(uid);
1782 } else {
1783 mUidRules.put(uid, newRules);
1784 }
1785 }
1786
1787 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1788 if (mRestrictBackground == restrictBackground) return;
1789
1790 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1791 final boolean curMetered = nai.networkCapabilities.isMetered();
1792 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1793 restrictBackground);
1794 }
1795
1796 mRestrictBackground = restrictBackground;
1797 }
1798
1799 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1800 boolean isBackgroundRestricted) {
1801 synchronized (mVpns) {
1802 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1803 // Because the return value of this function depends on the list of UIDs the
1804 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1805 // list all state depending on the return value of this function has to be recomputed.
1806 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1807 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001808 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001809 return true;
1810 }
1811 }
1812
1813 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1814 isNetworkMetered, isBackgroundRestricted);
1815 }
1816
Robin Lee3b3dd942015-05-12 18:14:58 +01001817 /**
1818 * Require that the caller is either in the same user or has appropriate permission to interact
1819 * across users.
1820 *
1821 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1822 */
1823 private void enforceCrossUserPermission(int userId) {
1824 if (userId == UserHandle.getCallingUserId()) {
1825 // Not a cross-user call.
1826 return;
1827 }
1828 mContext.enforceCallingOrSelfPermission(
1829 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1830 "ConnectivityService");
1831 }
1832
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001833 private void enforceAnyPermissionOf(String... permissions) {
1834 for (String permission : permissions) {
1835 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
1836 return;
1837 }
1838 }
1839 throw new SecurityException(
1840 "Requires one of the following permissions: " + String.join(", ", permissions) + ".");
1841 }
1842
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001843 private void enforceInternetPermission() {
1844 mContext.enforceCallingOrSelfPermission(
1845 android.Manifest.permission.INTERNET,
1846 "ConnectivityService");
1847 }
1848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001850 mContext.enforceCallingOrSelfPermission(
1851 android.Manifest.permission.ACCESS_NETWORK_STATE,
1852 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854
1855 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001856 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 }
1858
Charles He36738632017-05-15 17:07:18 +01001859 private void enforceSettingsPermission() {
1860 mContext.enforceCallingOrSelfPermission(
1861 android.Manifest.permission.NETWORK_SETTINGS,
1862 "ConnectivityService");
1863 }
1864
Chalard Jeanb552c462018-02-21 18:43:54 +09001865 private boolean checkSettingsPermission() {
1866 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1867 android.Manifest.permission.NETWORK_SETTINGS);
1868 }
1869
1870 private boolean checkSettingsPermission(int pid, int uid) {
1871 return PERMISSION_GRANTED == mContext.checkPermission(
1872 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1873 }
1874
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001875 private void enforceTetherAccessPermission() {
1876 mContext.enforceCallingOrSelfPermission(
1877 android.Manifest.permission.ACCESS_NETWORK_STATE,
1878 "ConnectivityService");
1879 }
1880
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001881 private void enforceConnectivityInternalPermission() {
1882 mContext.enforceCallingOrSelfPermission(
1883 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1884 "ConnectivityService");
1885 }
1886
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001887 private void enforceNetworkStackSettingsOrSetup() {
1888 enforceAnyPermissionOf(
1889 android.Manifest.permission.NETWORK_SETTINGS,
1890 android.Manifest.permission.NETWORK_SETUP_WIZARD,
1891 android.Manifest.permission.NETWORK_STACK);
1892 }
1893
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001894 private boolean checkNetworkStackPermission() {
1895 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1896 android.Manifest.permission.NETWORK_STACK);
1897 }
1898
Hugo Benichi514da602016-07-19 15:59:27 +09001899 private void enforceConnectivityRestrictedNetworksPermission() {
1900 try {
1901 mContext.enforceCallingOrSelfPermission(
1902 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1903 "ConnectivityService");
1904 return;
1905 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1906 enforceConnectivityInternalPermission();
1907 }
1908
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001909 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001910 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001911 }
1912
Lorenzo Colitti18660282016-07-04 12:55:44 +09001913 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001914 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001915 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001916 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001917 }
1918
1919 private void sendInetConditionBroadcast(NetworkInfo info) {
1920 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1921 }
1922
Wink Saville628b0852011-08-04 15:01:58 -07001923 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001924 synchronized (mVpns) {
1925 if (mLockdownTracker != null) {
1926 info = new NetworkInfo(info);
1927 mLockdownTracker.augmentNetworkInfo(info);
1928 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001929 }
1930
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001931 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001932 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001933 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 if (info.isFailover()) {
1935 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1936 info.setFailover(false);
1937 }
1938 if (info.getReason() != null) {
1939 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1940 }
1941 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001942 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1943 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001945 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001946 return intent;
1947 }
1948
1949 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1950 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1951 }
1952
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001953 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001954 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1955 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1956 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001957 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001958 final long ident = Binder.clearCallingIdentity();
1959 try {
1960 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1961 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1962 } finally {
1963 Binder.restoreCallingIdentity(ident);
1964 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001965 }
1966
Mike Lockwood0f79b542009-08-14 14:18:49 -04001967 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001968 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09001969 if (!mSystemReady
1970 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001971 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001972 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001973 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001974 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001975 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001976 }
1977
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001978 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001979 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001980 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001981 final NetworkInfo ni = intent.getParcelableExtra(
1982 ConnectivityManager.EXTRA_NETWORK_INFO);
1983 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1984 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1985 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001986 } else {
1987 BroadcastOptions opts = BroadcastOptions.makeBasic();
1988 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1989 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001990 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001991 final IBatteryStats bs = BatteryStatsService.getService();
1992 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001993 bs.noteConnectivityChanged(intent.getIntExtra(
1994 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001995 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001996 } catch (RemoteException e) {
1997 }
Chad Brubakerac925012018-03-08 10:37:09 -08001998 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001999 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002000 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08002001 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002002 } finally {
2003 Binder.restoreCallingIdentity(ident);
2004 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04002005 }
2006 }
2007
2008 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002009 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002010 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002011 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002012
Hugo Benichi20035e02017-04-26 14:53:28 +09002013 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002014 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002015 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002016 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002017 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002018 }
2019 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002020
Robin Lee244ce8e2016-01-05 18:03:46 +00002021 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2022 // for user to unlock device too.
2023 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002024
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002025 // Create network requests for always-on networks.
2026 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002027
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002028 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002029
2030 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
2032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002034 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002035 *
2036 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002037 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002038 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2040 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002041
2042 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002043 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002044
Robert Greenwalt7b816022014-04-18 15:25:25 -07002045 if (networkAgent.networkCapabilities.hasTransport(
2046 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002047 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2048 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002049 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002050 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002051 } else if (networkAgent.networkCapabilities.hasTransport(
2052 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002053 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2054 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002055 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002056 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002057 } else {
2058 // do not track any other networks
2059 timeout = 0;
2060 }
2061
Robert Greenwalt7b816022014-04-18 15:25:25 -07002062 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002063 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002064 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002065 } catch (Exception e) {
2066 // You shall not crash!
2067 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002068 }
2069 }
2070 }
2071
2072 /**
2073 * Remove data activity tracking when network disconnects.
2074 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002075 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2076 final String iface = networkAgent.linkProperties.getInterfaceName();
2077 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002078
Robert Greenwalt7b816022014-04-18 15:25:25 -07002079 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2080 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002081 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002082 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002083 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002084 } catch (Exception e) {
2085 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002086 }
2087 }
2088 }
2089
2090 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002091 * Update data activity tracking when network state is updated.
2092 */
2093 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2094 NetworkAgentInfo oldNetwork) {
2095 if (newNetwork != null) {
2096 setupDataActivityTracking(newNetwork);
2097 }
2098 if (oldNetwork != null) {
2099 removeDataActivityTracking(oldNetwork);
2100 }
2101 }
2102 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002103 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002104 * and set it on it's iface.
2105 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002106 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2107 final String iface = newLp.getInterfaceName();
2108 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002109 if (oldLp == null && mtu == 0) {
2110 // Silently ignore unset MTU value.
2111 return;
2112 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2114 if (VDBG) log("identical MTU - not setting");
2115 return;
2116 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002117 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002118 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002119 return;
2120 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002121
w1997615afd812014-08-05 15:18:11 -07002122 // Cannot set MTU without interface name
2123 if (TextUtils.isEmpty(iface)) {
2124 loge("Setting MTU size with null iface.");
2125 return;
2126 }
2127
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002129 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002130 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 } catch (Exception e) {
2132 Slog.e(TAG, "exception in setMtu()" + e);
2133 }
2134 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002135
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002136 @VisibleForTesting
2137 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002138 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2139
2140 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002141 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002142 protected MockableSystemProperties getSystemProperties() {
2143 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002144 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002145
lucaslin041a1af2018-11-28 19:27:52 +08002146 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002147 String[] values = null;
2148 if (tcpBufferSizes != null) {
2149 values = tcpBufferSizes.split(",");
2150 }
2151
2152 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002153 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002154 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2155 values = tcpBufferSizes.split(",");
2156 }
2157
2158 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2159
2160 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002161 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002162
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002163 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2164 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2165 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002166 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002167 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002168 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002169 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002170
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002171 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002172 Settings.Global.TCP_DEFAULT_INIT_RWND,
2173 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002174 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2175 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002176 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002177 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002178 }
2179
Robert Greenwalt562cc542014-05-15 18:07:26 -07002180 @Override
2181 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002182 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002183 NETWORK_RESTORE_DELAY_PROP_NAME);
2184 if(restoreDefaultNetworkDelayStr != null &&
2185 restoreDefaultNetworkDelayStr.length() != 0) {
2186 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002187 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002188 } catch (NumberFormatException e) {
2189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002191 // if the system property isn't set, use the value for the apn type
2192 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2193
2194 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2195 (mNetConfigs[networkType] != null)) {
2196 ret = mNetConfigs[networkType].restoreTime;
2197 }
2198 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 }
2200
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002201 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2202 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2203 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002204 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002205 // Start gathering diagnostic information.
2206 netDiags.add(new NetworkDiagnostics(
2207 nai.network,
2208 new LinkProperties(nai.linkProperties), // Must be a copy.
2209 DIAG_TIME_MS));
2210 }
2211
2212 for (NetworkDiagnostics netDiag : netDiags) {
2213 pw.println();
2214 netDiag.waitForMeasurements();
2215 netDiag.dump(pw);
2216 }
2217 }
2218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002220 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002221 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2222 }
2223
2224 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002225 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002226 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002227 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002228
Erik Kline3f8306b2018-05-01 16:51:44 +09002229 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002230 dumpNetworkDiagnostics(pw);
2231 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002232 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002233 mTethering.dump(fd, pw, args);
2234 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002235 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2236 dumpNetworks(pw);
2237 return;
2238 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2239 dumpNetworkRequests(pw);
2240 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002241 }
Erik Kline379747a2015-06-05 17:47:34 +09002242
Lorenzo Colittie3805462015-06-03 11:18:24 +09002243 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002244 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002245 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002246 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002247 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002248 pw.println();
2249
Paul Jensen85cf78e2015-06-25 13:25:07 -04002250 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002251 pw.print("Active default network: ");
2252 if (defaultNai == null) {
2253 pw.println("none");
2254 } else {
2255 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002257 pw.println();
2258
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002259 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002260 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002261 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002262 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002263 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002264
junyulai05986c62018-08-07 19:50:45 +08002265 pw.print("Restrict background: ");
2266 pw.println(mRestrictBackground);
2267 pw.println();
2268
2269 pw.println("Status for known UIDs:");
2270 pw.increaseIndent();
2271 final int size = mUidRules.size();
2272 for (int i = 0; i < size; i++) {
2273 // Don't crash if the array is modified while dumping in bugreports.
2274 try {
2275 final int uid = mUidRules.keyAt(i);
2276 final int uidRules = mUidRules.get(uid, RULE_NONE);
2277 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2278 } catch (ArrayIndexOutOfBoundsException e) {
2279 pw.println(" ArrayIndexOutOfBoundsException");
2280 } catch (ConcurrentModificationException e) {
2281 pw.println(" ConcurrentModificationException");
2282 }
2283 }
2284 pw.println();
2285 pw.decreaseIndent();
2286
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002287 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002288 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002289 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002290 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002291 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002292
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002293 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002294
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002295 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002296 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002297
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002298 pw.println();
2299 mKeepaliveTracker.dump(pw);
2300
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002301 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002302 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002303
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002304 pw.println();
2305 mMultipathPolicyTracker.dump(pw);
2306
Erik Kline3f8306b2018-05-01 16:51:44 +09002307 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002308 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002309 pw.println("mNetworkRequestInfoLogs (most recent first):");
2310 pw.increaseIndent();
2311 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2312 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002313
2314 pw.println();
2315 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2316 pw.increaseIndent();
2317 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2318 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002319
2320 pw.println();
2321 pw.println("NetTransition WakeLock activity (most recent first):");
2322 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002323 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2324 pw.println("total releases: " + mTotalWakelockReleases);
2325 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2326 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2327 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2328 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2329 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2330 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002331 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002332
2333 pw.println();
2334 pw.println("bandwidth update requests (by uid):");
2335 pw.increaseIndent();
2336 synchronized (mBandwidthRequests) {
2337 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2338 pw.println("[" + mBandwidthRequests.keyAt(i)
2339 + "]: " + mBandwidthRequests.valueAt(i));
2340 }
2341 }
2342 pw.decreaseIndent();
2343
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002344 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 }
2347
Hugo Benichi14683812018-09-03 08:32:56 +09002348 private void dumpNetworks(IndentingPrintWriter pw) {
2349 for (NetworkAgentInfo nai : networksSortedById()) {
2350 pw.println(nai.toString());
2351 pw.increaseIndent();
2352 pw.println(String.format(
2353 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2354 nai.numForegroundNetworkRequests(),
2355 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2356 nai.numBackgroundNetworkRequests(),
2357 nai.numNetworkRequests()));
2358 pw.increaseIndent();
2359 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2360 pw.println(nai.requestAt(i).toString());
2361 }
2362 pw.decreaseIndent();
2363 pw.println("Lingered:");
2364 pw.increaseIndent();
2365 nai.dumpLingerTimers(pw);
2366 pw.decreaseIndent();
2367 pw.decreaseIndent();
2368 }
2369 }
2370
2371 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2372 for (NetworkRequestInfo nri : requestsSortedById()) {
2373 pw.println(nri.toString());
2374 }
2375 }
2376
Hugo Benichia2a917c2018-09-03 08:19:02 +09002377 /**
2378 * Return an array of all current NetworkAgentInfos sorted by network id.
2379 */
2380 private NetworkAgentInfo[] networksSortedById() {
2381 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2382 networks = mNetworkAgentInfos.values().toArray(networks);
2383 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2384 return networks;
2385 }
2386
2387 /**
2388 * Return an array of all current NetworkRequest sorted by request id.
2389 */
2390 private NetworkRequestInfo[] requestsSortedById() {
2391 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2392 requests = mNetworkRequests.values().toArray(requests);
2393 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2394 return requests;
2395 }
2396
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002397 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002398 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002399 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002400 if (officialNai != null && officialNai.equals(nai)) return true;
2401 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002402 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002403 " - " + nai);
2404 }
2405 return false;
2406 }
2407
Robert Greenwalt42acef32009-08-12 16:08:25 -07002408 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002409 private class NetworkStateTrackerHandler extends Handler {
2410 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002411 super(looper);
2412 }
2413
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002414 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002416 default:
2417 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002418 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002419 handleAsyncChannelHalfConnect(msg);
2420 break;
2421 }
2422 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2423 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2424 if (nai != null) nai.asyncChannel.disconnect();
2425 break;
2426 }
2427 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2428 handleAsyncChannelDisconnected(msg);
2429 break;
2430 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002431 }
2432 return true;
2433 }
2434
2435 private void maybeHandleNetworkAgentMessage(Message msg) {
2436 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2437 if (nai == null) {
2438 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002439 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002440 }
2441 return;
2442 }
2443
2444 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002445 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002446 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2447 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002448 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2449 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002450 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002451 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002452 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002453 break;
2454 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002455 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002456 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002457 break;
2458 }
2459 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002460 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002461 updateNetworkInfo(nai, info);
2462 break;
2463 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002464 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002465 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002466 break;
2467 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002468 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002469 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2470 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002471 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002472 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002473 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002474 break;
2475 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002476 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002477 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2478 break;
2479 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002480 }
2481 }
2482
2483 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2484 switch (msg.what) {
2485 default:
2486 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002487 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002488 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002489 if (nai == null) break;
2490
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002491 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002492 final boolean wasValidated = nai.lastValidated;
2493 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002494 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2495 && valid) {
2496 nai.captivePortalLoginNotified = true;
2497 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2498 }
Erik Klinea24d4592018-01-11 21:07:29 +09002499
Erik Klinea24d4592018-01-11 21:07:29 +09002500 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2501
Erik Klinea24d4592018-01-11 21:07:29 +09002502 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002503 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2504 ? " with redirect to " + redirectUrl
2505 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002506 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2507 }
Erik Klinea24d4592018-01-11 21:07:29 +09002508 if (valid != nai.lastValidated) {
2509 if (wasDefault) {
2510 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2511 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002512 }
Erik Klinea24d4592018-01-11 21:07:29 +09002513 final int oldScore = nai.getCurrentScore();
2514 nai.lastValidated = valid;
2515 nai.everValidated |= valid;
2516 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2517 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2518 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002519 if (valid) {
2520 handleFreshlyValidatedNetwork(nai);
2521 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2522 // valid.
2523 mNotifier.clearNotification(nai.network.netId,
2524 NotificationType.NO_INTERNET);
2525 mNotifier.clearNotification(nai.network.netId,
2526 NotificationType.LOST_INTERNET);
2527 }
Erik Klinea24d4592018-01-11 21:07:29 +09002528 }
2529 updateInetCondition(nai);
2530 // Let the NetworkAgent know the state of its network
2531 Bundle redirectUrlBundle = new Bundle();
2532 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2533 nai.asyncChannel.sendMessage(
2534 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2535 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2536 0, redirectUrlBundle);
2537 if (wasValidated && !nai.lastValidated) {
2538 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002539 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002540 break;
2541 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002542 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002543 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002544 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002545 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002546 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002547 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002548 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002549 nai.lastCaptivePortalDetected = visible;
2550 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002551 if (visible) {
2552 nai.captivePortalLoginNotified = false;
2553 }
Calvin Onbe96da12016-10-11 15:10:46 -07002554 if (nai.lastCaptivePortalDetected &&
2555 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2556 if (DBG) log("Avoiding captive portal network: " + nai.name());
2557 nai.asyncChannel.sendMessage(
2558 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2559 teardownUnneededNetwork(nai);
2560 break;
2561 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002562 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002563 }
2564 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002565 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
2566 // notifications belong to the same network may be cleared unexpected.
2567 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2568 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002569 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002570 if (nai == null) {
2571 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2572 break;
2573 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002574 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002575 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002576 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002577 }
Paul Jensen869868be2014-05-15 10:33:05 -04002578 }
Paul Jensen869868be2014-05-15 10:33:05 -04002579 break;
2580 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002581 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002582 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002583 if (nai == null) break;
2584
Erik Kline736353a2018-03-21 07:18:33 -07002585 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002586 break;
2587 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002588 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002589 return true;
2590 }
2591
Calvin Onbe96da12016-10-11 15:10:46 -07002592 private int getCaptivePortalMode() {
2593 return Settings.Global.getInt(mContext.getContentResolver(),
2594 Settings.Global.CAPTIVE_PORTAL_MODE,
2595 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2596 }
2597
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002598 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2599 switch (msg.what) {
2600 default:
2601 return false;
2602 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2603 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2604 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2605 handleLingerComplete(nai);
2606 }
2607 break;
2608 }
2609 }
2610 return true;
2611 }
2612
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002613 @Override
2614 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002615 if (!maybeHandleAsyncChannelMessage(msg) &&
2616 !maybeHandleNetworkMonitorMessage(msg) &&
2617 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002618 maybeHandleNetworkAgentMessage(msg);
2619 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002620 }
2621 }
2622
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002623 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2624 private final NetworkAgentInfo mNai;
2625
2626 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2627 mNai = nai;
2628 }
2629
2630 @Override
2631 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2632 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2633 new Pair<>(mNai, networkMonitor)));
2634 }
2635
2636 @Override
2637 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2638 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2639 testResult, mNai.network.netId, redirectUrl));
2640 }
2641
2642 @Override
2643 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2644 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2645 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2646 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2647 }
2648
2649 @Override
2650 public void showProvisioningNotification(String action) {
2651 final Intent intent = new Intent(action);
2652 intent.setPackage(NETWORKSTACK_PACKAGE_NAME);
2653
2654 final PendingIntent pendingIntent;
2655 // Only the system server can register notifications with package "android"
2656 final long token = Binder.clearCallingIdentity();
2657 try {
2658 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2659 } finally {
2660 Binder.restoreCallingIdentity(token);
2661 }
2662 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2663 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2664 mNai.network.netId,
2665 pendingIntent));
2666 }
2667
2668 @Override
2669 public void hideProvisioningNotification() {
2670 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2671 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2672 mNai.network.netId));
2673 }
2674 }
2675
Erik Kline736353a2018-03-21 07:18:33 -07002676 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002677 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002678 }
2679
Erik Klinec6d00222018-06-26 18:53:43 +09002680 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2681 if (nai == null) return;
2682 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2683 // in order to restart a validation pass from within netd.
2684 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2685 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2686 updateDnses(nai.linkProperties, null, nai.network.netId);
2687 }
2688 }
2689
Erik Klinea24d4592018-01-11 21:07:29 +09002690 private void handlePrivateDnsSettingsChanged() {
2691 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2692
2693 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002694 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002695 if (networkRequiresValidation(nai)) {
2696 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2697 }
Erik Klinea24d4592018-01-11 21:07:29 +09002698 }
2699 }
2700
Erik Kline736353a2018-03-21 07:18:33 -07002701 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2702 // Private DNS only ever applies to networks that might provide
2703 // Internet access and therefore also require validation.
2704 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002705
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002706 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002707 // schedule DNS resolutions. If a DNS resolution is required the
2708 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002709 try {
2710 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2711 } catch (RemoteException e) {
2712 e.rethrowFromSystemServer();
2713 }
Erik Kline736353a2018-03-21 07:18:33 -07002714
2715 // With Private DNS bypass support, we can proceed to update the
2716 // Private DNS config immediately, even if we're in strict mode
2717 // and have not yet resolved the provider name into a set of IPs.
2718 updatePrivateDns(nai, cfg);
2719 }
2720
2721 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2722 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002723 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002724 }
2725
dalyk7301aa42018-03-05 12:42:22 -05002726 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2727 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2728 if (nai == null) {
2729 return;
2730 }
2731 mDnsManager.updatePrivateDnsValidation(update);
2732 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2733 }
2734
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002735 private void updateLingerState(NetworkAgentInfo nai, long now) {
2736 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2737 // 2. If the network was lingering and there are now requests, unlinger it.
2738 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2739 // one lingered request, start lingering.
2740 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002741 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002742 if (DBG) log("Unlingering " + nai.name());
2743 nai.unlinger();
2744 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002745 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002746 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002747 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002748 nai.linger();
2749 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2750 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2751 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002752 }
2753
Robert Greenwalt7b816022014-04-18 15:25:25 -07002754 private void handleAsyncChannelHalfConnect(Message msg) {
2755 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002756 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002757 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2758 if (VDBG) log("NetworkFactory connected");
2759 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002760 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002761 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002762 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002763 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002764 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002765 }
2766 } else {
2767 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002768 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002769 }
2770 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2771 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2772 if (VDBG) log("NetworkAgent connected");
2773 // A network agent has requested a connection. Establish the connection.
2774 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2775 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2776 } else {
2777 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002778 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002779 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002780 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002781 synchronized (mNetworkForNetId) {
2782 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002783 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002784 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002785 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002786 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002787 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002788 }
2789 }
2790 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002791
Chalard Jean392971c2018-05-11 20:19:20 +09002792 // This is a no-op if it's called with a message designating a network that has
2793 // already been destroyed, because its reference will not be found in the relevant
2794 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002795 private void handleAsyncChannelDisconnected(Message msg) {
2796 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2797 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002798 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002799 } else {
2800 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2801 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002802 }
2803 }
2804
Chalard Jean392971c2018-05-11 20:19:20 +09002805 // Destroys a network, remove references to it from the internal state managed by
2806 // ConnectivityService, free its interfaces and clean up.
2807 // Must be called on the Handler thread.
2808 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2809 if (DBG) {
2810 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2811 }
2812 // A network agent has disconnected.
2813 // TODO - if we move the logic to the network agent (have them disconnect
2814 // because they lost all their requests or because their score isn't good)
2815 // then they would disconnect organically, report their new state and then
2816 // disconnect the channel.
2817 if (nai.networkInfo.isConnected()) {
2818 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2819 null, null);
2820 }
2821 final boolean wasDefault = isDefaultNetwork(nai);
2822 if (wasDefault) {
2823 mDefaultInetConditionPublished = 0;
2824 // Log default network disconnection before required book-keeping.
2825 // Let rematchAllNetworksAndRequests() below record a new default network event
2826 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2827 // whose timestamps tell how long it takes to recover a default network.
2828 long now = SystemClock.elapsedRealtime();
2829 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2830 }
2831 notifyIfacesChangedForNetworkStats();
2832 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2833 // by other networks that are already connected. Perhaps that can be done by
2834 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2835 // of rematchAllNetworksAndRequests
2836 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2837 mKeepaliveTracker.handleStopAllKeepalives(nai,
2838 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2839 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2840 // Disable wakeup packet monitoring for each interface.
2841 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2842 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002843 try {
2844 nai.networkMonitor().notifyNetworkDisconnected();
2845 } catch (RemoteException e) {
2846 e.rethrowFromSystemServer();
2847 }
Chalard Jean392971c2018-05-11 20:19:20 +09002848 mNetworkAgentInfos.remove(nai.messenger);
2849 nai.maybeStopClat();
2850 synchronized (mNetworkForNetId) {
2851 // Remove the NetworkAgent, but don't mark the netId as
2852 // available until we've told netd to delete it below.
2853 mNetworkForNetId.remove(nai.network.netId);
2854 }
2855 // Remove all previously satisfied requests.
2856 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2857 NetworkRequest request = nai.requestAt(i);
2858 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2859 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2860 clearNetworkForRequest(request.requestId);
2861 sendUpdatedScoreToFactories(request, 0);
2862 }
2863 }
2864 nai.clearLingerState();
2865 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002866 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002867 notifyLockdownVpn(nai);
2868 ensureNetworkTransitionWakelock(nai.name());
2869 }
2870 mLegacyTypeTracker.remove(nai, wasDefault);
2871 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2872 updateAllVpnsCapabilities();
2873 }
2874 rematchAllNetworksAndRequests(null, 0);
2875 mLingerMonitor.noteDisconnect(nai);
2876 if (nai.created) {
2877 // Tell netd to clean up the configuration for this network
2878 // (routing rules, DNS, etc).
2879 // This may be slow as it requires a lot of netd shelling out to ip and
2880 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2881 // after we've rematched networks with requests which should make a potential
2882 // fallback network the default or requested a new network from the
2883 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2884 // long time.
2885 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002886 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002887 } catch (Exception e) {
2888 loge("Exception removing network: " + e);
2889 }
2890 mDnsManager.removeNetwork(nai.network);
2891 }
2892 synchronized (mNetworkForNetId) {
2893 mNetIdInUse.delete(nai.network.netId);
2894 }
2895 }
2896
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002897 // If this method proves to be too slow then we can maintain a separate
2898 // pendingIntent => NetworkRequestInfo map.
2899 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2900 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2901 Intent intent = pendingIntent.getIntent();
2902 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2903 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2904 if (existingPendingIntent != null &&
2905 existingPendingIntent.getIntent().filterEquals(intent)) {
2906 return entry.getValue();
2907 }
2908 }
2909 return null;
2910 }
2911
2912 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2913 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2914
2915 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2916 if (existingRequest != null) { // remove the existing request.
2917 if (DBG) log("Replacing " + existingRequest.request + " with "
2918 + nri.request + " because their intents matched.");
2919 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2920 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002921 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002922 }
2923
Erik Klineda4bfa82015-04-30 12:58:40 +09002924 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002925 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002926 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002927 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002928 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002929 if (nri.request.networkCapabilities.hasSignalStrength() &&
2930 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2931 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002932 }
2933 }
2934 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002935 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002936 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002937 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002938 }
2939 }
2940
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002941 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2942 int callingUid) {
2943 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2944 if (nri != null) {
2945 handleReleaseNetworkRequest(nri.request, callingUid);
2946 }
2947 }
2948
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002949 // Determines whether the network is the best (or could become the best, if it validated), for
2950 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2951 // on the value of reason:
2952 //
2953 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2954 // then it should be torn down.
2955 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2956 // then it should be lingered.
2957 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2958 final int numRequests;
2959 switch (reason) {
2960 case TEARDOWN:
2961 numRequests = nai.numRequestNetworkRequests();
2962 break;
2963 case LINGER:
2964 numRequests = nai.numForegroundNetworkRequests();
2965 break;
2966 default:
2967 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2968 return true;
2969 }
2970
2971 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002972 return false;
2973 }
Paul Jensene0988542015-06-25 15:30:08 -04002974 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002975 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2976 // Background requests don't affect lingering.
2977 continue;
2978 }
2979
Paul Jensene0988542015-06-25 15:30:08 -04002980 // If this Network is already the highest scoring Network for a request, or if
2981 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002982 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002983 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002984 // Note that this catches two important cases:
2985 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2986 // is currently satisfying the request. This is desirable when
2987 // cellular ends up validating but WiFi does not.
2988 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002989 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002990 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002991 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002992 nai.getCurrentScoreAsValidated())) {
2993 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002994 }
2995 }
Paul Jensene0988542015-06-25 15:30:08 -04002996 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002997 }
2998
Erik Klineacdd6392016-07-07 16:50:58 +09002999 private NetworkRequestInfo getNriForAppRequest(
3000 NetworkRequest request, int callingUid, String requestedOperation) {
3001 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3002
Robert Greenwalt9258c642014-03-26 16:47:06 -07003003 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07003004 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09003005 log(String.format("UID %d attempted to %s for unowned request %s",
3006 callingUid, requestedOperation, nri));
3007 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003008 }
Erik Klineacdd6392016-07-07 16:50:58 +09003009 }
3010
3011 return nri;
3012 }
3013
Erik Kline57faba92015-11-25 12:49:38 +09003014 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003015 if (mNetworkRequests.get(nri.request) == null) {
3016 return;
Erik Kline57faba92015-11-25 12:49:38 +09003017 }
Hugo Benichicd952782017-09-20 11:20:14 +09003018 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003019 return;
3020 }
3021 if (VDBG || (DBG && nri.request.isRequest())) {
3022 log("releasing " + nri.request + " (timeout)");
3023 }
3024 handleRemoveNetworkRequest(nri);
3025 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003026 }
3027
Erik Klineacdd6392016-07-07 16:50:58 +09003028 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003029 final NetworkRequestInfo nri =
3030 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3031 if (nri == null) {
3032 return;
Erik Kline57faba92015-11-25 12:49:38 +09003033 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003034 if (VDBG || (DBG && nri.request.isRequest())) {
3035 log("releasing " + nri.request + " (release request)");
3036 }
3037 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09003038 }
Erik Klineacdd6392016-07-07 16:50:58 +09003039
Hugo Benichidba33db2017-03-23 22:40:44 +09003040 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003041 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003042 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003043
Erik Klineacdd6392016-07-07 16:50:58 +09003044 synchronized (mUidToNetworkRequestCount) {
3045 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3046 if (requests < 1) {
3047 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3048 nri.mUid);
3049 } else if (requests == 1) {
3050 mUidToNetworkRequestCount.removeAt(
3051 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3052 } else {
3053 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3054 }
3055 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003056
Erik Klineacdd6392016-07-07 16:50:58 +09003057 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3058 if (nri.request.isRequest()) {
3059 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003060 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003061 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003062 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003063 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003064 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003065 log(" Removing from current network " + nai.name() +
3066 ", leaving " + nai.numNetworkRequests() + " requests.");
3067 }
3068 // If there are still lingered requests on this network, don't tear it down,
3069 // but resume lingering instead.
3070 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003071 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003072 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3073 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003074 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003075 wasKept = true;
3076 }
Hugo Benichicd952782017-09-20 11:20:14 +09003077 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003078 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3079 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003080 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003081 }
Erik Klineacdd6392016-07-07 16:50:58 +09003082 }
3083
Erik Klineacdd6392016-07-07 16:50:58 +09003084 // Maintain the illusion. When this request arrived, we might have pretended
3085 // that a network connected to serve it, even though the network was already
3086 // connected. Now that this request has gone away, we might have to pretend
3087 // that the network disconnected. LegacyTypeTracker will generate that
3088 // phantom disconnect for this type.
3089 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3090 boolean doRemove = true;
3091 if (wasKept) {
3092 // check if any of the remaining requests for this network are for the
3093 // same legacy type - if so, don't remove the nai
3094 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3095 NetworkRequest otherRequest = nai.requestAt(i);
3096 if (otherRequest.legacyType == nri.request.legacyType &&
3097 otherRequest.isRequest()) {
3098 if (DBG) log(" still have other legacy request - leaving");
3099 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003100 }
3101 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003102 }
3103
Erik Klineacdd6392016-07-07 16:50:58 +09003104 if (doRemove) {
3105 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003106 }
3107 }
Erik Klineacdd6392016-07-07 16:50:58 +09003108
3109 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3110 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3111 nri.request);
3112 }
3113 } else {
3114 // listens don't have a singular affectedNetwork. Check all networks to see
3115 // if this listen request applies and remove it.
3116 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3117 nai.removeRequest(nri.request.requestId);
3118 if (nri.request.networkCapabilities.hasSignalStrength() &&
3119 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3120 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3121 }
3122 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003123 }
3124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003125
Lorenzo Colitti18660282016-07-04 12:55:44 +09003126 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003127 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3128 enforceConnectivityInternalPermission();
3129 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003130 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003131 }
3132
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003133 @Override
3134 public void setAvoidUnvalidated(Network network) {
3135 enforceConnectivityInternalPermission();
3136 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3137 }
3138
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003139 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3140 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3141 " accept=" + accept + " always=" + always);
3142
3143 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3144 if (nai == null) {
3145 // Nothing to do.
3146 return;
3147 }
3148
3149 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003150 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003151 return;
3152 }
3153
3154 if (!nai.networkMisc.explicitlySelected) {
3155 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3156 }
3157
3158 if (accept != nai.networkMisc.acceptUnvalidated) {
3159 int oldScore = nai.getCurrentScore();
3160 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003161 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003162 sendUpdatedScoreToFactories(nai);
3163 }
3164
3165 if (always) {
3166 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003167 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003168 }
3169
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003170 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003171 // Tell the NetworkAgent to not automatically reconnect to the network.
3172 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003173 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003174 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003175 }
3176
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003177 }
3178
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003179 private void handleSetAvoidUnvalidated(Network network) {
3180 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3181 if (nai == null || nai.lastValidated) {
3182 // Nothing to do. The network either disconnected or revalidated.
3183 return;
3184 }
3185 if (!nai.avoidUnvalidated) {
3186 int oldScore = nai.getCurrentScore();
3187 nai.avoidUnvalidated = true;
3188 rematchAllNetworksAndRequests(nai, oldScore);
3189 sendUpdatedScoreToFactories(nai);
3190 }
3191 }
3192
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003193 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003194 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003195 mHandler.sendMessageDelayed(
3196 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3197 PROMPT_UNVALIDATED_DELAY_MS);
3198 }
3199
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003200 @Override
3201 public void startCaptivePortalApp(Network network) {
3202 enforceConnectivityInternalPermission();
3203 mHandler.post(() -> {
3204 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3205 if (nai == null) return;
3206 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003207 try {
3208 nai.networkMonitor().launchCaptivePortalApp();
3209 } catch (RemoteException e) {
3210 e.rethrowFromSystemServer();
3211 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003212 });
3213 }
3214
Hugo Benichic8e9e122016-09-14 23:23:08 +00003215 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003216 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003217 }
3218
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003219 @Override
3220 public boolean getAvoidBadWifi() {
3221 if (!checkNetworkStackPermission()) {
3222 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3223 }
3224 return avoidBadWifi();
3225 }
3226
3227
Erik Kline065ab6e2016-10-02 18:02:14 +09003228 private void rematchForAvoidBadWifiUpdate() {
3229 rematchAllNetworksAndRequests(null, 0);
3230 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3231 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3232 sendUpdatedScoreToFactories(nai);
3233 }
3234 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003235 }
3236
Erik Kline065ab6e2016-10-02 18:02:14 +09003237 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003238 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003239 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003240 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003241 if (!configRestrict) {
3242 pw.println("Bad Wi-Fi avoidance: unrestricted");
3243 return;
3244 }
3245
3246 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3247 pw.increaseIndent();
3248 pw.println("Config restrict: " + configRestrict);
3249
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003250 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003251 String description;
3252 // Can't use a switch statement because strings are legal case labels, but null is not.
3253 if ("0".equals(value)) {
3254 description = "get stuck";
3255 } else if (value == null) {
3256 description = "prompt";
3257 } else if ("1".equals(value)) {
3258 description = "avoid";
3259 } else {
3260 description = value + " (?)";
3261 }
3262 pw.println("User setting: " + description);
3263 pw.println("Network overrides:");
3264 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003265 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003266 if (nai.avoidUnvalidated) {
3267 pw.println(nai.name());
3268 }
3269 }
3270 pw.decreaseIndent();
3271 pw.decreaseIndent();
3272 }
3273
lucaslind2e045e02019-01-24 15:55:30 +08003274 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003275 final String action;
3276 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003277 case LOGGED_IN:
3278 action = Settings.ACTION_WIFI_SETTINGS;
3279 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3280 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3281 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3282 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003283 case NO_INTERNET:
3284 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3285 break;
3286 case LOST_INTERNET:
3287 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3288 break;
3289 default:
3290 Slog.wtf(TAG, "Unknown notification type " + type);
3291 return;
3292 }
3293
3294 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003295 if (type != NotificationType.LOGGED_IN) {
3296 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3297 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3298 intent.setClassName("com.android.settings",
3299 "com.android.settings.wifi.WifiNoInternetDialog");
3300 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003301
3302 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3303 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3304 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3305 }
3306
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003307 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003308 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003309 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3310
3311 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3312 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003313 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003314 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003315 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3316 return;
3317 }
lucaslind2e045e02019-01-24 15:55:30 +08003318 showNetworkNotification(nai, NotificationType.NO_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003319 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003320
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003321 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3322 NetworkCapabilities nc = nai.networkCapabilities;
3323 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003324
Erik Kline065ab6e2016-10-02 18:02:14 +09003325 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003326 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003327 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003328 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003329 }
3330
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003331 @Override
3332 public int getMultipathPreference(Network network) {
3333 enforceAccessPermission();
3334
3335 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003336 if (nai != null && nai.networkCapabilities
3337 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003338 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3339 }
3340
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003341 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3342 if (networkPreference != null) {
3343 return networkPreference;
3344 }
3345
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003346 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3347 }
3348
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003349 @Override
3350 public NetworkRequest getDefaultRequest() {
3351 return mDefaultRequest;
3352 }
3353
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003354 private class InternalHandler extends Handler {
3355 public InternalHandler(Looper looper) {
3356 super(looper);
3357 }
3358
3359 @Override
3360 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003361 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003362 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003363 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003364 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003365 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003366 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003367 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003368 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003369 break;
3370 }
Jason Monkdecd2952013-10-10 14:02:51 -04003371 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003372 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003373 break;
3374 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003375 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003376 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3377 break;
3378 }
3379 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3380 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003381 break;
3382 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003383 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003384 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3385 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3386 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003387 break;
3388 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003389 case EVENT_REGISTER_NETWORK_REQUEST:
3390 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003391 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003392 break;
3393 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003394 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3395 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003396 handleRegisterNetworkRequestWithIntent(msg);
3397 break;
3398 }
Erik Kline57faba92015-11-25 12:49:38 +09003399 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3400 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3401 handleTimedOutNetworkRequest(nri);
3402 break;
3403 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003404 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3405 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3406 break;
3407 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003408 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003409 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003410 break;
3411 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003412 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003413 Network network = (Network) msg.obj;
3414 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003415 break;
3416 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003417 case EVENT_SET_AVOID_UNVALIDATED: {
3418 handleSetAvoidUnvalidated((Network) msg.obj);
3419 break;
3420 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003421 case EVENT_PROMPT_UNVALIDATED: {
3422 handlePromptUnvalidated((Network) msg.obj);
3423 break;
3424 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003425 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3426 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003427 break;
3428 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003429 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3430 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3431 mKeepaliveTracker.handleStartKeepalive(msg);
3432 break;
3433 }
3434 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3435 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3436 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3437 int slot = msg.arg1;
3438 int reason = msg.arg2;
3439 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3440 break;
3441 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003442 case EVENT_SYSTEM_READY: {
3443 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003444 // Might have been called already in handleRegisterNetworkAgent since
3445 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3446 // this several times is fine.
3447 try {
3448 nai.networkMonitor().notifySystemReady();
3449 } catch (RemoteException e) {
3450 e.rethrowFromSystemServer();
3451 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003452 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003453 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003454 break;
3455 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003456 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003457 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003458 break;
3459 }
Erik Klinea24d4592018-01-11 21:07:29 +09003460 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3461 handlePrivateDnsSettingsChanged();
3462 break;
dalyk7301aa42018-03-05 12:42:22 -05003463 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3464 handlePrivateDnsValidationUpdate(
3465 (PrivateDnsValidationUpdate) msg.obj);
3466 break;
junyulai05986c62018-08-07 19:50:45 +08003467 case EVENT_UID_RULES_CHANGED:
3468 handleUidRulesChanged(msg.arg1, msg.arg2);
3469 break;
3470 case EVENT_DATA_SAVER_CHANGED:
3471 handleRestrictBackgroundChanged(toBool(msg.arg1));
3472 break;
lucaslind2e045e02019-01-24 15:55:30 +08003473 case EVENT_TIMEOUT_NOTIFICATION:
3474 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3475 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 }
3477 }
3478 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003479
3480 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003481 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003482 public int tether(String iface, String callerPkg) {
3483 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003484 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003485 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003486 } else {
3487 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3488 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003489 }
3490
3491 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003492 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003493 public int untether(String iface, String callerPkg) {
3494 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003495
3496 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003497 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003498 } else {
3499 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3500 }
3501 }
3502
3503 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003504 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003505 public int getLastTetherError(String iface) {
3506 enforceTetherAccessPermission();
3507
3508 if (isTetheringSupported()) {
3509 return mTethering.getLastTetherError(iface);
3510 } else {
3511 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3512 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003513 }
3514
3515 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003516 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003517 public String[] getTetherableUsbRegexs() {
3518 enforceTetherAccessPermission();
3519 if (isTetheringSupported()) {
3520 return mTethering.getTetherableUsbRegexs();
3521 } else {
3522 return new String[0];
3523 }
3524 }
3525
Lorenzo Colitti18660282016-07-04 12:55:44 +09003526 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003527 public String[] getTetherableWifiRegexs() {
3528 enforceTetherAccessPermission();
3529 if (isTetheringSupported()) {
3530 return mTethering.getTetherableWifiRegexs();
3531 } else {
3532 return new String[0];
3533 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003534 }
3535
Lorenzo Colitti18660282016-07-04 12:55:44 +09003536 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003537 public String[] getTetherableBluetoothRegexs() {
3538 enforceTetherAccessPermission();
3539 if (isTetheringSupported()) {
3540 return mTethering.getTetherableBluetoothRegexs();
3541 } else {
3542 return new String[0];
3543 }
3544 }
3545
Lorenzo Colitti18660282016-07-04 12:55:44 +09003546 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003547 public int setUsbTethering(boolean enable, String callerPkg) {
3548 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003549 if (isTetheringSupported()) {
3550 return mTethering.setUsbTethering(enable);
3551 } else {
3552 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3553 }
3554 }
3555
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003556 // TODO - move iface listing, queries, etc to new module
3557 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003558 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003559 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003560 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003561 return mTethering.getTetherableIfaces();
3562 }
3563
Lorenzo Colitti18660282016-07-04 12:55:44 +09003564 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003565 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003566 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003567 return mTethering.getTetheredIfaces();
3568 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003569
Lorenzo Colitti18660282016-07-04 12:55:44 +09003570 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003571 public String[] getTetheringErroredIfaces() {
3572 enforceTetherAccessPermission();
3573 return mTethering.getErroredIfaces();
3574 }
3575
Lorenzo Colitti18660282016-07-04 12:55:44 +09003576 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003577 public String[] getTetheredDhcpRanges() {
3578 enforceConnectivityInternalPermission();
3579 return mTethering.getTetheredDhcpRanges();
3580 }
3581
Udam Saini0e94c362017-06-07 12:06:28 -07003582 @Override
3583 public boolean isTetheringSupported(String callerPkg) {
3584 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3585 return isTetheringSupported();
3586 }
3587
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003588 // if ro.tether.denied = true we default to no tethering
3589 // gservices could set the secure setting to 1 though to enable it on a build where it
3590 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003591 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003592 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3593 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3594 Settings.Global.TETHER_SUPPORTED, defaultVal));
3595 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003596 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003597
3598 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3599 boolean adminUser = false;
3600 final long token = Binder.clearCallingIdentity();
3601 try {
3602 adminUser = mUserManager.isAdminUser();
3603 } finally {
3604 Binder.restoreCallingIdentity(token);
3605 }
3606
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003607 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003608 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003609
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003610 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003611 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3612 String callerPkg) {
3613 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003614 if (!isTetheringSupported()) {
3615 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3616 return;
3617 }
3618 mTethering.startTethering(type, receiver, showProvisioningUi);
3619 }
3620
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003621 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003622 public void stopTethering(int type, String callerPkg) {
3623 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003624 mTethering.stopTethering(type);
3625 }
3626
markchienf2731272019-01-16 17:44:13 +08003627 /**
3628 * Get the latest value of the tethering entitlement check.
3629 *
3630 * Note: Allow privileged apps who have TETHER_PRIVILEGED permission to access. If it turns
3631 * out some such apps are observed to abuse this API, change to per-UID limits on this API
3632 * if it's really needed.
3633 */
3634 @Override
3635 public void getLatestTetheringEntitlementValue(int type, ResultReceiver receiver,
3636 boolean showEntitlementUi, String callerPkg) {
3637 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3638 mTethering.getLatestTetheringEntitlementValue(type, receiver, showEntitlementUi);
3639 }
3640
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003641 // Called when we lose the default network and have no replacement yet.
3642 // This will automatically be cleared after X seconds or a new default network
3643 // becomes CONNECTED, whichever happens first. The timer is started by the
3644 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003645 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003646 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003647 if (mNetTransitionWakeLock.isHeld()) {
3648 return;
3649 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003650 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003651 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3652 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003653 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003654 mWakelockLogs.log("ACQUIRE for " + forWhom);
3655 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3656 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003657 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003658
Hugo Benichi4c31b342017-03-30 23:18:10 +09003659 // Called when we gain a new default network to release the network transition wakelock in a
3660 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3661 // message is cancelled.
3662 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003663 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003664 if (!mNetTransitionWakeLock.isHeld()) {
3665 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003666 }
3667 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003668 // Cancel self timeout on wakelock hold.
3669 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3670 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3671 mHandler.sendMessageDelayed(msg, 1000);
3672 }
3673
3674 // Called when either message of ensureNetworkTransitionWakelock or
3675 // scheduleReleaseNetworkTransitionWakelock is processed.
3676 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3677 String event = eventName(eventId);
3678 synchronized (this) {
3679 if (!mNetTransitionWakeLock.isHeld()) {
3680 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3681 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3682 return;
3683 }
3684 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003685 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3686 mTotalWakelockDurationMs += lockDuration;
3687 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3688 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003689 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003690 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003691 }
3692
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003693 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003694 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003695 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003696 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003697 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003698 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003699 }
3700
Lorenzo Colitti18660282016-07-04 12:55:44 +09003701 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003702 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003703 enforceAccessPermission();
3704 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003705 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003706 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003707 mHandler.sendMessage(
3708 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3709 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003710
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003711 private void handleReportNetworkConnectivity(
3712 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003713 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003714 if (network == null) {
3715 nai = getDefaultNetwork();
3716 } else {
3717 nai = getNetworkAgentInfoForNetwork(network);
3718 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003719 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3720 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3721 return;
3722 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003723 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003724 if (hasConnectivity == nai.lastValidated) {
3725 return;
3726 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003727 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003728 int netid = nai.network.netId;
3729 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003730 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003731 // Validating a network that has not yet connected could result in a call to
3732 // rematchNetworkAndRequests() which is not meant to work on such networks.
3733 if (!nai.everConnected) {
3734 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003735 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003736 LinkProperties lp = getLinkProperties(nai);
3737 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3738 return;
3739 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003740 try {
3741 nai.networkMonitor().forceReevaluation(uid);
3742 } catch (RemoteException e) {
3743 e.rethrowFromSystemServer();
3744 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003745 }
3746
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003747 /**
3748 * Returns information about the proxy a certain network is using. If given a null network, it
3749 * it will return the proxy for the bound network for the caller app or the default proxy if
3750 * none.
3751 *
3752 * @param network the network we want to get the proxy information for.
3753 * @return Proxy information if a network has a proxy configured, or otherwise null.
3754 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09003755 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003756 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003757 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003758 if (globalProxy != null) return globalProxy;
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003759 if (network == null) {
3760 // Get the network associated with the calling UID.
3761 final Network activeNetwork = getActiveNetworkForUidInternal(Binder.getCallingUid(),
3762 true);
3763 if (activeNetwork == null) {
3764 return null;
3765 }
3766 return getLinkPropertiesProxyInfo(activeNetwork);
3767 } else if (queryUserAccess(Binder.getCallingUid(), network.netId)) {
3768 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3769 // caller may not have.
3770 return getLinkPropertiesProxyInfo(network);
3771 }
3772 // No proxy info available if the calling UID does not have network access.
3773 return null;
3774 }
3775
3776 @VisibleForTesting
3777 protected boolean queryUserAccess(int uid, int netId) {
3778 return NetworkUtils.queryUserAccess(uid, netId);
3779 }
3780
3781 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensencee9b512015-05-06 07:32:40 -04003782 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3783 if (nai == null) return null;
3784 synchronized (nai) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003785 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
3786 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensencee9b512015-05-06 07:32:40 -04003787 }
3788 }
3789
Chalard Jean3c443fc2018-06-07 18:37:59 +09003790 @Override
3791 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003792 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003793 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003794 }
3795
Chalard Jean5afbc832018-06-07 18:02:37 +09003796 @Override
3797 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003798 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003799 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003800 }
3801
Jason Monk207900c2014-04-25 15:00:09 -04003802 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003803 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003804 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003805 proxy = null;
3806 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003807 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003808 }
3809
Irina Dumitrescu044a4362018-12-05 16:19:47 +00003810 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
3811 // when any network changes proxy.
3812 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
3813 // multi-network world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003814 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003815 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3816 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3817
Chalard Jean4949dd72018-06-07 17:41:29 +09003818 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09003819 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05003820 }
3821 }
3822
Robert Greenwalt434203a2010-10-11 16:00:27 -07003823 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003824 final private HashMap<Uri, Integer> mUriEventMap;
3825 final private Context mContext;
3826 final private Handler mHandler;
3827
3828 SettingsObserver(Context context, Handler handler) {
3829 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003830 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003831 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003832 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003833 }
3834
Erik Klineda4bfa82015-04-30 12:58:40 +09003835 void observe(Uri uri, int what) {
3836 mUriEventMap.put(uri, what);
3837 final ContentResolver resolver = mContext.getContentResolver();
3838 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003839 }
3840
3841 @Override
3842 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003843 Slog.wtf(TAG, "Should never be reached.");
3844 }
3845
3846 @Override
3847 public void onChange(boolean selfChange, Uri uri) {
3848 final Integer what = mUriEventMap.get(uri);
3849 if (what != null) {
3850 mHandler.obtainMessage(what.intValue()).sendToTarget();
3851 } else {
3852 loge("No matching event to send for URI=" + uri);
3853 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003854 }
3855 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003856
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003857 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003858 Slog.d(TAG, s);
3859 }
3860
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003861 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003862 Slog.e(TAG, s);
3863 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003864
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003865 private static void loge(String s, Throwable t) {
3866 Slog.e(TAG, s, t);
3867 }
3868
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003869 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003870 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003871 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3872 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3873 *
3874 * @param oldPackage Package name of the application which currently controls VPN, which will
3875 * be replaced. If there is no such application, this should should either be
3876 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3877 * @param newPackage Package name of the application which should gain control of VPN, or
3878 * {@code null} to disable.
3879 * @param userId User for whom to prepare the new VPN.
3880 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003881 * @hide
3882 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003883 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003884 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3885 int userId) {
3886 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003887
Hugo Benichi20035e02017-04-26 14:53:28 +09003888 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003889 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003890 Vpn vpn = mVpns.get(userId);
3891 if (vpn != null) {
3892 return vpn.prepare(oldPackage, newPackage);
3893 } else {
3894 return false;
3895 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003896 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003897 }
3898
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003899 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003900 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3901 * This method is used by system-privileged apps.
3902 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3903 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3904 *
3905 * @param packageName The package for which authorization state should change.
3906 * @param userId User for whom {@code packageName} is installed.
3907 * @param authorized {@code true} if this app should be able to start a VPN connection without
3908 * explicit user approval, {@code false} if not.
3909 *
Jeff Davidson05542602014-08-11 14:07:27 -07003910 * @hide
3911 */
3912 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003913 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3914 enforceCrossUserPermission(userId);
3915
Hugo Benichi20035e02017-04-26 14:53:28 +09003916 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003917 Vpn vpn = mVpns.get(userId);
3918 if (vpn != null) {
3919 vpn.setPackageAuthorization(packageName, authorized);
3920 }
Jeff Davidson05542602014-08-11 14:07:27 -07003921 }
3922 }
3923
3924 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003925 * Configure a TUN interface and return its file descriptor. Parameters
3926 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003927 * and not available in ConnectivityManager. Permissions are checked in
3928 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003929 * @hide
3930 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003931 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003932 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003933 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003934 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003935 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003936 return mVpns.get(user).establish(config);
3937 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003938 }
3939
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003940 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003941 * Start legacy VPN, controlling native daemons as needed. Creates a
3942 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003943 */
3944 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003945 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003946 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003947 final LinkProperties egress = getActiveLinkProperties();
3948 if (egress == null) {
3949 throw new IllegalStateException("Missing active network connection");
3950 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003951 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003952 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003953 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3954 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003955 }
3956
3957 /**
3958 * Return the information of the ongoing legacy VPN. This method is used
3959 * by VpnSettings and not available in ConnectivityManager. Permissions
3960 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003961 */
3962 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003963 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3964 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003965
Hugo Benichi20035e02017-04-26 14:53:28 +09003966 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003967 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003968 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003969 }
3970
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003971 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003972 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3973 * and not available in ConnectivityManager.
3974 */
3975 @Override
3976 public VpnInfo[] getAllVpnInfo() {
3977 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003978 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003979 if (mLockdownEnabled) {
3980 return new VpnInfo[0];
3981 }
3982
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003983 List<VpnInfo> infoList = new ArrayList<>();
3984 for (int i = 0; i < mVpns.size(); i++) {
3985 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3986 if (info != null) {
3987 infoList.add(info);
3988 }
3989 }
3990 return infoList.toArray(new VpnInfo[infoList.size()]);
3991 }
3992 }
3993
3994 /**
3995 * @return VPN information for accounting, or null if we can't retrieve all required
3996 * information, e.g primary underlying iface.
3997 */
3998 @Nullable
3999 private VpnInfo createVpnInfo(Vpn vpn) {
4000 VpnInfo info = vpn.getVpnInfo();
4001 if (info == null) {
4002 return null;
4003 }
4004 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
4005 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
4006 // the underlyingNetworks list.
4007 if (underlyingNetworks == null) {
4008 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
4009 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
4010 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
4011 }
4012 } else if (underlyingNetworks.length > 0) {
4013 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
4014 if (linkProperties != null) {
4015 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
4016 }
4017 }
4018 return info.primaryUnderlyingIface == null ? null : info;
4019 }
4020
4021 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01004022 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
4023 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004024 * Permissions are checked in Vpn class.
4025 * @hide
4026 */
4027 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01004028 public VpnConfig getVpnConfig(int userId) {
4029 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004030 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07004031 Vpn vpn = mVpns.get(userId);
4032 if (vpn != null) {
4033 return vpn.getVpnConfig();
4034 } else {
4035 return null;
4036 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07004037 }
4038 }
4039
Chalard Jean6b65ec72018-05-18 22:02:56 +09004040 /**
4041 * Ask all VPN objects to recompute and update their capabilities.
4042 *
4043 * When underlying networks change, VPNs may have to update capabilities to reflect things
4044 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4045 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4046 * handler thread through their agent, this is asynchronous. When the capabilities objects
4047 * are computed they will be up-to-date as they are computed synchronously from here and
4048 * this is running on the ConnectivityService thread.
4049 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
4050 */
4051 private void updateAllVpnsCapabilities() {
4052 synchronized (mVpns) {
4053 for (int i = 0; i < mVpns.size(); i++) {
4054 final Vpn vpn = mVpns.valueAt(i);
4055 vpn.updateCapabilities();
4056 }
4057 }
4058 }
4059
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004060 @Override
4061 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004062 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4063 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4064 return false;
4065 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004066
Hugo Benichi69744342017-11-27 10:57:16 +09004067 synchronized (mVpns) {
4068 // Tear down existing lockdown if profile was removed
4069 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4070 if (mLockdownEnabled) {
4071 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4072 if (profileTag == null) {
4073 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4074 return false;
4075 }
4076 String profileName = new String(profileTag);
4077 final VpnProfile profile = VpnProfile.decode(
4078 profileName, mKeyStore.get(Credentials.VPN + profileName));
4079 if (profile == null) {
4080 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4081 setLockdownTracker(null);
4082 return true;
4083 }
4084 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004085 Vpn vpn = mVpns.get(user);
4086 if (vpn == null) {
4087 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4088 return false;
4089 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004090 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004091 } else {
4092 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004093 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004094 }
4095
4096 return true;
4097 }
4098
4099 /**
4100 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4101 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4102 */
Hugo Benichi69744342017-11-27 10:57:16 +09004103 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004104 private void setLockdownTracker(LockdownVpnTracker tracker) {
4105 // Shutdown any existing tracker
4106 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004107 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4108 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004109 mLockdownTracker = null;
4110 if (existing != null) {
4111 existing.shutdown();
4112 }
4113
Robin Leec3736bc2017-03-10 16:19:54 +00004114 if (tracker != null) {
4115 mLockdownTracker = tracker;
4116 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004117 }
4118 }
4119
Hugo Benichi69744342017-11-27 10:57:16 +09004120 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004121 private void throwIfLockdownEnabled() {
4122 if (mLockdownEnabled) {
4123 throw new IllegalStateException("Unavailable in lockdown mode");
4124 }
4125 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004126
Robin Lee244ce8e2016-01-05 18:03:46 +00004127 /**
Robin Lee17e61832016-05-09 13:46:28 +01004128 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4129 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004130 *
Robin Lee17e61832016-05-09 13:46:28 +01004131 * @return {@code true} if the service was started, the service was already connected, or there
4132 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004133 */
Robin Lee17e61832016-05-09 13:46:28 +01004134 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004135 synchronized (mVpns) {
4136 Vpn vpn = mVpns.get(userId);
4137 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004138 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004139 // exists already.
4140 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4141 return false;
4142 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004143
Robin Lee812800c2016-05-13 15:38:08 +01004144 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004145 }
4146 }
4147
4148 @Override
Charles He36738632017-05-15 17:07:18 +01004149 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4150 enforceSettingsPermission();
4151 enforceCrossUserPermission(userId);
4152
4153 synchronized (mVpns) {
4154 Vpn vpn = mVpns.get(userId);
4155 if (vpn == null) {
4156 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4157 return false;
4158 }
4159 return vpn.isAlwaysOnPackageSupported(packageName);
4160 }
4161 }
4162
4163 @Override
Dan Albertee8e6a02019-01-24 21:05:39 +00004164 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
4165 enforceConnectivityInternalPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004166 enforceCrossUserPermission(userId);
4167
Robin Lee244ce8e2016-01-05 18:03:46 +00004168 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004169 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4170 if (LockdownVpnTracker.isEnabled()) {
4171 return false;
4172 }
4173
Robin Lee244ce8e2016-01-05 18:03:46 +00004174 Vpn vpn = mVpns.get(userId);
4175 if (vpn == null) {
4176 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4177 return false;
4178 }
Dan Albertee8e6a02019-01-24 21:05:39 +00004179 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004180 return false;
4181 }
Robin Lee17e61832016-05-09 13:46:28 +01004182 if (!startAlwaysOnVpn(userId)) {
Dan Albertee8e6a02019-01-24 21:05:39 +00004183 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00004184 return false;
4185 }
4186 }
4187 return true;
4188 }
4189
4190 @Override
4191 public String getAlwaysOnVpnPackage(int userId) {
Dan Albertee8e6a02019-01-24 21:05:39 +00004192 enforceConnectivityInternalPermission();
Robin Lee244ce8e2016-01-05 18:03:46 +00004193 enforceCrossUserPermission(userId);
4194
4195 synchronized (mVpns) {
4196 Vpn vpn = mVpns.get(userId);
4197 if (vpn == null) {
4198 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4199 return null;
4200 }
4201 return vpn.getAlwaysOnPackage();
4202 }
4203 }
4204
Wink Savilleab9321d2013-06-29 21:10:57 -07004205 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004206 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004207 // TODO: Remove? Any reason to trigger a provisioning check?
4208 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004209 }
4210
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004211 /** Location to an updatable file listing carrier provisioning urls.
4212 * An example:
4213 *
4214 * <?xml version="1.0" encoding="utf-8"?>
4215 * <provisioningUrls>
4216 * <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 -07004217 * </provisioningUrls>
4218 */
4219 private static final String PROVISIONING_URL_PATH =
4220 "/data/misc/radio/provisioning_urls.xml";
4221 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004222
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004223 /** XML tag for root element. */
4224 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4225 /** XML tag for individual url */
4226 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004227 /** XML attribute for mcc */
4228 private static final String ATTR_MCC = "mcc";
4229 /** XML attribute for mnc */
4230 private static final String ATTR_MNC = "mnc";
4231
Paul Jensen434dde82015-06-11 09:43:30 -04004232 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004233 FileReader fileReader = null;
4234 XmlPullParser parser = null;
4235 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004236
4237 try {
4238 fileReader = new FileReader(mProvisioningUrlFile);
4239 parser = Xml.newPullParser();
4240 parser.setInput(fileReader);
4241 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4242
4243 while (true) {
4244 XmlUtils.nextElement(parser);
4245
4246 String element = parser.getName();
4247 if (element == null) break;
4248
Paul Jensen434dde82015-06-11 09:43:30 -04004249 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004250 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4251 try {
4252 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4253 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4254 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4255 parser.next();
4256 if (parser.getEventType() == XmlPullParser.TEXT) {
4257 return parser.getText();
4258 }
4259 }
4260 }
4261 } catch (NumberFormatException e) {
4262 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4263 }
4264 }
4265 }
4266 return null;
4267 } catch (FileNotFoundException e) {
4268 loge("Carrier Provisioning Urls file not found");
4269 } catch (XmlPullParserException e) {
4270 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4271 } catch (IOException e) {
4272 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4273 } finally {
4274 if (fileReader != null) {
4275 try {
4276 fileReader.close();
4277 } catch (IOException e) {}
4278 }
4279 }
4280 return null;
4281 }
4282
Wink Saville42d4f082013-07-20 20:31:59 -07004283 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004284 public String getMobileProvisioningUrl() {
4285 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004286 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004287 if (TextUtils.isEmpty(url)) {
4288 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004289 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004290 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004291 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004292 }
Wink Saville8cf35602013-07-10 23:00:07 -07004293 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004294 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004295 String phoneNumber = mTelephonyManager.getLine1Number();
4296 if (TextUtils.isEmpty(phoneNumber)) {
4297 phoneNumber = "0000000000";
4298 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004299 url = String.format(url,
4300 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4301 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004302 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004303 }
4304
Wink Savilleab9321d2013-06-29 21:10:57 -07004305 return url;
4306 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004307
Wink Saville948282b2013-08-29 08:55:16 -07004308 @Override
4309 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004310 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004311 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004312 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4313 return;
4314 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004315 final long ident = Binder.clearCallingIdentity();
4316 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004317 // Concatenate the range of types onto the range of NetIDs.
4318 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4319 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004320 } finally {
4321 Binder.restoreCallingIdentity(ident);
4322 }
Wink Saville948282b2013-08-29 08:55:16 -07004323 }
Wink Saville7788c612013-08-29 14:57:08 -07004324
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004325 @Override
4326 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004327 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004328 final long ident = Binder.clearCallingIdentity();
4329 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004330 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004331 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004332 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4333 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004334 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004335 } finally {
4336 Binder.restoreCallingIdentity(ident);
4337 }
4338 }
4339
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004340 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004341 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004342 Vpn userVpn = mVpns.get(userId);
4343 if (userVpn != null) {
4344 loge("Starting user already has a VPN");
4345 return;
4346 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004347 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004348 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004349 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4350 updateLockdownVpn();
4351 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004352 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004353 }
4354
4355 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004356 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004357 Vpn userVpn = mVpns.get(userId);
4358 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004359 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004360 return;
4361 }
Robin Lee17e61832016-05-09 13:46:28 +01004362 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004363 mVpns.delete(userId);
4364 }
4365 }
4366
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004367 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004368 mPermissionMonitor.onUserAdded(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004369 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004370 final int vpnsSize = mVpns.size();
4371 for (int i = 0; i < vpnsSize; i++) {
4372 Vpn vpn = mVpns.valueAt(i);
4373 vpn.onUserAdded(userId);
4374 }
4375 }
4376 }
4377
4378 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004379 mPermissionMonitor.onUserRemoved(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004380 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004381 final int vpnsSize = mVpns.size();
4382 for (int i = 0; i < vpnsSize; i++) {
4383 Vpn vpn = mVpns.valueAt(i);
4384 vpn.onUserRemoved(userId);
4385 }
4386 }
4387 }
4388
junyulai2454b692018-11-01 17:16:31 +08004389 private void onPackageAdded(String packageName, int uid) {
4390 if (TextUtils.isEmpty(packageName) || uid < 0) {
4391 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4392 return;
4393 }
4394 mPermissionMonitor.onPackageAdded(packageName, uid);
4395 }
4396
junyulaiefb04d32018-11-12 22:39:30 +08004397 private void onPackageReplaced(String packageName, int uid) {
4398 if (TextUtils.isEmpty(packageName) || uid < 0) {
4399 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4400 return;
4401 }
4402 final int userId = UserHandle.getUserId(uid);
4403 synchronized (mVpns) {
4404 final Vpn vpn = mVpns.get(userId);
4405 if (vpn == null) {
4406 return;
4407 }
4408 // Legacy always-on VPN won't be affected since the package name is not set.
4409 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4410 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4411 + userId);
4412 vpn.startAlwaysOnVpn();
4413 }
4414 }
4415 }
4416
4417 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004418 if (TextUtils.isEmpty(packageName) || uid < 0) {
4419 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4420 return;
4421 }
4422 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004423
4424 final int userId = UserHandle.getUserId(uid);
4425 synchronized (mVpns) {
4426 final Vpn vpn = mVpns.get(userId);
4427 if (vpn == null) {
4428 return;
4429 }
4430 // Legacy always-on VPN won't be affected since the package name is not set.
4431 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4432 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4433 + userId);
Dan Albertee8e6a02019-01-24 21:05:39 +00004434 vpn.setAlwaysOnPackage(null, false);
junyulaiefb04d32018-11-12 22:39:30 +08004435 }
4436 }
junyulai2454b692018-11-01 17:16:31 +08004437 }
4438
Robin Lee89e7a692016-02-29 14:38:17 +00004439 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004440 synchronized (mVpns) {
4441 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4442 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4443 updateLockdownVpn();
4444 } else {
4445 startAlwaysOnVpn(userId);
4446 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004447 }
4448 }
4449
junyulai2454b692018-11-01 17:16:31 +08004450 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004451 @Override
4452 public void onReceive(Context context, Intent intent) {
4453 final String action = intent.getAction();
4454 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004455 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4456 final Uri packageData = intent.getData();
4457 final String packageName =
4458 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004459 if (userId == UserHandle.USER_NULL) return;
4460
Robin Lee323f29d2016-05-04 16:38:06 +01004461 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004462 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004463 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004464 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004465 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4466 onUserAdded(userId);
4467 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4468 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004469 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4470 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004471 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4472 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004473 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4474 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004475 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004476 final boolean isReplacing = intent.getBooleanExtra(
4477 Intent.EXTRA_REPLACING, false);
4478 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004479 }
4480 }
4481 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004482
Robin Lee95204e02017-01-27 11:59:22 +00004483 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4484 @Override
4485 public void onReceive(Context context, Intent intent) {
4486 // Try creating lockdown tracker, since user present usually means
4487 // unlocked keystore.
4488 updateLockdownVpn();
4489 mContext.unregisterReceiver(this);
4490 }
4491 };
4492
Chalard Jean4133a122018-06-04 13:33:12 +09004493 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4494 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004495
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004496 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4497 // Map from UID to number of NetworkRequests that UID has filed.
4498 @GuardedBy("mUidToNetworkRequestCount")
4499 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4500
Robert Greenwalta67be032014-05-16 15:49:14 -07004501 private static class NetworkFactoryInfo {
4502 public final String name;
4503 public final Messenger messenger;
4504 public final AsyncChannel asyncChannel;
4505
4506 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4507 this.name = name;
4508 this.messenger = messenger;
4509 this.asyncChannel = asyncChannel;
4510 }
4511 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004512
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004513 private void ensureNetworkRequestHasType(NetworkRequest request) {
4514 if (request.type == NetworkRequest.Type.NONE) {
4515 throw new IllegalArgumentException(
4516 "All NetworkRequests in ConnectivityService must have a type");
4517 }
4518 }
4519
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004520 /**
4521 * Tracks info about the requester.
4522 * Also used to notice when the calling process dies so we can self-expire
4523 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004524 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004525 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004526 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004527 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004528 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004529 final int mPid;
4530 final int mUid;
4531 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004532
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004533 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004534 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004535 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004536 mPendingIntent = pi;
4537 messenger = null;
4538 mBinder = null;
4539 mPid = getCallingPid();
4540 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004541 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004542 }
4543
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004544 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004545 super();
4546 messenger = m;
4547 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004548 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004549 mBinder = binder;
4550 mPid = getCallingPid();
4551 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004552 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004553 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004554
4555 try {
4556 mBinder.linkToDeath(this, 0);
4557 } catch (RemoteException e) {
4558 binderDied();
4559 }
4560 }
4561
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004562 private void enforceRequestCountLimit() {
4563 synchronized (mUidToNetworkRequestCount) {
4564 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4565 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004566 throw new ServiceSpecificException(
4567 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004568 }
4569 mUidToNetworkRequestCount.put(mUid, networkRequests);
4570 }
4571 }
4572
Robert Greenwalt9258c642014-03-26 16:47:06 -07004573 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004574 if (mBinder != null) {
4575 mBinder.unlinkToDeath(this, 0);
4576 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004577 }
4578
4579 public void binderDied() {
4580 log("ConnectivityService NetworkRequestInfo binderDied(" +
4581 request + ", " + mBinder + ")");
4582 releaseNetworkRequest(request);
4583 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004584
4585 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004586 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004587 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004588 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004589 }
4590
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004591 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4592 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4593 if (badCapability != null) {
4594 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004595 }
4596 }
4597
Chalard Jeanb03a6222018-04-11 21:09:10 +09004598 // This checks that the passed capabilities either do not request a specific SSID, or the
4599 // calling app has permission to do so.
4600 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4601 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004602 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004603 throw new SecurityException("Insufficient permissions to request a specific SSID");
4604 }
4605 }
4606
Erik Kline9d598e12015-07-13 16:37:51 +09004607 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004608 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004609 synchronized (nai) {
4610 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4611 if (nri.request.networkCapabilities.hasSignalStrength() &&
4612 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4613 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4614 }
4615 }
4616 }
Chalard Jean4133a122018-06-04 13:33:12 +09004617 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004618 }
4619
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004620 private void updateSignalStrengthThresholds(
4621 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4622 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004623 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004624 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4625
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004626 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004627 String detail;
4628 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4629 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4630 } else {
4631 detail = reason;
4632 }
4633 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4634 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4635 }
4636
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004637 nai.asyncChannel.sendMessage(
4638 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004639 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004640 }
4641
Etan Cohen859748f2017-04-03 17:42:34 -07004642 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4643 if (nc == null) {
4644 return;
4645 }
4646 NetworkSpecifier ns = nc.getNetworkSpecifier();
4647 if (ns == null) {
4648 return;
4649 }
4650 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4651 ns.assertValidFromUid(Binder.getCallingUid());
4652 }
4653
Robert Greenwalt9258c642014-03-26 16:47:06 -07004654 @Override
4655 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004656 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004657 final NetworkRequest.Type type = (networkCapabilities == null)
4658 ? NetworkRequest.Type.TRACK_DEFAULT
4659 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004660 // If the requested networkCapabilities is null, take them instead from
4661 // the default network request. This allows callers to keep track of
4662 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004663 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004664 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004665 enforceAccessPermission();
4666 } else {
4667 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4668 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004669 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4670 // of the app when the request is filed, but we never change the request if the app
4671 // changes network state. http://b/29964605
4672 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004673 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004674 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004675 ensureSufficientPermissionsForRequest(networkCapabilities,
4676 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004677 // Set the UID range for this request to the single UID of the requester, or to an empty
4678 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004679 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4680 // are no visible methods to set the UIDs, an app could use reflection to try and get
4681 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004682 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004683
Etan Cohenba07c8c2017-02-05 10:42:27 -08004684 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004685 throw new IllegalArgumentException("Bad timeout specified");
4686 }
Etan Cohen859748f2017-04-03 17:42:34 -07004687 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004688
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004689 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004690 nextNetworkRequestId(), type);
4691 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004692 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004693
4694 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004695 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004696 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004697 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004698 }
4699 return networkRequest;
4700 }
4701
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004702 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004703 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004704 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004705 } else {
4706 enforceChangePermission();
4707 }
4708 }
4709
fenglub15e72b2015-03-20 11:29:56 -07004710 @Override
fengludb571472015-04-21 17:12:05 -07004711 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004712 enforceAccessPermission();
4713 NetworkAgentInfo nai = null;
4714 if (network == null) {
4715 return false;
4716 }
4717 synchronized (mNetworkForNetId) {
4718 nai = mNetworkForNetId.get(network.netId);
4719 }
4720 if (nai != null) {
4721 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004722 synchronized (mBandwidthRequests) {
4723 final int uid = Binder.getCallingUid();
4724 Integer uidReqs = mBandwidthRequests.get(uid);
4725 if (uidReqs == null) {
4726 uidReqs = new Integer(0);
4727 }
4728 mBandwidthRequests.put(uid, ++uidReqs);
4729 }
fenglub15e72b2015-03-20 11:29:56 -07004730 return true;
4731 }
4732 return false;
4733 }
4734
Felipe Lemeee27cab2016-06-20 16:36:29 -07004735 private boolean isSystem(int uid) {
4736 return uid < Process.FIRST_APPLICATION_UID;
4737 }
fenglub15e72b2015-03-20 11:29:56 -07004738
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004739 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004740 final int uid = Binder.getCallingUid();
4741 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004742 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004743 return;
4744 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004745 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4746 // Policy already enforced.
4747 return;
4748 }
4749 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4750 // If UID is restricted, don't allow them to bring up metered APNs.
4751 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004752 }
4753 }
4754
Robert Greenwalt9258c642014-03-26 16:47:06 -07004755 @Override
4756 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4757 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004758 checkNotNull(operation, "PendingIntent cannot be null.");
4759 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4760 enforceNetworkRequestPermissions(networkCapabilities);
4761 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004762 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004763 ensureSufficientPermissionsForRequest(networkCapabilities,
4764 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004765 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004766 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004767
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004768 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004769 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4770 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004771 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004772 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4773 nri));
4774 return networkRequest;
4775 }
4776
Jeremy Joslin79294842014-12-03 17:15:28 -08004777 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4778 mHandler.sendMessageDelayed(
4779 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4780 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4781 }
4782
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004783 @Override
4784 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004785 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004786 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4787 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004788 }
4789
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004790 // In order to implement the compatibility measure for pre-M apps that call
4791 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4792 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4793 // This ensures it has permission to do so.
4794 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4795 if (nc == null) {
4796 return false;
4797 }
4798 int[] transportTypes = nc.getTransportTypes();
4799 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4800 return false;
4801 }
4802 try {
4803 mContext.enforceCallingOrSelfPermission(
4804 android.Manifest.permission.ACCESS_WIFI_STATE,
4805 "ConnectivityService");
4806 } catch (SecurityException e) {
4807 return false;
4808 }
4809 return true;
4810 }
4811
Robert Greenwalt9258c642014-03-26 16:47:06 -07004812 @Override
4813 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4814 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004815 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4816 enforceAccessPermission();
4817 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004818
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004819 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004820 ensureSufficientPermissionsForRequest(networkCapabilities,
4821 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004822 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004823 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4824 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4825 // onLost and onAvailable callbacks when networks move in and out of the background.
4826 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4827 // can't request networks.
4828 restrictBackgroundRequestForCaller(nc);
4829 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004830
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004831 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004832 NetworkRequest.Type.LISTEN);
4833 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004834 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004835
4836 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4837 return networkRequest;
4838 }
4839
4840 @Override
4841 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4842 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004843 checkNotNull(operation, "PendingIntent cannot be null.");
4844 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4845 enforceAccessPermission();
4846 }
Etan Cohen859748f2017-04-03 17:42:34 -07004847 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004848 ensureSufficientPermissionsForRequest(networkCapabilities,
4849 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004850
Chalard Jeandda156a2018-01-10 21:19:32 +09004851 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004852 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004853
4854 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004855 NetworkRequest.Type.LISTEN);
4856 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004857 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004858
4859 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004860 }
4861
Erik Klineacdd6392016-07-07 16:50:58 +09004862 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004863 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004864 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004865 mHandler.sendMessage(mHandler.obtainMessage(
4866 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004867 }
4868
4869 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004870 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004871 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004872 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4873 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004874 }
4875
Robert Greenwalta67be032014-05-16 15:49:14 -07004876 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004877 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004878 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4879 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4880 }
4881
4882 @Override
4883 public void unregisterNetworkFactory(Messenger messenger) {
4884 enforceConnectivityInternalPermission();
4885 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4886 }
4887
4888 private void handleUnregisterNetworkFactory(Messenger messenger) {
4889 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4890 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004891 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004892 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004893 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004894 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004895 }
4896
Robert Greenwalt7b816022014-04-18 15:25:25 -07004897 /**
4898 * NetworkAgentInfo supporting a request by requestId.
4899 * These have already been vetted (their Capabilities satisfy the request)
4900 * and the are the highest scored network available.
4901 * the are keyed off the Requests requestId.
4902 */
Hugo Benichicd952782017-09-20 11:20:14 +09004903 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4904 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004905 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004906
Paul Jensen31a94f42015-02-13 14:18:39 -05004907 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4908 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004909 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004910 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4911 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4912 // there may not be a strict 1:1 correlation between the two.
4913 @GuardedBy("mNetworkForNetId")
4914 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004915
Robert Greenwalt7b816022014-04-18 15:25:25 -07004916 // NetworkAgentInfo keyed off its connecting messenger
4917 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004918 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004919 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004920
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004921 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004922 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004923
Paul Jensen2c311d62014-11-17 12:34:51 -05004924 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004926
Erik Klineda4bfa82015-04-30 12:58:40 +09004927 // Request used to optionally keep mobile data active even when higher
4928 // priority networks like Wi-Fi are active.
4929 private final NetworkRequest mDefaultMobileDataRequest;
4930
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004931 // Request used to optionally keep wifi data active even when higher
4932 // priority networks like ethernet are active.
4933 private final NetworkRequest mDefaultWifiRequest;
4934
Hugo Benichicd952782017-09-20 11:20:14 +09004935 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4936 synchronized (mNetworkForRequestId) {
4937 return mNetworkForRequestId.get(requestId);
4938 }
4939 }
4940
4941 private void clearNetworkForRequest(int requestId) {
4942 synchronized (mNetworkForRequestId) {
4943 mNetworkForRequestId.remove(requestId);
4944 }
4945 }
4946
4947 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4948 synchronized (mNetworkForRequestId) {
4949 mNetworkForRequestId.put(requestId, nai);
4950 }
4951 }
4952
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004953 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004954 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004955 }
4956
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004957 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004958 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004959 }
4960
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004961 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4962 return nri.request.requestId == mDefaultRequest.requestId;
4963 }
4964
Paul Jensen31a94f42015-02-13 14:18:39 -05004965 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004966 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004967 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004968 enforceConnectivityInternalPermission();
4969
Rubin Xu1bb5c082017-09-05 18:40:49 +01004970 LinkProperties lp = new LinkProperties(linkProperties);
4971 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004972 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4973 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004974 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004975 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004976 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Lorenzo Colitti9307ca22019-01-12 01:54:23 +09004977 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004978 // Make sure the network capabilities reflect what the agent info says.
4979 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09004980 final String extraInfo = networkInfo.getExtraInfo();
4981 final String name = TextUtils.isEmpty(extraInfo)
4982 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004983 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004984 final long token = Binder.clearCallingIdentity();
4985 try {
4986 mContext.getSystemService(NetworkStack.class)
4987 .makeNetworkMonitor(nai.network, name, new NetworkMonitorCallbacks(nai));
4988 } finally {
4989 Binder.restoreCallingIdentity(token);
4990 }
4991 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
4992 // If the network disconnects or sends any other event before that, messages are deferred by
4993 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
4994 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05004995 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004996 }
4997
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004998 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
4999 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005000 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09005001 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005002 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09005003 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05005004 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005005 synchronized (this) {
5006 if (mSystemReady) {
5007 try {
5008 networkMonitor.notifySystemReady();
5009 } catch (RemoteException e) {
5010 e.rethrowFromSystemServer();
5011 }
5012 }
5013 }
5014
5015 try {
5016 networkMonitor.start();
5017 } catch (RemoteException e) {
5018 e.rethrowFromSystemServer();
5019 }
Erik Klinee5dac902018-03-04 21:01:01 +09005020 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
5021 NetworkInfo networkInfo = nai.networkInfo;
5022 nai.networkInfo = null;
5023 updateNetworkInfo(nai, networkInfo);
5024 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005025 }
5026
lucaslin25a4ec32018-11-28 12:51:55 +08005027 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
5028 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005029 int netId = networkAgent.network.netId;
5030
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005031 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
5032 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09005033 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08005034 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09005035 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09005036
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005037 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005038 updateMtu(newLp, oldLp);
5039 // TODO - figure out what to do for clat
5040// for (LinkProperties lp : newLp.getStackedLinks()) {
5041// updateMtu(lp, null);
5042// }
lucaslin041a1af2018-11-28 19:27:52 +08005043 if (isDefaultNetwork(networkAgent)) {
5044 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5045 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005046
Erik Kline94887872016-04-05 13:30:49 +09005047 updateRoutes(newLp, oldLp, netId);
5048 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005049 // Make sure LinkProperties represents the latest private DNS status.
5050 // This does not need to be done before updateDnses because the
5051 // LinkProperties are not the source of the private DNS configuration.
5052 // updateDnses will fetch the private DNS configuration from DnsManager.
5053 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005054
Paul Jensene0bef712014-12-10 15:12:18 -05005055 if (isDefaultNetwork(networkAgent)) {
5056 handleApplyDefaultProxy(newLp.getHttpProxy());
5057 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005058 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005059 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005060 // TODO - move this check to cover the whole function
5061 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005062 synchronized (networkAgent) {
5063 networkAgent.linkProperties = newLp;
5064 }
lucaslin25a4ec32018-11-28 12:51:55 +08005065 // Start or stop clat accordingly to network state.
5066 networkAgent.updateClat(mNMS);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005067 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005068 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005069 try {
5070 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5071 } catch (RemoteException e) {
5072 e.rethrowFromSystemServer();
5073 }
lucaslin25a4ec32018-11-28 12:51:55 +08005074 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5075 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005076 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005077
5078 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005079 }
5080
Joel Scherpelz668370b2017-06-08 15:35:21 +09005081 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005082 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005083 // marks on unsupported interfaces is harmless.
5084 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5085 return;
5086 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005087
Joel Scherpelz668370b2017-06-08 15:35:21 +09005088 int mark = mContext.getResources().getInteger(
5089 com.android.internal.R.integer.config_networkWakeupPacketMark);
5090 int mask = mContext.getResources().getInteger(
5091 com.android.internal.R.integer.config_networkWakeupPacketMask);
5092
5093 // Mask/mark of zero will not detect anything interesting.
5094 // Don't install rules unless both values are nonzero.
5095 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005096 return;
5097 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005098
5099 final String prefix = "iface:" + iface;
5100 try {
5101 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005102 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005103 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005104 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005105 }
5106 } catch (Exception e) {
5107 loge("Exception modifying wakeup packet monitoring: " + e);
5108 }
5109
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005110 }
5111
5112 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5113 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005114 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005115 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5116 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005117 for (String iface : interfaceDiff.added) {
5118 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005119 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005120 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005121 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005122 } catch (Exception e) {
5123 loge("Exception adding interface: " + e);
5124 }
5125 }
5126 for (String iface : interfaceDiff.removed) {
5127 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005128 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005129 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005130 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005131 } catch (Exception e) {
5132 loge("Exception removing interface: " + e);
5133 }
5134 }
5135 }
5136
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005137 /**
5138 * Have netd update routes from oldLp to newLp.
5139 * @return true if routes changed between oldLp and newLp
5140 */
5141 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005142 // Compare the route diff to determine which routes should be added and removed.
5143 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5144 oldLp != null ? oldLp.getAllRoutes() : null,
5145 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005146
5147 // add routes before removing old in case it helps with continuous connectivity
5148
Chalard Jean4d660112018-06-04 16:52:49 +09005149 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150 for (RouteInfo route : routeDiff.added) {
5151 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005152 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005153 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005154 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005155 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005156 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5157 loge("Exception in addRoute for non-gateway: " + e);
5158 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005159 }
5160 }
5161 for (RouteInfo route : routeDiff.added) {
5162 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005163 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005164 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005165 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005166 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005167 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5168 loge("Exception in addRoute for gateway: " + e);
5169 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005170 }
5171 }
5172
5173 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005174 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005175 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005176 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005177 } catch (Exception e) {
5178 loge("Exception in removeRoute: " + e);
5179 }
5180 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005181 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005182 }
Erik Kline41368502015-06-17 13:19:54 +09005183
Erik Kline94887872016-04-05 13:30:49 +09005184 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5185 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5186 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005187 }
Erik Kline94887872016-04-05 13:30:49 +09005188
Erik Kline1742fe12017-12-13 19:40:49 +09005189 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5190 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5191
Erik Klinea24d4592018-01-11 21:07:29 +09005192 if (DBG) {
5193 final Collection<InetAddress> dnses = newLp.getDnsServers();
5194 log("Setting DNS servers for network " + netId + " to " + dnses);
5195 }
Erik Kline94887872016-04-05 13:30:49 +09005196 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005197 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005198 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005199 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005200 }
Erik Kline4edba012017-04-07 15:29:29 +09005201 }
5202
Luke Huang8a462ec2018-08-24 20:33:16 +08005203 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005204 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005205 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005206 }
5207 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005208 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005209 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005210 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005211 }
5212
Paul Jensen3d194ea2015-06-16 14:27:36 -04005213 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005214 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5215 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5216 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005217 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005218 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005219 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005220 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5221 // causing a connect/teardown loop.
5222 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5223 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005224 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005225 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005226 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5227 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005228 // does not cause any request (that is not a listen) currently matching that agent to
5229 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005230 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005231 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005232 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005233 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005234 }
5235
Paul Jensen3d194ea2015-06-16 14:27:36 -04005236 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005237 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005238 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005239 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005240 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005241 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005242 }
Paul Jensene0988542015-06-25 15:30:08 -04005243 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005244 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005245 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005246 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005247 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005248 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005249 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005250 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005251 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005252 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005253 if (nai.isSuspended()) {
5254 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5255 } else {
5256 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5257 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005258
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005259 return newNc;
5260 }
5261
5262 /**
5263 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5264 *
5265 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5266 * capabilities we manage and store in {@code nai}, such as validated status and captive
5267 * portal status)
5268 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5269 * potentially triggers rematches.
5270 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5271 * change.)
5272 *
5273 * @param oldScore score of the network before any of the changes that prompted us
5274 * to call this function.
5275 * @param nai the network having its capabilities updated.
5276 * @param nc the new network capabilities.
5277 */
5278 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5279 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5280
5281 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005282
Luke Huang8a462ec2018-08-24 20:33:16 +08005283 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5284 final int newPermission = getNetworkPermission(newNc);
5285 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005286 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005287 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005288 } catch (RemoteException e) {
5289 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005290 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005291 }
5292
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005293 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005294 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005295 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005296 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005297 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005298
Chalard Jeanf213ca12018-01-16 18:43:05 +09005299 updateUids(nai, prevNc, newNc);
5300
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005301 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005302 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5303 // the change we're processing can't affect any requests, it can only affect the listens
5304 // on this network. We might have been called by rematchNetworkAndRequests when a
5305 // network changed foreground state.
5306 processListenRequests(nai, true);
5307 } else {
5308 // If the requestable capabilities have changed or the score changed, we can't have been
5309 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005310 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005311 try {
5312 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5313 } catch (RemoteException e) {
5314 e.rethrowFromSystemServer();
5315 }
Paul Jensene0988542015-06-25 15:30:08 -04005316 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005317 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005318
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005319 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005320 final boolean oldMetered = prevNc.isMetered();
5321 final boolean newMetered = newNc.isMetered();
5322 final boolean meteredChanged = oldMetered != newMetered;
5323
5324 if (meteredChanged) {
5325 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5326 mRestrictBackground);
5327 }
5328
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005329 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005330 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005331
5332 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005333 if (meteredChanged || roamingChanged) {
5334 notifyIfacesChangedForNetworkStats();
5335 }
5336 }
5337
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005338 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005339 // Tell VPNs about updated capabilities, since they may need to
5340 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005341 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005342 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005343 }
5344
Chalard Jeanf213ca12018-01-16 18:43:05 +09005345 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5346 NetworkCapabilities newNc) {
5347 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5348 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5349 if (null == prevRanges) prevRanges = new ArraySet<>();
5350 if (null == newRanges) newRanges = new ArraySet<>();
5351 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5352
5353 prevRanges.removeAll(newRanges);
5354 newRanges.removeAll(prevRangesCopy);
5355
5356 try {
5357 if (!newRanges.isEmpty()) {
5358 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5359 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005360 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005361 }
5362 if (!prevRanges.isEmpty()) {
5363 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5364 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005365 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005366 }
5367 } catch (Exception e) {
5368 // Never crash!
5369 loge("Exception in updateUids: " + e);
5370 }
5371 }
5372
Hugo Benichief502882017-09-01 01:23:32 +00005373 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07005374 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005375 // Ignore updates for disconnected networks
5376 return;
5377 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005378 // newLp is already a defensive copy.
5379 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005380 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005381 log("Update of LinkProperties for " + nai.name() +
5382 "; created=" + nai.created +
5383 "; everConnected=" + nai.everConnected);
5384 }
lucaslin25a4ec32018-11-28 12:51:55 +08005385 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005386 }
5387
Paul Jensenc8b9a742014-09-30 15:37:41 -04005388 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005389 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5390 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005391 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005392 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04005393 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
5394 }
5395 }
5396
Robert Greenwalt7b816022014-04-18 15:25:25 -07005397 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005398 if (VDBG || DDBG){
5399 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5400 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005401 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07005402 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5403 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005404 }
5405 }
5406
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005407 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5408 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005409 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005410 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005411 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5412 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005413 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005414 sendIntent(nri.mPendingIntent, intent);
5415 }
5416 // else not handled
5417 }
5418
5419 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5420 mPendingIntentWakeLock.acquire();
5421 try {
5422 if (DBG) log("Sending " + pendingIntent);
5423 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5424 } catch (PendingIntent.CanceledException e) {
5425 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5426 mPendingIntentWakeLock.release();
5427 releasePendingNetworkRequest(pendingIntent);
5428 }
5429 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5430 }
5431
5432 @Override
5433 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5434 String resultData, Bundle resultExtras) {
5435 if (DBG) log("Finished sending " + pendingIntent);
5436 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005437 // Release with a delay so the receiving client has an opportunity to put in its
5438 // own request.
5439 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005440 }
5441
Chalard Jeanf19db372018-01-26 19:24:40 +09005442 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005443 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005444 if (nri.messenger == null) {
5445 return; // Default request has no msgr
5446 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005447 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005448 // TODO: check if defensive copies of data is needed.
5449 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005450 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005451 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5452 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005453 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005454 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005455 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005456 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5457 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005458 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005459 // For this notification, arg1 contains the blocked status.
5460 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005461 break;
5462 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005463 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005464 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005465 break;
5466 }
5467 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005468 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005469 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005470 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005471 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005472 break;
5473 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005474 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005475 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005476 break;
5477 }
junyulai05986c62018-08-07 19:50:45 +08005478 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005479 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005480 msg.arg1 = arg1;
5481 break;
5482 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005483 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005484 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005485 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005486 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005487 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005488 String notification = ConnectivityManager.getCallbackName(notificationType);
5489 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005490 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005491 nri.messenger.send(msg);
5492 } catch (RemoteException e) {
5493 // may occur naturally in the race of binder death.
5494 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5495 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005496 }
5497
Hugo Benichidba33db2017-03-23 22:40:44 +09005498 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5499 bundle.putParcelable(t.getClass().getSimpleName(), t);
5500 }
5501
Paul Jensenc8b9a742014-09-30 15:37:41 -04005502 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005503 if (nai.numRequestNetworkRequests() != 0) {
5504 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5505 NetworkRequest nr = nai.requestAt(i);
5506 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005507 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005508 loge("Dead network still had at least " + nr);
5509 break;
5510 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005511 }
5512 nai.asyncChannel.disconnect();
5513 }
5514
Robert Greenwalt7b816022014-04-18 15:25:25 -07005515 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5516 if (oldNetwork == null) {
5517 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5518 return;
5519 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005520 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005521
5522 // If we get here it means that the last linger timeout for this network expired. So there
5523 // must be no other active linger timers, and we must stop lingering.
5524 oldNetwork.clearLingerState();
5525
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005526 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005527 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005528 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005529 } else {
5530 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005531 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5532 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005533 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005534 }
5535
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005536 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005537 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005538
Paul Jensen27b02b72014-07-14 12:03:33 -04005539 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005540 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005541 } catch (Exception e) {
5542 loge("Exception setting default network :" + e);
5543 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005544
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005545 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005546 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005547 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005548 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005549 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005550 }
5551
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005552 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005553 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5554 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5555 NetworkRequest nr = nri.request;
5556 if (!nr.isListen()) continue;
5557 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5558 nai.removeRequest(nri.request.requestId);
5559 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5560 }
5561 }
5562
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005563 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005564 try {
5565 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5566 } catch (RemoteException e) {
5567 e.rethrowFromSystemServer();
5568 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005569 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5570 }
5571
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005572 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5573 NetworkRequest nr = nri.request;
5574 if (!nr.isListen()) continue;
5575 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5576 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005577 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005578 }
5579 }
5580 }
5581
Paul Jensen2161a8e2014-09-11 11:00:39 -04005582 // Handles a network appearing or improving its score.
5583 //
5584 // - Evaluates all current NetworkRequests that can be
5585 // satisfied by newNetwork, and reassigns to newNetwork
5586 // any such requests for which newNetwork is the best.
5587 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005588 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005589 // needed. A network is needed if it is the best network for
5590 // one or more NetworkRequests, or if it is a VPN.
5591 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005592 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005593 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005594 //
5595 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5596 // networks that have no chance (i.e. even if validated)
5597 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005598 //
5599 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5600 // it does not remove NetworkRequests that other Networks could better satisfy.
5601 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5602 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5603 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005604 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005605 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005606 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5607 // performed to tear down unvalidated networks that have no chance (i.e. even if
5608 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005609 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005610 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005611 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005612 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005613 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005614 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005615
5616 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5617 final int score = newNetwork.getCurrentScore();
5618
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005619 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005620
Paul Jensen2161a8e2014-09-11 11:00:39 -04005621 // Find and migrate to this Network any NetworkRequests for
5622 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005623 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5624 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005625 NetworkCapabilities nc = newNetwork.networkCapabilities;
5626 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005627 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005628 // Process requests in the first pass and listens in the second pass. This allows us to
5629 // change a network's capabilities depending on which requests it has. This is only
5630 // correct if the change in capabilities doesn't affect whether the network satisfies
5631 // requests or not, and doesn't affect the network's score.
5632 if (nri.request.isListen()) continue;
5633
Hugo Benichicd952782017-09-20 11:20:14 +09005634 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005635 final boolean satisfies = newNetwork.satisfies(nri.request);
5636 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005637 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005638 log("Network " + newNetwork.name() + " was already satisfying" +
5639 " request " + nri.request.requestId + ". No change.");
5640 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005641 keep = true;
5642 continue;
5643 }
5644
5645 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005646 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005647 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005648 // next check if it's better than any current network we're using for
5649 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005650 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005651 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005652 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005653 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005654 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005655 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005656 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005657 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005658 if (VDBG || DDBG){
5659 log(" accepting network in place of " + currentNetwork.name());
5660 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005661 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005662 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005663 affectedNetworks.add(currentNetwork);
5664 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005665 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005666 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005667 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005668 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005669 if (!newNetwork.addRequest(nri.request)) {
5670 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5671 }
5672 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005673 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005674 // Tell NetworkFactories about the new score, so they can stop
5675 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005676 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005677 // network. Think about if there is a way to reduce this. Push
5678 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005679 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005680 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005681 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005682 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005683 if (currentNetwork != null) {
5684 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5685 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005686 }
5687 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005688 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005689 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5690 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005691 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005692 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5693 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5694 // This means this code doesn't have to handle the case where "currentNetwork" no
5695 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5696 if (DBG) {
5697 log("Network " + newNetwork.name() + " stopped satisfying" +
5698 " request " + nri.request.requestId);
5699 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005700 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005701 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005702 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005703 sendUpdatedScoreToFactories(nri.request, 0);
5704 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005705 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5706 newNetwork.name() +
5707 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005708 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005709 // TODO: Technically, sending CALLBACK_LOST here is
5710 // incorrect if there is a replacement network currently
5711 // connected that can satisfy nri, which is a request
5712 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005713 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5714 // so this code is only incorrect for a network that loses
5715 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005716 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005717 }
5718 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005719 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005720 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005721 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005722 makeDefault(newNetwork);
5723 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005724 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005725 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005726 // Have a new default network, release the transition wakelock in
5727 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005728 }
5729
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005730 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5731 Slog.wtf(TAG, String.format(
5732 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005733 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005734 }
5735 if (newNetwork.getCurrentScore() != score) {
5736 Slog.wtf(TAG, String.format(
5737 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005738 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005739 }
5740
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005741 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005742 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5743 // If the network went from background to foreground or vice versa, we need to update
5744 // its foreground state. It is safe to do this after rematching the requests because
5745 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5746 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005747 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005748 } else {
5749 processListenRequests(newNetwork, false);
5750 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005751
Paul Jensencf4c2c62015-07-01 14:16:32 -04005752 // do this after the default net is switched, but
5753 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005754 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005755
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005756 // Linger any networks that are no longer needed. This should be done after sending the
5757 // available callback for newNetwork.
5758 for (NetworkAgentInfo nai : affectedNetworks) {
5759 updateLingerState(nai, now);
5760 }
5761 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5762 // does not need to be done in any particular order.
5763 updateLingerState(newNetwork, now);
5764
Paul Jensencf4c2c62015-07-01 14:16:32 -04005765 if (isNewDefault) {
5766 // Maintain the illusion: since the legacy API only
5767 // understands one network at a time, we must pretend
5768 // that the current default network disconnected before
5769 // the new one connected.
5770 if (oldDefaultNetwork != null) {
5771 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5772 oldDefaultNetwork, true);
5773 }
5774 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5775 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5776 notifyLockdownVpn(newNetwork);
5777 }
5778
Robert Greenwalt7b816022014-04-18 15:25:25 -07005779 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005780 // Notify battery stats service about this network, both the normal
5781 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005782 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005783 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005784 final IBatteryStats bs = BatteryStatsService.getService();
5785 final int type = newNetwork.networkInfo.getType();
5786
5787 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5788 bs.noteNetworkInterfaceType(baseIface, type);
5789 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5790 final String stackedIface = stacked.getInterfaceName();
5791 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005792 }
5793 } catch (RemoteException ignored) {
5794 }
5795
Robert Greenwalt152ed372014-12-17 17:19:53 -08005796 // This has to happen after the notifyNetworkCallbacks as that tickles each
5797 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005798 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005799 // and will generally do a dns request so they can ensureRouteToHost and if
5800 // they do that before the callbacks happen they'll use the default network.
5801 //
5802 // TODO: Is there still a race here? We send the broadcast
5803 // after sending the callback, but if the app can receive the
5804 // broadcast before the callback, it might still break.
5805 //
5806 // This *does* introduce a race where if the user uses the new api
5807 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5808 // they may get old info. Reverse this after the old startUsing api is removed.
5809 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005810 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5811 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005812 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005813 // legacy type tracker filters out repeat adds
5814 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5815 }
5816 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005817
5818 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5819 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5820 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5821 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5822 if (newNetwork.isVPN()) {
5823 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5824 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005825 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005826 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5827 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005828 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005829 if (nai.getLingerExpiry() > 0) {
5830 // This network has active linger timers and no requests, but is not
5831 // lingering. Linger it.
5832 //
5833 // One way (the only way?) this can happen if this network is unvalidated
5834 // and became unneeded due to another network improving its score to the
5835 // point where this network will no longer be able to satisfy any requests
5836 // even if it validates.
5837 updateLingerState(nai, now);
5838 } else {
5839 if (DBG) log("Reaping " + nai.name());
5840 teardownUnneededNetwork(nai);
5841 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005842 }
5843 }
5844 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005845 }
5846
Paul Jensen1c7ba022015-06-16 14:27:36 -04005847 /**
5848 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5849 * being disconnected.
5850 * @param changed If only one Network's score or capabilities have been modified since the last
5851 * time this function was called, pass this Network in this argument, otherwise pass
5852 * null.
5853 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5854 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5855 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5856 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5857 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005858 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005859 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005860 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5861 // to avoid the slowness. It is not simply enough to process just "changed", for
5862 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005863 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005864
5865 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5866 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5867 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005868 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005869 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005870 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005871 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005872 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5873 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5874 // Rematch higher scoring networks first to prevent requests first matching a lower
5875 // scoring network and then a higher scoring network, which could produce multiple
5876 // callbacks and inadvertently unlinger networks.
5877 Arrays.sort(nais);
5878 for (NetworkAgentInfo nai : nais) {
5879 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005880 // Only reap the last time through the loop. Reaping before all rematching
5881 // is complete could incorrectly teardown a network that hasn't yet been
5882 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005883 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005884 : ReapUnvalidatedNetworks.REAP,
5885 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005886 }
5887 }
5888 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005889
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005890 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005891 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005892 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005893 // For now only update icons for default connection.
5894 // TODO: Update WiFi and cellular icons separately. b/17237507
5895 if (!isDefaultNetwork(nai)) return;
5896
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005897 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005898 // Don't repeat publish.
5899 if (newInetCondition == mDefaultInetConditionPublished) return;
5900
5901 mDefaultInetConditionPublished = newInetCondition;
5902 sendInetConditionBroadcast(nai.networkInfo);
5903 }
5904
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005905 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005906 synchronized (mVpns) {
5907 if (mLockdownTracker != null) {
5908 if (nai != null && nai.isVPN()) {
5909 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5910 } else {
5911 mLockdownTracker.onNetworkInfoChanged();
5912 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005913 }
5914 }
5915 }
5916
Robert Greenwalt7b816022014-04-18 15:25:25 -07005917 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005918 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005919 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005920 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005921 synchronized (networkAgent) {
5922 oldInfo = networkAgent.networkInfo;
5923 networkAgent.networkInfo = newInfo;
5924 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005925 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005926
Robert Greenwalt7b816022014-04-18 15:25:25 -07005927 if (DBG) {
5928 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5929 (oldInfo == null ? "null" : oldInfo.getState()) +
5930 " to " + state);
5931 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005932
Robin Lee585e2482016-05-01 23:00:00 +01005933 if (!networkAgent.created
5934 && (state == NetworkInfo.State.CONNECTED
5935 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005936
5937 // A network that has just connected has zero requests and is thus a foreground network.
5938 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5939
Robert Greenwalt7b816022014-04-18 15:25:25 -07005940 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005941 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005942 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08005943 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005944 (networkAgent.networkMisc == null ||
5945 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005946 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08005947 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005948 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005949 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005950 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005951 loge("Error creating network " + networkAgent.network.netId + ": "
5952 + e.getMessage());
5953 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005954 }
Paul Jenseneec75412014-08-04 12:21:19 -04005955 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005956 }
5957
5958 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5959 networkAgent.everConnected = true;
5960
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005961 if (networkAgent.linkProperties == null) {
5962 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5963 }
5964
Erik Kline736353a2018-03-21 07:18:33 -07005965 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08005966 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
5967 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005968
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005969 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
5970 // command must be sent after updating LinkProperties to maximize chances of
5971 // NetworkMonitor seeing the correct LinkProperties when starting.
5972 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
5973 try {
5974 networkAgent.networkMonitor().notifyNetworkConnected();
5975 } catch (RemoteException e) {
5976 e.rethrowFromSystemServer();
5977 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005978 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005979
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005980 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5981 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5982 // capabilities, so it only needs to be done once on initial connect, not every time the
5983 // network's capabilities change. Note that we do this before rematching the network,
5984 // so we could decide to tear it down immediately afterwards. That's fine though - on
5985 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5986 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005987 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005988
Paul Jensen2161a8e2014-09-11 11:00:39 -04005989 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005990 final long now = SystemClock.elapsedRealtime();
5991 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005992
5993 // This has to happen after matching the requests, because callbacks are just requests.
5994 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005995 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005996 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005997 if (networkAgent.isVPN()) {
Chalard Jeanf213ca12018-01-16 18:43:05 +09005998 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005999 }
Chalard Jean392971c2018-05-11 20:19:20 +09006000 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescu044a4362018-12-05 16:19:47 +00006001 if (networkAgent.isVPN()) {
6002 // As the active or bound network changes for apps, broadcast the default proxy, as
6003 // apps may need to update their proxy data. This is called after disconnecting from
6004 // VPN to make sure we do not broadcast the old proxy data.
6005 // TODO(b/122649188): send the broadcast only to VPN users.
6006 mProxyTracker.sendProxyBroadcast();
6007 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07006008 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
6009 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09006010 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07006011 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04006012 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006013 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09006014 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
6015 networkAgent.networkCapabilities);
6016 // TODO (b/73132094) : remove this call once the few users of onSuspended and
6017 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07006018 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
6019 ConnectivityManager.CALLBACK_SUSPENDED :
6020 ConnectivityManager.CALLBACK_RESUMED));
6021 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07006022 }
6023 }
6024
Robert Greenwaltac96c522014-06-03 16:43:57 -07006025 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006026 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07006027 if (score < 0) {
6028 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
6029 "). Bumping score to min of 0");
6030 score = 0;
6031 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07006032
Paul Jensen2161a8e2014-09-11 11:00:39 -04006033 final int oldScore = nai.getCurrentScore();
6034 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07006035
Paul Jensen85cf78e2015-06-25 13:25:07 -04006036 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04006037
Paul Jensenc8b9a742014-09-30 15:37:41 -04006038 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07006039 }
6040
Erik Klinec75d4fa2017-02-15 19:59:17 +09006041 // Notify only this one new request of the current state. Transfer all the
6042 // current state by calling NetworkCapabilities and LinkProperties callbacks
6043 // so that callers can be guaranteed to have as close to atomicity in state
6044 // transfer as can be supported by this current API.
6045 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006046 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006047 if (nri.mPendingIntent != null) {
6048 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6049 // Attempt no subsequent state pushes where intents are involved.
6050 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006051 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006052
junyulai05986c62018-08-07 19:50:45 +08006053 final boolean metered = nai.networkCapabilities.isMetered();
6054 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6055 metered, mRestrictBackground);
6056 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6057 }
6058
6059 /**
6060 * Notify of the blocked state apps with a registered callback matching a given NAI.
6061 *
6062 * Unlike other callbacks, blocked status is different between each individual uid. So for
6063 * any given nai, all requests need to be considered according to the uid who filed it.
6064 *
6065 * @param nai The target NetworkAgentInfo.
6066 * @param oldMetered True if the previous network capabilities is metered.
6067 * @param newRestrictBackground True if data saver is enabled.
6068 */
6069 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6070 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6071
6072 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6073 NetworkRequest nr = nai.requestAt(i);
6074 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6075 final int uidRules = mUidRules.get(nri.mUid);
6076 final boolean oldBlocked, newBlocked;
6077 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6078 // between these two calls.
6079 synchronized (mVpns) {
6080 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6081 oldRestrictBackground);
6082 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6083 newRestrictBackground);
6084 }
6085 if (oldBlocked != newBlocked) {
6086 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6087 encodeBool(newBlocked));
6088 }
6089 }
6090 }
6091
6092 /**
6093 * Notify apps with a given UID of the new blocked state according to new uid rules.
6094 * @param uid The uid for which the rules changed.
6095 * @param newRules The new rules to apply.
6096 */
6097 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6098 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6099 final boolean metered = nai.networkCapabilities.isMetered();
6100 final boolean oldBlocked, newBlocked;
6101 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6102 // rules changed event. And this function actually loop through all connected nai and
6103 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6104 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6105 synchronized (mVpns) {
6106 oldBlocked = isUidNetworkingWithVpnBlocked(
6107 uid, mUidRules.get(uid), metered, mRestrictBackground);
6108 newBlocked = isUidNetworkingWithVpnBlocked(
6109 uid, newRules, metered, mRestrictBackground);
6110 }
6111 if (oldBlocked == newBlocked) {
6112 return;
6113 }
6114 final int arg = encodeBool(newBlocked);
6115 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6116 NetworkRequest nr = nai.requestAt(i);
6117 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6118 if (nri != null && nri.mUid == uid) {
6119 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6120 }
6121 }
6122 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006123 }
6124
Robert Greenwalt8d482522015-06-24 13:23:42 -07006125 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006126 // The NetworkInfo we actually send out has no bearing on the real
6127 // state of affairs. For example, if the default connection is mobile,
6128 // and a request for HIPRI has just gone away, we need to pretend that
6129 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6130 // the state to DISCONNECTED, even though the network is of type MOBILE
6131 // and is still connected.
6132 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6133 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006134 if (state != DetailedState.DISCONNECTED) {
6135 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006136 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006137 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006138 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006139 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6140 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6141 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6142 if (info.isFailover()) {
6143 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6144 nai.networkInfo.setFailover(false);
6145 }
6146 if (info.getReason() != null) {
6147 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6148 }
6149 if (info.getExtraInfo() != null) {
6150 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6151 }
6152 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006153 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006154 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006155 if (newDefaultAgent != null) {
6156 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6157 newDefaultAgent.networkInfo);
6158 } else {
6159 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6160 }
6161 }
6162 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6163 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006164 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006165 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006166 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006167 }
6168 }
6169 }
6170
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006171 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006172 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006173 String notification = ConnectivityManager.getCallbackName(notifyType);
6174 log("notifyType " + notification + " for " + networkAgent.name());
6175 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006176 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6177 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006178 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6179 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006180 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6181 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006182 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006183 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006184 } else {
6185 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6186 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006187 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006188 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006189
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006190 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6191 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6192 }
6193
Jeff Sharkey69736342014-12-08 14:50:12 -08006194 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006195 * Returns the list of all interfaces that could be used by network traffic that does not
6196 * explicitly specify a network. This includes the default network, but also all VPNs that are
6197 * currently connected.
6198 *
6199 * Must be called on the handler thread.
6200 */
6201 private Network[] getDefaultNetworks() {
6202 ArrayList<Network> defaultNetworks = new ArrayList<>();
6203 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6204 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6205 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6206 defaultNetworks.add(nai.network);
6207 }
6208 }
6209 return defaultNetworks.toArray(new Network[0]);
6210 }
6211
6212 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006213 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6214 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006215 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006216 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08006217 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006218 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08006219 } catch (Exception ignored) {
6220 }
6221 }
6222
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006223 @Override
6224 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006225 int user = UserHandle.getUserId(Binder.getCallingUid());
6226 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006227 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006228 return mVpns.get(user).addAddress(address, prefixLength);
6229 }
6230 }
6231
6232 @Override
6233 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006234 int user = UserHandle.getUserId(Binder.getCallingUid());
6235 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006236 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006237 return mVpns.get(user).removeAddress(address, prefixLength);
6238 }
6239 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006240
6241 @Override
6242 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006243 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006244 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006245 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006246 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006247 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006248 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006249 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006250 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006251 }
6252 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006253 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006254
6255 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006256 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006257 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006258 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006259 }
6260
6261 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006262 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
6263 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
6264 enforceKeepalivePermission();
6265 mKeepaliveTracker.startNattKeepalive(
6266 getNetworkAgentInfoForNetwork(network),
6267 intervalSeconds, messenger, binder,
6268 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
6269 }
6270
6271 @Override
junyulai215b8772019-01-15 11:32:44 +08006272 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
6273 int intervalSeconds, Messenger messenger, IBinder binder, String srcAddr,
6274 String dstAddr) {
6275 enforceKeepalivePermission();
6276 mKeepaliveTracker.startNattKeepalive(
6277 getNetworkAgentInfoForNetwork(network), fd, resourceId,
6278 intervalSeconds, messenger, binder,
6279 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6280 }
6281
6282 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006283 public void stopKeepalive(Network network, int slot) {
6284 mHandler.sendMessage(mHandler.obtainMessage(
6285 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
6286 }
6287
6288 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006289 public void factoryReset() {
6290 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006291
6292 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6293 return;
6294 }
6295
Robin Lee3b3dd942015-05-12 18:14:58 +01006296 final int userId = UserHandle.getCallingUserId();
6297
Stuart Scottf1fb3972015-04-02 18:00:02 -07006298 // Turn airplane mode off
6299 setAirplaneMode(false);
6300
Stuart Scotte3e314d2015-04-20 14:07:45 -07006301 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6302 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006303 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006304 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006305 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006306 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006307 }
6308
Stuart Scotte3e314d2015-04-20 14:07:45 -07006309 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006310 // Remove always-on package
6311 synchronized (mVpns) {
6312 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6313 if (alwaysOnPackage != null) {
Dan Albertee8e6a02019-01-24 21:05:39 +00006314 setAlwaysOnVpnPackage(userId, null, false);
Victor Changb04a5ea2016-05-30 20:36:30 +01006315 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6316 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006317
Hugo Benichi69744342017-11-27 10:57:16 +09006318 // Turn Always-on VPN off
6319 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6320 final long ident = Binder.clearCallingIdentity();
6321 try {
6322 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6323 mLockdownEnabled = false;
6324 setLockdownTracker(null);
6325 } finally {
6326 Binder.restoreCallingIdentity(ident);
6327 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006328 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006329
Hugo Benichi69744342017-11-27 10:57:16 +09006330 // Turn VPN off
6331 VpnConfig vpnConfig = getVpnConfig(userId);
6332 if (vpnConfig != null) {
6333 if (vpnConfig.legacy) {
6334 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6335 } else {
6336 // Prevent this app (packagename = vpnConfig.user) from initiating
6337 // VPN connections in the future without user intervention.
6338 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006339
Hugo Benichi69744342017-11-27 10:57:16 +09006340 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6341 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006342 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006343 }
6344 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006345
6346 Settings.Global.putString(mContext.getContentResolver(),
6347 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006348 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006349
Ricky Wai44dcbde2018-01-23 04:09:45 +00006350 @Override
6351 public byte[] getNetworkWatchlistConfigHash() {
6352 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6353 if (nwm == null) {
6354 loge("Unable to get NetworkWatchlistManager");
6355 return null;
6356 }
6357 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6358 return nwm.getWatchlistConfigHash();
6359 }
6360
Paul Jensencf4c2c62015-07-01 14:16:32 -04006361 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006362 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6363 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006364 }
6365
6366 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006367 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6368 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6369 }
6370
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006371 @VisibleForTesting
6372 public boolean hasService(String name) {
6373 return ServiceManager.checkService(name) != null;
6374 }
6375
Hugo Benichi64901e52017-10-19 14:42:40 +09006376 @VisibleForTesting
6377 protected IpConnectivityMetrics.Logger metricsLogger() {
6378 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6379 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006380 }
6381
6382 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006383 int[] transports = nai.networkCapabilities.getTransportTypes();
6384 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006385 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006386
6387 private static boolean toBool(int encodedBoolean) {
6388 return encodedBoolean != 0; // Only 0 means false.
6389 }
6390
6391 private static int encodeBool(boolean b) {
6392 return b ? 1 : 0;
6393 }
mswest46386886f2018-03-12 10:34:34 -07006394
6395 @Override
6396 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6397 FileDescriptor err, String[] args, ShellCallback callback,
6398 ResultReceiver resultReceiver) {
6399 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6400 }
6401
6402 private class ShellCmd extends ShellCommand {
6403
6404 @Override
6405 public int onCommand(String cmd) {
6406 if (cmd == null) {
6407 return handleDefaultCommands(cmd);
6408 }
6409 final PrintWriter pw = getOutPrintWriter();
6410 try {
6411 switch (cmd) {
6412 case "airplane-mode":
6413 final String action = getNextArg();
6414 if ("enable".equals(action)) {
6415 setAirplaneMode(true);
6416 return 0;
6417 } else if ("disable".equals(action)) {
6418 setAirplaneMode(false);
6419 return 0;
6420 } else if (action == null) {
6421 final ContentResolver cr = mContext.getContentResolver();
6422 final int enabled = Settings.Global.getInt(cr,
6423 Settings.Global.AIRPLANE_MODE_ON);
6424 pw.println(enabled == 0 ? "disabled" : "enabled");
6425 return 0;
6426 } else {
6427 onHelp();
6428 return -1;
6429 }
6430 default:
6431 return handleDefaultCommands(cmd);
6432 }
6433 } catch (Exception e) {
6434 pw.println(e);
6435 }
6436 return -1;
6437 }
6438
6439 @Override
6440 public void onHelp() {
6441 PrintWriter pw = getOutPrintWriter();
6442 pw.println("Connectivity service commands:");
6443 pw.println(" help");
6444 pw.println(" Print this help text.");
6445 pw.println(" airplane-mode [enable|disable]");
6446 pw.println(" Turn airplane mode on or off.");
6447 pw.println(" airplane-mode");
6448 pw.println(" Get airplane mode.");
6449 }
6450 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006451
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006452 @GuardedBy("mVpns")
6453 private Vpn getVpnIfOwner() {
6454 final int uid = Binder.getCallingUid();
6455 final int user = UserHandle.getUserId(uid);
6456
6457 final Vpn vpn = mVpns.get(user);
6458 if (vpn == null) {
6459 return null;
6460 } else {
6461 final VpnInfo info = vpn.getVpnInfo();
6462 return (info == null || info.ownerUid != uid) ? null : vpn;
6463 }
6464 }
6465
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006466 /**
6467 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6468 * for testing.
6469 */
6470 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6471 if (checkNetworkStackPermission()) {
6472 return null;
6473 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006474 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006475 Vpn vpn = getVpnIfOwner();
6476 if (vpn != null) {
6477 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006478 }
6479 }
6480 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6481 + "permission");
6482 }
6483
6484 /**
6485 * @param connectionInfo the connection to resolve.
6486 * @return {@code uid} if the connection is found and the app has permission to observe it
6487 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6488 * connection is not found.
6489 */
6490 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6491 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6492 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6493 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6494 }
6495
6496 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6497 connectionInfo.local, connectionInfo.remote);
6498
6499 /* Filter out Uids not associated with the VPN. */
6500 if (vpn != null && !vpn.appliesToUid(uid)) {
6501 return INVALID_UID;
6502 }
6503
6504 return uid;
6505 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006506
6507 @Override
6508 public boolean isCallerCurrentAlwaysOnVpnApp() {
6509 synchronized (mVpns) {
6510 Vpn vpn = getVpnIfOwner();
6511 return vpn != null && vpn.getAlwaysOn();
6512 }
6513 }
6514
6515 @Override
6516 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6517 synchronized (mVpns) {
6518 Vpn vpn = getVpnIfOwner();
6519 return vpn != null && vpn.getLockdown();
6520 }
6521 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006522}