blob: 8b32afbb73dc810ba18d8c25fc6cc8c9963111e1 [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.
Chalard Jeanff5d0052018-06-07 19:20:08 +0900518 private final ProxyTracker mProxyTracker;
Jason Monk602b2322013-07-03 17:04:33 -0400519
Erik Klineda4bfa82015-04-30 12:58:40 +0900520 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700521
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400522 private UserManager mUserManager;
523
Chalard Jean4133a122018-06-04 13:33:12 +0900524 private NetworkConfig[] mNetConfigs;
525 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700526
Robert Greenwalt50393202011-06-21 17:26:14 -0700527 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900528 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700529
Chalard Jean4133a122018-06-04 13:33:12 +0900530 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400531
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900532 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900533 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900534 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900535
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700536 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800537 private static final int MIN_NET_ID = 100; // some reserved marks
538 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700539 private int mNextNetId = MIN_NET_ID;
540
Robert Greenwalt34524f02014-05-18 16:22:10 -0700541 // sequence number of NetworkRequests
542 private int mNextNetworkRequestId = 1;
543
Erik Kline7523eb32015-07-09 18:24:03 +0900544 // NetworkRequest activity String log entries.
545 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
546 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
547
Hugo Benichic2ae2872016-07-11 11:05:12 +0900548 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900549 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900550 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
551
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900552 private static final int MAX_WAKELOCK_LOGS = 20;
553 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900554 private int mTotalWakelockAcquisitions = 0;
555 private int mTotalWakelockReleases = 0;
556 private long mTotalWakelockDurationMs = 0;
557 private long mMaxWakelockDurationMs = 0;
558 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900559
Hugo Benichif9fdf872016-07-28 17:53:06 +0900560 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900561
Nathan Haroldfd45e5f2018-07-30 13:38:01 -0700562 @GuardedBy("mBandwidthRequests")
563 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
564
Erik Kline065ab6e2016-10-02 18:02:14 +0900565 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900566 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900567
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900568 @VisibleForTesting
569 final MultipathPolicyTracker mMultipathPolicyTracker;
570
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 /**
572 * Implements support for the legacy "one network per network type" model.
573 *
574 * We used to have a static array of NetworkStateTrackers, one for each
575 * network type, but that doesn't work any more now that we can have,
576 * for example, more that one wifi network. This class stores all the
577 * NetworkAgentInfo objects that support a given type, but the legacy
578 * API will only see the first one.
579 *
580 * It serves two main purposes:
581 *
582 * 1. Provide information about "the network for a given type" (since this
583 * API only supports one).
584 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
585 * the first network for a given type changes, or if the default network
586 * changes.
587 */
588 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900589
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900590 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900591 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700593 /**
594 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
595 * Each list holds references to all NetworkAgentInfos that are used to
596 * satisfy requests for that network type.
597 *
598 * This array is built out at startup such that an unsupported network
599 * doesn't get an ArrayList instance, making this a tristate:
600 * unsupported, supported but not active and active.
601 *
602 * The actual lists are populated when we scan the network types that
603 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 *
605 * Threading model:
606 * - addSupportedType() is only called in the constructor
607 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
608 * They are therefore not thread-safe with respect to each other.
609 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
610 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
611 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700612 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900613 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614
615 public LegacyTypeTracker() {
616 mTypeLists = (ArrayList<NetworkAgentInfo>[])
617 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
618 }
619
620 public void addSupportedType(int type) {
621 if (mTypeLists[type] != null) {
622 throw new IllegalStateException(
623 "legacy list for type " + type + "already initialized");
624 }
Chalard Jean4133a122018-06-04 13:33:12 +0900625 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700626 }
627
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700628 public boolean isTypeSupported(int type) {
629 return isNetworkTypeValid(type) && mTypeLists[type] != null;
630 }
631
632 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900633 synchronized (mTypeLists) {
634 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
635 return mTypeLists[type].get(0);
636 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700637 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900638 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700639 }
640
Robert Greenwalt8d482522015-06-24 13:23:42 -0700641 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900642 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900643 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900645 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900646 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900647 }
648 }
649
650 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700651 public void add(int type, NetworkAgentInfo nai) {
652 if (!isTypeSupported(type)) {
653 return; // Invalid network type.
654 }
655 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
656
657 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
658 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700659 return;
660 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900661 synchronized (mTypeLists) {
662 list.add(nai);
663 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900664
665 // 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 +0900666 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900667 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700668 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
669 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700670 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700671 }
672
Lorenzo Colittia793a672014-07-31 23:20:17 +0900673 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900674 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900675 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
676 if (list == null || list.isEmpty()) {
677 return;
678 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900679 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900680
Hugo Benichi78caa2582016-06-21 09:48:07 +0900681 synchronized (mTypeLists) {
682 if (!list.remove(nai)) {
683 return;
684 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900685 }
686
Robert Greenwalt8d482522015-06-24 13:23:42 -0700687 final DetailedState state = DetailedState.DISCONNECTED;
688
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900689 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700690 maybeLogBroadcast(nai, state, type, wasDefault);
691 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900692 }
693
694 if (!list.isEmpty() && wasFirstNetwork) {
695 if (DBG) log("Other network available for type " + type +
696 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900697 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700698 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
699 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900700 }
701 }
702
703 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900704 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
705 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700706 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900707 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700708 }
709 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700710
Robert Greenwalt8d482522015-06-24 13:23:42 -0700711 // send out another legacy broadcast - currently only used for suspend/unsuspend
712 // toggle
713 public void update(NetworkAgentInfo nai) {
714 final boolean isDefault = isDefaultNetwork(nai);
715 final DetailedState state = nai.networkInfo.getDetailedState();
716 for (int type = 0; type < mTypeLists.length; type++) {
717 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700718 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900719 final boolean isFirst = contains && (nai == list.get(0));
720 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700721 maybeLogBroadcast(nai, state, type, isDefault);
722 sendLegacyNetworkBroadcast(nai, state, type);
723 }
724 }
725 }
726
Lorenzo Colittia793a672014-07-31 23:20:17 +0900727 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900728 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900729 String state = (nai.networkInfo != null) ?
730 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
731 "???/???";
732 return name + " " + state;
733 }
734
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700735 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900736 pw.println("mLegacyTypeTracker:");
737 pw.increaseIndent();
738 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700739 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900740 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700741 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900742 pw.println();
743 pw.println("Current state:");
744 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900745 synchronized (mTypeLists) {
746 for (int type = 0; type < mTypeLists.length; type++) {
747 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
748 for (NetworkAgentInfo nai : mTypeLists[type]) {
749 pw.println(type + " " + naiToString(nai));
750 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900751 }
752 }
753 pw.decreaseIndent();
754 pw.decreaseIndent();
755 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700756 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700757 }
758 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
759
Vishnu Nair5c010902017-10-26 10:08:50 -0700760 /**
761 * Helper class which parses out priority arguments and dumps sections according to their
762 * priority. If priority arguments are omitted, function calls the legacy dump command.
763 */
764 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
765 @Override
766 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
767 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
768 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
769 }
770
771 @Override
772 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
773 doDump(fd, pw, args, asProto);
774 }
775
776 @Override
777 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
778 doDump(fd, pw, args, asProto);
779 }
780 };
781
Jeff Sharkey899223b2012-08-04 15:24:58 -0700782 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700783 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900784 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
785 }
786
787 @VisibleForTesting
788 protected ConnectivityService(Context context, INetworkManagementService netManager,
789 INetworkStatsService statsService, INetworkPolicyManager policyManager,
790 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800791 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800792
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900793 mSystemProperties = getSystemProperties();
794
Hugo Benichif9fdf872016-07-28 17:53:06 +0900795 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900796 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900797 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900798 mNetworkRequests.put(mDefaultRequest, defaultNRI);
799 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900800
Chalard Jeandda156a2018-01-10 21:19:32 +0900801 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900802 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700803
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -0700804 // The default WiFi request is a background request so that apps using WiFi are
805 // migrated to a better network (typically ethernet) when one comes up, instead
806 // of staying on WiFi forever.
807 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
808 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
809
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900810 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900811 mHandlerThread.start();
812 mHandler = new InternalHandler(mHandlerThread.getLooper());
813 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700814
Jeremy Joslin79294842014-12-03 17:15:28 -0800815 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
816 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
817
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900818 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900819
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700820 mContext = checkNotNull(context, "missing Context");
Luke Huang4e25ec62018-09-27 16:58:23 +0800821 mNMS = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800822 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700823 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900824 mPolicyManagerInternal = checkNotNull(
825 LocalServices.getService(NetworkPolicyManagerInternal.class),
826 "missing NetworkPolicyManagerInternal");
Chalard Jeanff5d0052018-06-07 19:20:08 +0900827 mProxyTracker = new ProxyTracker(context, mHandler, EVENT_PROXY_HAS_CHANGED);
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900828
Luke Huang674660f2018-09-27 19:33:11 +0800829 mNetd = NetdService.getInstance();
Jeff Sharkey82f85212012-08-24 11:17:25 -0700830 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700831 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700832
junyulai05986c62018-08-07 19:50:45 +0800833 // To ensure uid rules are synchronized with Network Policy, register for
834 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
835 // reading existing policy from disk.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700836 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900837 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700838 } catch (RemoteException e) {
839 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700840 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700841 }
842
843 final PowerManager powerManager = (PowerManager) context.getSystemService(
844 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700845 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
846 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
847 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800848 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700849
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700850 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700851
Wink Saville51f456f2013-04-23 14:26:51 -0700852 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900853 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700854 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700855 String[] naStrings = context.getResources().getStringArray(
856 com.android.internal.R.array.networkAttributes);
857 for (String naString : naStrings) {
858 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700859 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700860 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700861 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800862 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700863 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700864 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700865 }
Wink Saville51f456f2013-04-23 14:26:51 -0700866 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
867 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
868 n.type);
869 continue;
870 }
Wink Saville975c8482011-04-07 14:23:45 -0700871 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800872 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700873 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700874 continue;
875 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700876 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700877
Wink Saville975c8482011-04-07 14:23:45 -0700878 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700879 mNetworksDefined++;
880 } catch(Exception e) {
881 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700882 }
883 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700884
885 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
886 if (mNetConfigs[TYPE_VPN] == null) {
887 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
888 // don't need to add TYPE_VPN to mNetConfigs.
889 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
890 mNetworksDefined++; // used only in the log() statement below.
891 }
892
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900893 // Do the same for Ethernet, since it's often not specified in the configs, although many
894 // devices can use it via USB host adapters.
895 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
896 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
897 mNetworksDefined++;
898 }
899
Wink Saville5e56bc52013-07-29 15:00:57 -0700900 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700901
Robert Greenwalt50393202011-06-21 17:26:14 -0700902 mProtectedNetworks = new ArrayList<Integer>();
903 int[] protectedNetworks = context.getResources().getIntArray(
904 com.android.internal.R.array.config_protectedNetworks);
905 for (int p : protectedNetworks) {
906 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
907 mProtectedNetworks.add(p);
908 } else {
909 if (DBG) loge("Ignoring protectedNetwork " + p);
910 }
911 }
912
Erik Kline47222fc2017-04-30 19:36:15 +0900913 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800914
Luke Huang4e25ec62018-09-27 16:58:23 +0800915 mPermissionMonitor = new PermissionMonitor(mContext, mNMS);
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700916
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700917 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700918 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100919 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700920 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700921 intentFilter.addAction(Intent.ACTION_USER_ADDED);
922 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000923 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700924 mContext.registerReceiverAsUser(
junyulai2454b692018-11-01 17:16:31 +0800925 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000926 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
927 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900928
junyulai2454b692018-11-01 17:16:31 +0800929 // Listen to package add and removal events for all users.
930 intentFilter = new IntentFilter();
931 intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
junyulaiefb04d32018-11-12 22:39:30 +0800932 intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
junyulai2454b692018-11-01 17:16:31 +0800933 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
934 intentFilter.addDataScheme("package");
935 mContext.registerReceiverAsUser(
936 mIntentReceiver, UserHandle.ALL, intentFilter, null, null);
937
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700938 try {
Luke Huang4e25ec62018-09-27 16:58:23 +0800939 mNMS.registerObserver(mTethering);
940 mNMS.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700941 } catch (RemoteException e) {
942 loge("Error registering observer :" + e);
943 }
944
Erik Klineda4bfa82015-04-30 12:58:40 +0900945 mSettingsObserver = new SettingsObserver(mContext, mHandler);
946 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800947
Chalard Jean4133a122018-06-04 13:33:12 +0900948 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
949 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400950
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400951 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900952
953 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900954 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
955 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900956
957 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
958 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
959 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
960 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
961 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
962 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
963 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900964
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900965 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900966 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900967 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900968
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900969 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
970
Luke Huang4e25ec62018-09-27 16:58:23 +0800971 mDnsManager = new DnsManager(mContext, mNMS, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900972 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700974
Mike Yuf9729752018-08-17 15:22:05 +0800975 @VisibleForTesting
976 protected Tethering makeTethering() {
Erik Kline47222fc2017-04-30 19:36:15 +0900977 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900978 final TetheringDependencies deps = new TetheringDependencies() {
979 @Override
980 public boolean isTetheringSupported() {
981 return ConnectivityService.this.isTetheringSupported();
982 }
Erik Kline72302902018-06-14 17:36:40 +0900983 @Override
984 public NetworkRequest getDefaultNetworkRequest() {
985 return mDefaultRequest;
986 }
Erik Kline465ff3a2018-03-09 14:18:02 +0900987 };
Luke Huang4e25ec62018-09-27 16:58:23 +0800988 return new Tethering(mContext, mNMS, mStatsService, mPolicyManager,
Erik Kline47222fc2017-04-30 19:36:15 +0900989 IoThread.get().getLooper(), new MockableSystemProperties(),
990 deps);
991 }
992
Chalard Jean26400492018-04-18 20:18:38 +0900993 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
994 final NetworkCapabilities netCap = new NetworkCapabilities();
995 netCap.addCapability(NET_CAPABILITY_INTERNET);
996 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
997 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
998 netCap.setSingleUid(uid);
999 return netCap;
1000 }
1001
Chalard Jeandda156a2018-01-10 21:19:32 +09001002 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001003 int transportType, NetworkRequest.Type type) {
Erik Kline72302902018-06-14 17:36:40 +09001004 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09001005 netCap.addCapability(NET_CAPABILITY_INTERNET);
1006 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +09001007 if (transportType > -1) {
1008 netCap.addTransportType(transportType);
1009 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001010 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +09001011 }
1012
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001013 // Used only for testing.
1014 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -07001015 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001016 // changing ContentResolver to make registerContentObserver non-final).
1017 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1018 // by subclassing SettingsObserver.
1019 @VisibleForTesting
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001020 void updateAlwaysOnNetworks() {
1021 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +09001022 }
1023
Erik Kline736353a2018-03-21 07:18:33 -07001024 // See FakeSettingsProvider comment above.
1025 @VisibleForTesting
1026 void updatePrivateDnsSettings() {
1027 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1028 }
1029
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001030 private void handleAlwaysOnNetworkRequest(
1031 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09001032 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001033 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1034 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Klineda4bfa82015-04-30 12:58:40 +09001035 if (enable == isEnabled) {
1036 return; // Nothing to do.
1037 }
1038
1039 if (enable) {
1040 handleRegisterNetworkRequest(new NetworkRequestInfo(
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001041 null, networkRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +09001042 } else {
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001043 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID);
Erik Klineda4bfa82015-04-30 12:58:40 +09001044 }
1045 }
1046
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001047 private void handleConfigureAlwaysOnNetworks() {
1048 handleAlwaysOnNetworkRequest(
1049 mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
1050 handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
1051 false);
1052 }
1053
Erik Klineda4bfa82015-04-30 12:58:40 +09001054 private void registerSettingsCallbacks() {
1055 // Watch for global HTTP proxy changes.
1056 mSettingsObserver.observe(
1057 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1058 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1059
1060 // Watch for whether or not to keep mobile data always on.
1061 mSettingsObserver.observe(
1062 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07001063 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1064
1065 // Watch for whether or not to keep wifi always on.
1066 mSettingsObserver.observe(
1067 Settings.Global.getUriFor(Settings.Global.WIFI_ALWAYS_REQUESTED),
1068 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Erik Klineda4bfa82015-04-30 12:58:40 +09001069 }
1070
Erik Klinea24d4592018-01-11 21:07:29 +09001071 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -07001072 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1073 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +09001074 }
1075 }
1076
Robert Greenwalt34524f02014-05-18 16:22:10 -07001077 private synchronized int nextNetworkRequestId() {
1078 return mNextNetworkRequestId++;
1079 }
1080
Paul Jensen67b0b072015-06-10 11:22:17 -04001081 @VisibleForTesting
1082 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001083 synchronized (mNetworkForNetId) {
1084 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1085 int netId = mNextNetId;
1086 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1087 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001088 if (!mNetIdInUse.get(netId)) {
1089 mNetIdInUse.put(netId, true);
1090 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001091 }
1092 }
1093 }
1094 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001095 }
1096
Chalard Jeanc0982912018-06-07 16:11:34 +09001097 private NetworkState getFilteredNetworkState(int networkType, int uid) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001098 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001099 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1100 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001101 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001102 state = nai.getNetworkState();
1103 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001104 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001105 final NetworkInfo info = new NetworkInfo(networkType, 0,
1106 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1108 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001109 final NetworkCapabilities capabilities = new NetworkCapabilities();
1110 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1111 !info.isRoaming());
1112 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001113 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001114 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001115 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001116 return state;
1117 } else {
1118 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001119 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001120 }
1121
junyulai4a192e22018-06-13 15:00:37 +08001122 @VisibleForTesting
1123 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001124 if (network == null) {
1125 return null;
1126 }
Erik Kline736353a2018-03-21 07:18:33 -07001127 return getNetworkAgentInfoForNetId(network.netId);
1128 }
1129
1130 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001131 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001132 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001133 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001135
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001136 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001137 synchronized (mVpns) {
1138 if (!mLockdownEnabled) {
1139 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001140 Vpn vpn = mVpns.get(user);
1141 if (vpn != null && vpn.appliesToUid(uid)) {
1142 return vpn.getUnderlyingNetworks();
1143 }
1144 }
1145 }
1146 return null;
1147 }
1148
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001150 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001151
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001152 final Network[] networks = getVpnUnderlyingNetworks(uid);
1153 if (networks != null) {
1154 // getUnderlyingNetworks() returns:
1155 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1156 // empty array => the VPN explicitly said "no default network".
1157 // non-empty array => the VPN specified one or more default networks; we use the
1158 // first one.
1159 if (networks.length > 0) {
1160 nai = getNetworkAgentInfoForNetwork(networks[0]);
1161 } else {
1162 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001163 }
1164 }
1165
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 return nai.getNetworkState();
1168 } else {
1169 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001171 }
1172
1173 /**
1174 * Check if UID should be blocked from using the network with the given LinkProperties.
1175 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1177 boolean ignoreBlocked) {
1178 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001179 if (ignoreBlocked) {
1180 return false;
1181 }
Robin Lee17e61832016-05-09 13:46:28 +01001182 synchronized (mVpns) {
1183 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
junyulai8ed89152018-10-25 10:56:17 +08001184 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
Robin Lee17e61832016-05-09 13:46:28 +01001185 return true;
1186 }
1187 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001188 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001189 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001190 }
1191
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001192 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001193 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1194 return;
1195 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001196 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001197 synchronized (mBlockedAppUids) {
1198 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001199 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001200 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001201 blocked = false;
1202 } else {
1203 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001204 }
1205 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001206 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1207 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1208 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001209 }
1210
junyulai05986c62018-08-07 19:50:45 +08001211 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net,
1212 boolean blocked) {
1213 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1214 return;
1215 }
1216 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1217 log(String.format("Blocked status changed to %s for %d(%d) on netId %d", blocked,
1218 nri.mUid, nri.request.requestId, net.netId));
1219 mNetworkInfoBlockingLogs.log(action + " " + nri.mUid);
1220 }
1221
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001222 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001223 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1224 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001225 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001226 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001227 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001228 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1229
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001230 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001231 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001232 }
Hugo Benichi69744342017-11-27 10:57:16 +09001233 synchronized (mVpns) {
1234 if (mLockdownTracker != null) {
1235 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1236 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001237 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001238 }
1239
1240 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 * Return NetworkInfo for the active (i.e., connected) network interface.
1242 * It is assumed that at most one network is active at a time. If more
1243 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001244 * @return the info for the active network, or {@code null} if none is
1245 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001247 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001249 enforceAccessPermission();
1250 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001251 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001252 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001253 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1254 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256
Paul Jensen31a94f42015-02-13 14:18:39 -05001257 @Override
1258 public Network getActiveNetwork() {
1259 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001260 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001261 }
1262
1263 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001264 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001265 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001266 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001267 }
1268
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001269 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001270 final int user = UserHandle.getUserId(uid);
1271 int vpnNetId = NETID_UNSET;
1272 synchronized (mVpns) {
1273 final Vpn vpn = mVpns.get(user);
Chalard Jean26400492018-04-18 20:18:38 +09001274 // TODO : now that capabilities contain the UID, the appliesToUid test should
1275 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001276 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1277 }
1278 NetworkAgentInfo nai;
1279 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001280 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jean26400492018-04-18 20:18:38 +09001281 if (nai != null) {
1282 final NetworkCapabilities requiredCaps =
1283 createDefaultNetworkCapabilitiesForUid(uid);
1284 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1285 return nai.network;
1286 }
1287 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001288 }
1289 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001290 if (nai != null
1291 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1292 nai = null;
1293 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001294 return nai != null ? nai.network : null;
1295 }
1296
Lorenzo Colitti18660282016-07-04 12:55:44 +09001297 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001298 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1299 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001300 final int uid = Binder.getCallingUid();
1301 NetworkState state = getUnfilteredActiveNetworkState(uid);
1302 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001303 }
1304
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001305 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001306 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001307 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001308 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001309 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001310 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001311 }
1312
1313 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 public NetworkInfo getNetworkInfo(int networkType) {
1315 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001316 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001317 if (getVpnUnderlyingNetworks(uid) != null) {
1318 // A VPN is active, so we may need to return one of its underlying networks. This
1319 // information is not available in LegacyTypeTracker, so we have to get it from
1320 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001321 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001322 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001323 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001324 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001325 }
1326 }
Chalard Jeanc0982912018-06-07 16:11:34 +09001327 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001328 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001331 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001332 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001333 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001334 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001335 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001336 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001337 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001338 return state.networkInfo;
1339 } else {
1340 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001341 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001342 }
1343
1344 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 public NetworkInfo[] getAllNetworkInfo() {
1346 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001347 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001348 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1349 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001350 NetworkInfo info = getNetworkInfo(networkType);
1351 if (info != null) {
1352 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001355 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001358 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001359 public Network getNetworkForType(int networkType) {
1360 enforceAccessPermission();
1361 final int uid = Binder.getCallingUid();
Chalard Jeanc0982912018-06-07 16:11:34 +09001362 NetworkState state = getFilteredNetworkState(networkType, uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001363 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001364 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001365 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001366 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001367 }
1368
1369 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001370 public Network[] getAllNetworks() {
1371 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001372 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001373 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001374 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001375 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001376 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001377 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001378 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001379 }
1380
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001381 @Override
1382 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1383 // The basic principle is: if an app's traffic could possibly go over a
1384 // network, without the app doing anything multinetwork-specific,
1385 // (hence, by "default"), then include that network's capabilities in
1386 // the array.
1387 //
1388 // In the normal case, app traffic only goes over the system's default
1389 // network connection, so that's the only network returned.
1390 //
1391 // With a VPN in force, some app traffic may go into the VPN, and thus
1392 // over whatever underlying networks the VPN specifies, while other app
1393 // traffic may go over the system default network (e.g.: a split-tunnel
1394 // VPN, or an app disallowed by the VPN), so the set of networks
1395 // returned includes the VPN's underlying networks and the system
1396 // default.
1397 enforceAccessPermission();
1398
Chalard Jean4133a122018-06-04 13:33:12 +09001399 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001400
1401 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001402 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001403 if (nc != null) {
1404 result.put(nai.network, nc);
1405 }
1406
Hugo Benichi69744342017-11-27 10:57:16 +09001407 synchronized (mVpns) {
1408 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001409 Vpn vpn = mVpns.get(userId);
1410 if (vpn != null) {
1411 Network[] networks = vpn.getUnderlyingNetworks();
1412 if (networks != null) {
1413 for (Network network : networks) {
1414 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001415 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001416 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001417 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001418 }
1419 }
1420 }
1421 }
1422 }
1423 }
1424
1425 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1426 out = result.values().toArray(out);
1427 return out;
1428 }
1429
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001430 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001431 public boolean isNetworkSupported(int networkType) {
1432 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001433 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001434 }
1435
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001436 /**
1437 * Return LinkProperties for the active (i.e., connected) default
1438 * network interface. It is assumed that at most one default network
1439 * is active at a time. If more than one is active, it is indeterminate
1440 * which will be returned.
1441 * @return the ip properties for the active network, or {@code null} if
1442 * none is active
1443 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001444 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001445 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001446 enforceAccessPermission();
1447 final int uid = Binder.getCallingUid();
1448 NetworkState state = getUnfilteredActiveNetworkState(uid);
1449 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001450 }
1451
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001452 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001453 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001454 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001455 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1456 if (nai != null) {
1457 synchronized (nai) {
1458 return new LinkProperties(nai.linkProperties);
1459 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001460 }
1461 return null;
1462 }
1463
Robert Greenwalt12e67352014-05-13 21:41:06 -07001464 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001465 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001466 public LinkProperties getLinkProperties(Network network) {
1467 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001468 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1469 }
1470
1471 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1472 if (nai == null) {
1473 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001474 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001475 synchronized (nai) {
1476 return new LinkProperties(nai.linkProperties);
1477 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001478 }
1479
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001480 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001481 if (nai != null) {
1482 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001483 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001484 return networkCapabilitiesRestrictedForCallerPermissions(
1485 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001486 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001487 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001488 }
1489 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001490 return null;
1491 }
1492
1493 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001494 public NetworkCapabilities getNetworkCapabilities(Network network) {
1495 enforceAccessPermission();
1496 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1497 }
1498
Chalard Jeanb03a6222018-04-11 21:09:10 +09001499 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001500 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001501 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean26400492018-04-18 20:18:38 +09001502 if (!checkSettingsPermission(callerPid, callerUid)) {
1503 newNc.setUids(null);
1504 newNc.setSSID(null);
1505 }
Etan Cohen836ad572018-12-30 17:59:59 -08001506 if (newNc.getNetworkSpecifier() != null) {
1507 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1508 }
Chalard Jeanb03a6222018-04-11 21:09:10 +09001509 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001510 }
1511
Chalard Jeanb552c462018-02-21 18:43:54 +09001512 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1513 if (!checkSettingsPermission()) {
1514 nc.setSingleUid(Binder.getCallingUid());
1515 }
1516 }
1517
Chalard Jean26aa91a2018-03-20 19:13:57 +09001518 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1519 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1520 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1521 }
1522 }
1523
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001524 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001525 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001526 // Require internal since we're handing out IMSI details
1527 enforceConnectivityInternalPermission();
1528
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001529 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001530 for (Network network : getAllNetworks()) {
1531 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1532 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001533 // TODO (b/73321673) : NetworkState contains a copy of the
1534 // NetworkCapabilities, which may contain UIDs of apps to which the
1535 // network applies. Should the UIDs be cleared so as not to leak or
1536 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001537 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001538 }
1539 }
1540 return result.toArray(new NetworkState[result.size()]);
1541 }
1542
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001543 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001544 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001545 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001546 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1547 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1548 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001549 }
1550
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001551 @Override
1552 public boolean isActiveNetworkMetered() {
1553 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001554
Eric Enslenc81ef192018-02-07 18:03:53 -08001555 final int uid = Binder.getCallingUid();
1556 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001557 if (caps != null) {
1558 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1559 } else {
1560 // Always return the most conservative value
1561 return true;
1562 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001563 }
1564
Jeff Sharkey216c1812012-08-05 14:29:23 -07001565 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1566 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001567 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001568 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001569 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001570 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001571 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001572
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001573 /**
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001574 * Ensures that the system cannot call a particular method.
1575 */
1576 private boolean disallowedBecauseSystemCaller() {
1577 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
1578 // requestRouteToHost.
1579 if (isSystem(Binder.getCallingUid())) {
1580 log("This method exists only for app backwards compatibility"
1581 + " and must not be called by system services.");
1582 return true;
1583 }
1584 return false;
1585 }
1586
1587 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 * Ensure that a network route exists to deliver traffic to the specified
1589 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001590 * @param networkType the type of the network over which traffic to the
1591 * specified host is to be routed
1592 * @param hostAddress the IP address of the host to which the route is
1593 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 * @return {@code true} on success, {@code false} on failure
1595 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001596 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001597 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
Lorenzo Colitti2e31a7c2018-09-28 11:31:55 +09001598 if (disallowedBecauseSystemCaller()) {
1599 return false;
1600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001602 if (mProtectedNetworks.contains(networkType)) {
1603 enforceConnectivityInternalPermission();
1604 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001605
Chad Brubakerc0234532014-02-14 13:24:29 -08001606 InetAddress addr;
1607 try {
1608 addr = InetAddress.getByAddress(hostAddress);
1609 } catch (UnknownHostException e) {
1610 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1611 return false;
1612 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001615 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 return false;
1617 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001618
1619 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1620 if (nai == null) {
1621 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1622 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1623 } else {
1624 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1625 }
1626 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001627 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001628
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001629 DetailedState netState;
1630 synchronized (nai) {
1631 netState = nai.networkInfo.getDetailedState();
1632 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001633
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001634 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001635 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001636 log("requestRouteToHostAddress on down network "
1637 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001638 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001639 }
1640 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001642
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001643 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001644 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001645 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001646 LinkProperties lp;
1647 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001648 synchronized (nai) {
1649 lp = nai.linkProperties;
1650 netId = nai.network.netId;
1651 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001652 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001653 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1654 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001655 } finally {
1656 Binder.restoreCallingIdentity(token);
1657 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001658 }
1659
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001660 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001661 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001662 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001663 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001664 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001665 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001666 if (bestRoute.getGateway().equals(addr)) {
1667 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001668 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001669 } else {
1670 // if we will connect to this through another route, add a direct route
1671 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001672 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001673 }
1674 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001675 if (DBG) log("Adding legacy route " + bestRoute +
1676 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001677 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08001678 mNMS.addLegacyRouteForNetId(netId, bestRoute, uid);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001679 } catch (Exception e) {
1680 // never crash - catch them all
1681 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001682 return false;
1683 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001684 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686
dalyk7301aa42018-03-05 12:42:22 -05001687 @VisibleForTesting
1688 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1689 @Override
1690 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1691 String hostname, boolean validated) {
1692 try {
1693 mHandler.sendMessage(mHandler.obtainMessage(
1694 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1695 new PrivateDnsValidationUpdate(netId,
1696 InetAddress.parseNumericAddress(ipAddress),
1697 hostname, validated)));
1698 } catch (IllegalArgumentException e) {
1699 loge("Error parsing ip address in validation event");
1700 }
1701 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001702
1703 @Override
1704 public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
1705 String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
1706 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
1707 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
1708 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
1709 // event callback for certain nai. e.g. cellular. Register here to pass to
1710 // NetworkMonitor instead.
1711 // TODO: Move the Dns Event to NetworkMonitor. Use Binder.clearCallingIdentity() in
1712 // registerNetworkAgent to have NetworkMonitor created with system process as design
1713 // expectation. Also, NetdEventListenerService only allow one callback from each
1714 // caller type. Need to re-factor NetdEventListenerService to allow multiple
1715 // NetworkMonitor registrants.
1716 if (nai != null && nai.satisfies(mDefaultRequest)) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09001717 try {
1718 nai.networkMonitor().notifyDnsResponse(returnCode);
1719 } catch (RemoteException e) {
1720 e.rethrowFromSystemServer();
1721 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001722 }
1723 }
dalyk7301aa42018-03-05 12:42:22 -05001724 };
1725
1726 @VisibleForTesting
1727 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001728 final IIpConnectivityMetrics ipConnectivityMetrics =
1729 IIpConnectivityMetrics.Stub.asInterface(
1730 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1731 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001732 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001733 return;
dalyk7301aa42018-03-05 12:42:22 -05001734 }
1735
1736 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001737 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001738 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1739 mNetdEventCallback);
1740 } catch (Exception e) {
1741 loge("Error registering netd callback: " + e);
1742 }
1743 }
1744
Jeff Sharkey75d31892018-01-18 22:01:59 +09001745 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001746 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001747 public void onUidRulesChanged(int uid, int uidRules) {
junyulai05986c62018-08-07 19:50:45 +08001748 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_RULES_CHANGED, uid, uidRules));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001749 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001750 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001751 public void onRestrictBackgroundChanged(boolean restrictBackground) {
junyulai05986c62018-08-07 19:50:45 +08001752 // caller is NPMS, since we only register with them
1753 if (LOGD_BLOCKED_NETWORKINFO) {
1754 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1755 }
1756 mHandler.sendMessage(mHandler.obtainMessage(
1757 EVENT_DATA_SAVER_CHANGED, restrictBackground ? 1 : 0, 0));
1758
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001759 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001760 if (restrictBackground) {
1761 log("onRestrictBackgroundChanged(true): disabling tethering");
1762 mTethering.untetherAll();
1763 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001764 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001765 };
1766
junyulai05986c62018-08-07 19:50:45 +08001767 void handleUidRulesChanged(int uid, int newRules) {
1768 // skip update when we've already applied rules
1769 final int oldRules = mUidRules.get(uid, RULE_NONE);
1770 if (oldRules == newRules) return;
1771
1772 maybeNotifyNetworkBlockedForNewUidRules(uid, newRules);
1773
1774 if (newRules == RULE_NONE) {
1775 mUidRules.delete(uid);
1776 } else {
1777 mUidRules.put(uid, newRules);
1778 }
1779 }
1780
1781 void handleRestrictBackgroundChanged(boolean restrictBackground) {
1782 if (mRestrictBackground == restrictBackground) return;
1783
1784 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1785 final boolean curMetered = nai.networkCapabilities.isMetered();
1786 maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
1787 restrictBackground);
1788 }
1789
1790 mRestrictBackground = restrictBackground;
1791 }
1792
1793 private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
1794 boolean isBackgroundRestricted) {
1795 synchronized (mVpns) {
1796 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1797 // Because the return value of this function depends on the list of UIDs the
1798 // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
1799 // list all state depending on the return value of this function has to be recomputed.
1800 // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
1801 // send the necessary onBlockedStatusChanged callbacks.
junyulai8ed89152018-10-25 10:56:17 +08001802 if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
junyulai05986c62018-08-07 19:50:45 +08001803 return true;
1804 }
1805 }
1806
1807 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
1808 isNetworkMetered, isBackgroundRestricted);
1809 }
1810
Robin Lee3b3dd942015-05-12 18:14:58 +01001811 /**
1812 * Require that the caller is either in the same user or has appropriate permission to interact
1813 * across users.
1814 *
1815 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1816 */
1817 private void enforceCrossUserPermission(int userId) {
1818 if (userId == UserHandle.getCallingUserId()) {
1819 // Not a cross-user call.
1820 return;
1821 }
1822 mContext.enforceCallingOrSelfPermission(
1823 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1824 "ConnectivityService");
1825 }
1826
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001827 private void enforceAnyPermissionOf(String... permissions) {
1828 for (String permission : permissions) {
1829 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
1830 return;
1831 }
1832 }
1833 throw new SecurityException(
1834 "Requires one of the following permissions: " + String.join(", ", permissions) + ".");
1835 }
1836
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001837 private void enforceInternetPermission() {
1838 mContext.enforceCallingOrSelfPermission(
1839 android.Manifest.permission.INTERNET,
1840 "ConnectivityService");
1841 }
1842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001844 mContext.enforceCallingOrSelfPermission(
1845 android.Manifest.permission.ACCESS_NETWORK_STATE,
1846 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 }
1848
1849 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001850 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 }
1852
Charles He36738632017-05-15 17:07:18 +01001853 private void enforceSettingsPermission() {
1854 mContext.enforceCallingOrSelfPermission(
1855 android.Manifest.permission.NETWORK_SETTINGS,
1856 "ConnectivityService");
1857 }
1858
Chalard Jeanb552c462018-02-21 18:43:54 +09001859 private boolean checkSettingsPermission() {
1860 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1861 android.Manifest.permission.NETWORK_SETTINGS);
1862 }
1863
1864 private boolean checkSettingsPermission(int pid, int uid) {
1865 return PERMISSION_GRANTED == mContext.checkPermission(
1866 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1867 }
1868
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001869 private void enforceTetherAccessPermission() {
1870 mContext.enforceCallingOrSelfPermission(
1871 android.Manifest.permission.ACCESS_NETWORK_STATE,
1872 "ConnectivityService");
1873 }
1874
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001875 private void enforceConnectivityInternalPermission() {
1876 mContext.enforceCallingOrSelfPermission(
1877 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1878 "ConnectivityService");
1879 }
1880
Lorenzo Colittif5845d12018-10-09 18:55:11 +09001881 private void enforceNetworkStackSettingsOrSetup() {
1882 enforceAnyPermissionOf(
1883 android.Manifest.permission.NETWORK_SETTINGS,
1884 android.Manifest.permission.NETWORK_SETUP_WIZARD,
1885 android.Manifest.permission.NETWORK_STACK);
1886 }
1887
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07001888 private boolean checkNetworkStackPermission() {
1889 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1890 android.Manifest.permission.NETWORK_STACK);
1891 }
1892
Hugo Benichi514da602016-07-19 15:59:27 +09001893 private void enforceConnectivityRestrictedNetworksPermission() {
1894 try {
1895 mContext.enforceCallingOrSelfPermission(
1896 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1897 "ConnectivityService");
1898 return;
1899 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1900 enforceConnectivityInternalPermission();
1901 }
1902
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001903 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001904 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001905 }
1906
Lorenzo Colitti18660282016-07-04 12:55:44 +09001907 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001908 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001909 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001910 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001911 }
1912
1913 private void sendInetConditionBroadcast(NetworkInfo info) {
1914 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1915 }
1916
Wink Saville628b0852011-08-04 15:01:58 -07001917 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001918 synchronized (mVpns) {
1919 if (mLockdownTracker != null) {
1920 info = new NetworkInfo(info);
1921 mLockdownTracker.augmentNetworkInfo(info);
1922 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001923 }
1924
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001925 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001926 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001927 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 if (info.isFailover()) {
1929 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1930 info.setFailover(false);
1931 }
1932 if (info.getReason() != null) {
1933 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1934 }
1935 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001936 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1937 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001939 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001940 return intent;
1941 }
1942
1943 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1944 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1945 }
1946
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001947 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001948 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1949 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1950 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001951 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001952 final long ident = Binder.clearCallingIdentity();
1953 try {
1954 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1955 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1956 } finally {
1957 Binder.restoreCallingIdentity(ident);
1958 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001959 }
1960
Mike Lockwood0f79b542009-08-14 14:18:49 -04001961 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001962 synchronized (this) {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09001963 if (!mSystemReady
1964 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001965 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001966 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001967 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001968 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001969 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001970 }
1971
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001972 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001973 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001974 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001975 final NetworkInfo ni = intent.getParcelableExtra(
1976 ConnectivityManager.EXTRA_NETWORK_INFO);
1977 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1978 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1979 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001980 } else {
1981 BroadcastOptions opts = BroadcastOptions.makeBasic();
1982 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1983 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001984 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001985 final IBatteryStats bs = BatteryStatsService.getService();
1986 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001987 bs.noteConnectivityChanged(intent.getIntExtra(
1988 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001989 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001990 } catch (RemoteException e) {
1991 }
Chad Brubakerac925012018-03-08 10:37:09 -08001992 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001993 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001994 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001995 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001996 } finally {
1997 Binder.restoreCallingIdentity(ident);
1998 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001999 }
2000 }
2001
2002 void systemReady() {
Chalard Jean655ad152018-06-08 12:47:42 +09002003 mProxyTracker.loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05002004 registerNetdEventCallback();
markchiena6c72872018-11-13 18:34:56 +09002005 mTethering.systemReady();
Wink Saville948282b2013-08-29 08:55:16 -07002006
Hugo Benichi20035e02017-04-26 14:53:28 +09002007 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04002008 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002009 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002010 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08002011 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04002012 }
2013 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002014
Robin Lee244ce8e2016-01-05 18:03:46 +00002015 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
2016 // for user to unlock device too.
2017 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002018
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07002019 // Create network requests for always-on networks.
2020 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
Erik Klineda4bfa82015-04-30 12:58:40 +09002021
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002022 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002023
2024 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
2026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07002029 *
2030 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002031 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07002032 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002033 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2034 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07002035
2036 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002037 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07002038
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 if (networkAgent.networkCapabilities.hasTransport(
2040 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002041 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2042 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07002043 10);
Haoyu Bai04124232012-06-28 15:26:19 -07002044 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002045 } else if (networkAgent.networkCapabilities.hasTransport(
2046 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002047 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2048 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07002049 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002050 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07002051 } else {
2052 // do not track any other networks
2053 timeout = 0;
2054 }
2055
Robert Greenwalt7b816022014-04-18 15:25:25 -07002056 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07002057 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002058 mNMS.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002059 } catch (Exception e) {
2060 // You shall not crash!
2061 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002062 }
2063 }
2064 }
2065
2066 /**
2067 * Remove data activity tracking when network disconnects.
2068 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2070 final String iface = networkAgent.linkProperties.getInterfaceName();
2071 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07002072
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2074 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07002075 try {
Chalard Jean4d660112018-06-04 16:52:49 +09002076 // the call fails silently if no idle timer setup for this interface
Luke Huang4e25ec62018-09-27 16:58:23 +08002077 mNMS.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07002078 } catch (Exception e) {
2079 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07002080 }
2081 }
2082 }
2083
2084 /**
Chiachang Wanga6093042018-09-28 22:42:48 +08002085 * Update data activity tracking when network state is updated.
2086 */
2087 private void updateDataActivityTracking(NetworkAgentInfo newNetwork,
2088 NetworkAgentInfo oldNetwork) {
2089 if (newNetwork != null) {
2090 setupDataActivityTracking(newNetwork);
2091 }
2092 if (oldNetwork != null) {
2093 removeDataActivityTracking(oldNetwork);
2094 }
2095 }
2096 /**
Chalard Jean4d660112018-06-04 16:52:49 +09002097 * Reads the network specific MTU size from resources.
sy.yun9d9b74a2013-09-02 05:24:09 +09002098 * and set it on it's iface.
2099 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07002100 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2101 final String iface = newLp.getInterfaceName();
2102 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09002103 if (oldLp == null && mtu == 0) {
2104 // Silently ignore unset MTU value.
2105 return;
2106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002107 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2108 if (VDBG) log("identical MTU - not setting");
2109 return;
2110 }
Robert Greenwalt43074032014-08-15 17:53:05 -07002111 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002112 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 return;
2114 }
sy.yun9d9b74a2013-09-02 05:24:09 +09002115
w1997615afd812014-08-05 15:18:11 -07002116 // Cannot set MTU without interface name
2117 if (TextUtils.isEmpty(iface)) {
2118 loge("Setting MTU size with null iface.");
2119 return;
2120 }
2121
Robert Greenwalt7b816022014-04-18 15:25:25 -07002122 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002123 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Luke Huang4e25ec62018-09-27 16:58:23 +08002124 mNMS.setMtu(iface, mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 } catch (Exception e) {
2126 Slog.e(TAG, "exception in setMtu()" + e);
2127 }
2128 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002129
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002130 @VisibleForTesting
2131 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04002132 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
2133
2134 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04002135 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002136 protected MockableSystemProperties getSystemProperties() {
2137 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04002138 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002139
lucaslin041a1af2018-11-28 19:27:52 +08002140 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002141 String[] values = null;
2142 if (tcpBufferSizes != null) {
2143 values = tcpBufferSizes.split(",");
2144 }
2145
2146 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002147 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002148 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2149 values = tcpBufferSizes.split(",");
2150 }
2151
2152 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2153
2154 try {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09002155 if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002156
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002157 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2158 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2159 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002160 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng7f14dbc2018-11-08 17:36:21 -08002161 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07002162 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002163 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002164
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002165 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002166 Settings.Global.TCP_DEFAULT_INIT_RWND,
2167 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002168 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2169 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002170 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08002171 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002172 }
2173
Robert Greenwalt562cc542014-05-15 18:07:26 -07002174 @Override
2175 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002176 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07002177 NETWORK_RESTORE_DELAY_PROP_NAME);
2178 if(restoreDefaultNetworkDelayStr != null &&
2179 restoreDefaultNetworkDelayStr.length() != 0) {
2180 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01002181 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002182 } catch (NumberFormatException e) {
2183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002185 // if the system property isn't set, use the value for the apn type
2186 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2187
2188 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2189 (mNetConfigs[networkType] != null)) {
2190 ret = mNetConfigs[networkType].restoreTime;
2191 }
2192 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 }
2194
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002195 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2196 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2197 final long DIAG_TIME_MS = 5000;
Hugo Benichia2a917c2018-09-03 08:19:02 +09002198 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002199 // Start gathering diagnostic information.
2200 netDiags.add(new NetworkDiagnostics(
2201 nai.network,
2202 new LinkProperties(nai.linkProperties), // Must be a copy.
2203 DIAG_TIME_MS));
2204 }
2205
2206 for (NetworkDiagnostics netDiag : netDiags) {
2207 pw.println();
2208 netDiag.waitForMeasurements();
2209 netDiag.dump(pw);
2210 }
2211 }
2212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002214 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002215 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2216 }
2217
2218 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002219 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002220 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002221 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002222
Erik Kline3f8306b2018-05-01 16:51:44 +09002223 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002224 dumpNetworkDiagnostics(pw);
2225 return;
Erik Kline3f8306b2018-05-01 16:51:44 +09002226 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09002227 mTethering.dump(fd, pw, args);
2228 return;
Hugo Benichi14683812018-09-03 08:32:56 +09002229 } else if (ArrayUtils.contains(args, NETWORK_ARG)) {
2230 dumpNetworks(pw);
2231 return;
2232 } else if (ArrayUtils.contains(args, REQUEST_ARG)) {
2233 dumpNetworkRequests(pw);
2234 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002235 }
Erik Kline379747a2015-06-05 17:47:34 +09002236
Lorenzo Colittie3805462015-06-03 11:18:24 +09002237 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002238 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002239 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002240 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002241 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002242 pw.println();
2243
Paul Jensen85cf78e2015-06-25 13:25:07 -04002244 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002245 pw.print("Active default network: ");
2246 if (defaultNai == null) {
2247 pw.println("none");
2248 } else {
2249 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002251 pw.println();
2252
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002253 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002254 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002255 dumpNetworks(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002256 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002257 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002258
junyulai05986c62018-08-07 19:50:45 +08002259 pw.print("Restrict background: ");
2260 pw.println(mRestrictBackground);
2261 pw.println();
2262
2263 pw.println("Status for known UIDs:");
2264 pw.increaseIndent();
2265 final int size = mUidRules.size();
2266 for (int i = 0; i < size; i++) {
2267 // Don't crash if the array is modified while dumping in bugreports.
2268 try {
2269 final int uid = mUidRules.keyAt(i);
2270 final int uidRules = mUidRules.get(uid, RULE_NONE);
2271 pw.println("UID=" + uid + " rules=" + uidRulesToString(uidRules));
2272 } catch (ArrayIndexOutOfBoundsException e) {
2273 pw.println(" ArrayIndexOutOfBoundsException");
2274 } catch (ConcurrentModificationException e) {
2275 pw.println(" ConcurrentModificationException");
2276 }
2277 }
2278 pw.println();
2279 pw.decreaseIndent();
2280
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002281 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002282 pw.increaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002283 dumpNetworkRequests(pw);
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002284 pw.decreaseIndent();
Hugo Benichi14683812018-09-03 08:32:56 +09002285 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002286
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002287 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002288
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002289 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002290 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002291
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002292 pw.println();
2293 mKeepaliveTracker.dump(pw);
2294
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002295 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002296 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002297
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002298 pw.println();
2299 mMultipathPolicyTracker.dump(pw);
2300
Erik Kline3f8306b2018-05-01 16:51:44 +09002301 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002302 pw.println();
Erik Kline7523eb32015-07-09 18:24:03 +09002303 pw.println("mNetworkRequestInfoLogs (most recent first):");
2304 pw.increaseIndent();
2305 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2306 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002307
2308 pw.println();
2309 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2310 pw.increaseIndent();
2311 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2312 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002313
2314 pw.println();
2315 pw.println("NetTransition WakeLock activity (most recent first):");
2316 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002317 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2318 pw.println("total releases: " + mTotalWakelockReleases);
2319 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2320 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2321 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2322 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2323 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2324 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002325 mWakelockLogs.reverseDump(fd, pw, args);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07002326
2327 pw.println();
2328 pw.println("bandwidth update requests (by uid):");
2329 pw.increaseIndent();
2330 synchronized (mBandwidthRequests) {
2331 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2332 pw.println("[" + mBandwidthRequests.keyAt(i)
2333 + "]: " + mBandwidthRequests.valueAt(i));
2334 }
2335 }
2336 pw.decreaseIndent();
2337
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002338 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 }
2341
Hugo Benichi14683812018-09-03 08:32:56 +09002342 private void dumpNetworks(IndentingPrintWriter pw) {
2343 for (NetworkAgentInfo nai : networksSortedById()) {
2344 pw.println(nai.toString());
2345 pw.increaseIndent();
2346 pw.println(String.format(
2347 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2348 nai.numForegroundNetworkRequests(),
2349 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2350 nai.numBackgroundNetworkRequests(),
2351 nai.numNetworkRequests()));
2352 pw.increaseIndent();
2353 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2354 pw.println(nai.requestAt(i).toString());
2355 }
2356 pw.decreaseIndent();
2357 pw.println("Lingered:");
2358 pw.increaseIndent();
2359 nai.dumpLingerTimers(pw);
2360 pw.decreaseIndent();
2361 pw.decreaseIndent();
2362 }
2363 }
2364
2365 private void dumpNetworkRequests(IndentingPrintWriter pw) {
2366 for (NetworkRequestInfo nri : requestsSortedById()) {
2367 pw.println(nri.toString());
2368 }
2369 }
2370
Hugo Benichia2a917c2018-09-03 08:19:02 +09002371 /**
2372 * Return an array of all current NetworkAgentInfos sorted by network id.
2373 */
2374 private NetworkAgentInfo[] networksSortedById() {
2375 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
2376 networks = mNetworkAgentInfos.values().toArray(networks);
2377 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.netId));
2378 return networks;
2379 }
2380
2381 /**
2382 * Return an array of all current NetworkRequest sorted by request id.
2383 */
2384 private NetworkRequestInfo[] requestsSortedById() {
2385 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
2386 requests = mNetworkRequests.values().toArray(requests);
2387 Arrays.sort(requests, Comparator.comparingInt(nri -> nri.request.requestId));
2388 return requests;
2389 }
2390
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002391 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002392 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002393 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002394 if (officialNai != null && officialNai.equals(nai)) return true;
2395 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002396 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002397 " - " + nai);
2398 }
2399 return false;
2400 }
2401
Robert Greenwalt42acef32009-08-12 16:08:25 -07002402 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002403 private class NetworkStateTrackerHandler extends Handler {
2404 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002405 super(looper);
2406 }
2407
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002408 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002410 default:
2411 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002412 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413 handleAsyncChannelHalfConnect(msg);
2414 break;
2415 }
2416 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2417 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2418 if (nai != null) nai.asyncChannel.disconnect();
2419 break;
2420 }
2421 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2422 handleAsyncChannelDisconnected(msg);
2423 break;
2424 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002425 }
2426 return true;
2427 }
2428
2429 private void maybeHandleNetworkAgentMessage(Message msg) {
2430 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2431 if (nai == null) {
2432 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002433 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002434 }
2435 return;
2436 }
2437
2438 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002439 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002440 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2441 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002442 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2443 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002444 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002445 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002446 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002447 break;
2448 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002449 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002450 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002451 break;
2452 }
2453 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002454 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002455 updateNetworkInfo(nai, info);
2456 break;
2457 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002458 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Roshan Pius64e99ef2018-08-02 10:25:02 -07002459 updateNetworkScore(nai, msg.arg1);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002460 break;
2461 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002462 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002463 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2464 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002465 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002466 nai.networkMisc.explicitlySelected = true;
Roshan Piuseaf8dee2018-08-10 07:36:39 -07002467 nai.networkMisc.acceptUnvalidated = msg.arg1 == 1;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002468 break;
2469 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002470 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002471 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2472 break;
2473 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002474 }
2475 }
2476
2477 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2478 switch (msg.what) {
2479 default:
2480 return false;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002481 case EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002482 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002483 if (nai == null) break;
2484
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002485 final boolean valid = (msg.arg1 == NETWORK_TEST_RESULT_VALID);
Erik Klinea24d4592018-01-11 21:07:29 +09002486 final boolean wasValidated = nai.lastValidated;
2487 final boolean wasDefault = isDefaultNetwork(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002488 if (nai.everCaptivePortalDetected && !nai.captivePortalLoginNotified
2489 && valid) {
2490 nai.captivePortalLoginNotified = true;
2491 showNetworkNotification(nai, NotificationType.LOGGED_IN);
2492 }
Erik Klinea24d4592018-01-11 21:07:29 +09002493
Erik Klinea24d4592018-01-11 21:07:29 +09002494 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2495
Erik Klinea24d4592018-01-11 21:07:29 +09002496 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002497 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2498 ? " with redirect to " + redirectUrl
2499 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002500 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2501 }
Erik Klinea24d4592018-01-11 21:07:29 +09002502 if (valid != nai.lastValidated) {
2503 if (wasDefault) {
2504 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2505 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002506 }
Erik Klinea24d4592018-01-11 21:07:29 +09002507 final int oldScore = nai.getCurrentScore();
2508 nai.lastValidated = valid;
2509 nai.everValidated |= valid;
2510 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2511 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2512 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
lucaslind2e045e02019-01-24 15:55:30 +08002513 if (valid) {
2514 handleFreshlyValidatedNetwork(nai);
2515 // Clear NO_INTERNET and LOST_INTERNET notifications if network becomes
2516 // valid.
2517 mNotifier.clearNotification(nai.network.netId,
2518 NotificationType.NO_INTERNET);
2519 mNotifier.clearNotification(nai.network.netId,
2520 NotificationType.LOST_INTERNET);
2521 }
Erik Klinea24d4592018-01-11 21:07:29 +09002522 }
2523 updateInetCondition(nai);
2524 // Let the NetworkAgent know the state of its network
2525 Bundle redirectUrlBundle = new Bundle();
2526 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2527 nai.asyncChannel.sendMessage(
2528 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2529 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2530 0, redirectUrlBundle);
2531 if (wasValidated && !nai.lastValidated) {
2532 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002533 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002534 break;
2535 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002536 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002537 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002538 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002539 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002540 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002541 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002542 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002543 nai.lastCaptivePortalDetected = visible;
2544 nai.everCaptivePortalDetected |= visible;
lucaslind2e045e02019-01-24 15:55:30 +08002545 if (visible) {
2546 nai.captivePortalLoginNotified = false;
2547 }
Calvin Onbe96da12016-10-11 15:10:46 -07002548 if (nai.lastCaptivePortalDetected &&
2549 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2550 if (DBG) log("Avoiding captive portal network: " + nai.name());
2551 nai.asyncChannel.sendMessage(
2552 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2553 teardownUnneededNetwork(nai);
2554 break;
2555 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002556 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002557 }
2558 if (!visible) {
lucaslind2e045e02019-01-24 15:55:30 +08002559 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
2560 // notifications belong to the same network may be cleared unexpected.
2561 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
2562 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002563 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002564 if (nai == null) {
2565 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2566 break;
2567 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002568 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002569 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002570 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002571 }
Paul Jensen869868be2014-05-15 10:33:05 -04002572 }
Paul Jensen869868be2014-05-15 10:33:05 -04002573 break;
2574 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002575 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002576 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002577 if (nai == null) break;
2578
Erik Kline736353a2018-03-21 07:18:33 -07002579 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002580 break;
2581 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002582 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002583 return true;
2584 }
2585
Calvin Onbe96da12016-10-11 15:10:46 -07002586 private int getCaptivePortalMode() {
2587 return Settings.Global.getInt(mContext.getContentResolver(),
2588 Settings.Global.CAPTIVE_PORTAL_MODE,
2589 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2590 }
2591
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002592 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2593 switch (msg.what) {
2594 default:
2595 return false;
2596 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2597 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2598 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2599 handleLingerComplete(nai);
2600 }
2601 break;
2602 }
2603 }
2604 return true;
2605 }
2606
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002607 @Override
2608 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002609 if (!maybeHandleAsyncChannelMessage(msg) &&
2610 !maybeHandleNetworkMonitorMessage(msg) &&
2611 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002612 maybeHandleNetworkAgentMessage(msg);
2613 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002614 }
2615 }
2616
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002617 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
2618 private final NetworkAgentInfo mNai;
2619
2620 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
2621 mNai = nai;
2622 }
2623
2624 @Override
2625 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
2626 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
2627 new Pair<>(mNai, networkMonitor)));
2628 }
2629
2630 @Override
2631 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
2632 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(EVENT_NETWORK_TESTED,
2633 testResult, mNai.network.netId, redirectUrl));
2634 }
2635
2636 @Override
2637 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
2638 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2639 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
2640 0, mNai.network.netId, PrivateDnsConfig.fromParcel(config)));
2641 }
2642
2643 @Override
2644 public void showProvisioningNotification(String action) {
2645 final Intent intent = new Intent(action);
2646 intent.setPackage(NETWORKSTACK_PACKAGE_NAME);
2647
2648 final PendingIntent pendingIntent;
2649 // Only the system server can register notifications with package "android"
2650 final long token = Binder.clearCallingIdentity();
2651 try {
2652 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
2653 } finally {
2654 Binder.restoreCallingIdentity(token);
2655 }
2656 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2657 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
2658 mNai.network.netId,
2659 pendingIntent));
2660 }
2661
2662 @Override
2663 public void hideProvisioningNotification() {
2664 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
2665 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE,
2666 mNai.network.netId));
2667 }
2668 }
2669
Erik Kline736353a2018-03-21 07:18:33 -07002670 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
Lorenzo Colittied3168e2019-01-23 17:54:08 +09002671 return isValidationRequired(nai.networkCapabilities);
Erik Kline736353a2018-03-21 07:18:33 -07002672 }
2673
Erik Klinec6d00222018-06-26 18:53:43 +09002674 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
2675 if (nai == null) return;
2676 // If the Private DNS mode is opportunistic, reprogram the DNS servers
2677 // in order to restart a validation pass from within netd.
2678 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2679 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
2680 updateDnses(nai.linkProperties, null, nai.network.netId);
2681 }
2682 }
2683
Erik Klinea24d4592018-01-11 21:07:29 +09002684 private void handlePrivateDnsSettingsChanged() {
2685 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2686
2687 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002688 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002689 if (networkRequiresValidation(nai)) {
2690 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2691 }
Erik Klinea24d4592018-01-11 21:07:29 +09002692 }
2693 }
2694
Erik Kline736353a2018-03-21 07:18:33 -07002695 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2696 // Private DNS only ever applies to networks that might provide
2697 // Internet access and therefore also require validation.
2698 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002699
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002700 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline736353a2018-03-21 07:18:33 -07002701 // schedule DNS resolutions. If a DNS resolution is required the
2702 // result will be sent back to us.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002703 try {
2704 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
2705 } catch (RemoteException e) {
2706 e.rethrowFromSystemServer();
2707 }
Erik Kline736353a2018-03-21 07:18:33 -07002708
2709 // With Private DNS bypass support, we can proceed to update the
2710 // Private DNS config immediately, even if we're in strict mode
2711 // and have not yet resolved the provider name into a set of IPs.
2712 updatePrivateDns(nai, cfg);
2713 }
2714
2715 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2716 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002717 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002718 }
2719
dalyk7301aa42018-03-05 12:42:22 -05002720 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2721 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2722 if (nai == null) {
2723 return;
2724 }
2725 mDnsManager.updatePrivateDnsValidation(update);
2726 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2727 }
2728
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002729 private void updateLingerState(NetworkAgentInfo nai, long now) {
2730 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2731 // 2. If the network was lingering and there are now requests, unlinger it.
2732 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2733 // one lingered request, start lingering.
2734 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002735 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002736 if (DBG) log("Unlingering " + nai.name());
2737 nai.unlinger();
2738 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002739 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002740 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002741 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002742 nai.linger();
2743 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2744 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2745 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002746 }
2747
Robert Greenwalt7b816022014-04-18 15:25:25 -07002748 private void handleAsyncChannelHalfConnect(Message msg) {
2749 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002750 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002751 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2752 if (VDBG) log("NetworkFactory connected");
2753 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002754 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002755 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002756 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002757 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002758 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002759 }
2760 } else {
2761 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002762 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002763 }
2764 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2765 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2766 if (VDBG) log("NetworkAgent connected");
2767 // A network agent has requested a connection. Establish the connection.
2768 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2769 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2770 } else {
2771 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002772 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002773 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002774 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002775 synchronized (mNetworkForNetId) {
2776 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002777 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002778 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002779 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002780 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002781 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002782 }
2783 }
2784 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002785
Chalard Jean392971c2018-05-11 20:19:20 +09002786 // This is a no-op if it's called with a message designating a network that has
2787 // already been destroyed, because its reference will not be found in the relevant
2788 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002789 private void handleAsyncChannelDisconnected(Message msg) {
2790 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2791 if (nai != null) {
Chalard Jean392971c2018-05-11 20:19:20 +09002792 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002793 } else {
2794 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2795 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002796 }
2797 }
2798
Chalard Jean392971c2018-05-11 20:19:20 +09002799 // Destroys a network, remove references to it from the internal state managed by
2800 // ConnectivityService, free its interfaces and clean up.
2801 // Must be called on the Handler thread.
2802 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2803 if (DBG) {
2804 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2805 }
2806 // A network agent has disconnected.
2807 // TODO - if we move the logic to the network agent (have them disconnect
2808 // because they lost all their requests or because their score isn't good)
2809 // then they would disconnect organically, report their new state and then
2810 // disconnect the channel.
2811 if (nai.networkInfo.isConnected()) {
2812 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2813 null, null);
2814 }
2815 final boolean wasDefault = isDefaultNetwork(nai);
2816 if (wasDefault) {
2817 mDefaultInetConditionPublished = 0;
2818 // Log default network disconnection before required book-keeping.
2819 // Let rematchAllNetworksAndRequests() below record a new default network event
2820 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2821 // whose timestamps tell how long it takes to recover a default network.
2822 long now = SystemClock.elapsedRealtime();
2823 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2824 }
2825 notifyIfacesChangedForNetworkStats();
2826 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2827 // by other networks that are already connected. Perhaps that can be done by
2828 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2829 // of rematchAllNetworksAndRequests
2830 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2831 mKeepaliveTracker.handleStopAllKeepalives(nai,
2832 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2833 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2834 // Disable wakeup packet monitoring for each interface.
2835 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2836 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09002837 try {
2838 nai.networkMonitor().notifyNetworkDisconnected();
2839 } catch (RemoteException e) {
2840 e.rethrowFromSystemServer();
2841 }
Chalard Jean392971c2018-05-11 20:19:20 +09002842 mNetworkAgentInfos.remove(nai.messenger);
2843 nai.maybeStopClat();
2844 synchronized (mNetworkForNetId) {
2845 // Remove the NetworkAgent, but don't mark the netId as
2846 // available until we've told netd to delete it below.
2847 mNetworkForNetId.remove(nai.network.netId);
2848 }
2849 // Remove all previously satisfied requests.
2850 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2851 NetworkRequest request = nai.requestAt(i);
2852 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2853 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2854 clearNetworkForRequest(request.requestId);
2855 sendUpdatedScoreToFactories(request, 0);
2856 }
2857 }
2858 nai.clearLingerState();
2859 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Chiachang Wanga6093042018-09-28 22:42:48 +08002860 updateDataActivityTracking(null /* newNetwork */, nai);
Chalard Jean392971c2018-05-11 20:19:20 +09002861 notifyLockdownVpn(nai);
2862 ensureNetworkTransitionWakelock(nai.name());
2863 }
2864 mLegacyTypeTracker.remove(nai, wasDefault);
2865 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2866 updateAllVpnsCapabilities();
2867 }
2868 rematchAllNetworksAndRequests(null, 0);
2869 mLingerMonitor.noteDisconnect(nai);
2870 if (nai.created) {
2871 // Tell netd to clean up the configuration for this network
2872 // (routing rules, DNS, etc).
2873 // This may be slow as it requires a lot of netd shelling out to ip and
2874 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2875 // after we've rematched networks with requests which should make a potential
2876 // fallback network the default or requested a new network from the
2877 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2878 // long time.
2879 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08002880 mNMS.removeNetwork(nai.network.netId);
Chalard Jean392971c2018-05-11 20:19:20 +09002881 } catch (Exception e) {
2882 loge("Exception removing network: " + e);
2883 }
2884 mDnsManager.removeNetwork(nai.network);
2885 }
2886 synchronized (mNetworkForNetId) {
2887 mNetIdInUse.delete(nai.network.netId);
2888 }
2889 }
2890
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002891 // If this method proves to be too slow then we can maintain a separate
2892 // pendingIntent => NetworkRequestInfo map.
2893 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2894 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2895 Intent intent = pendingIntent.getIntent();
2896 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2897 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2898 if (existingPendingIntent != null &&
2899 existingPendingIntent.getIntent().filterEquals(intent)) {
2900 return entry.getValue();
2901 }
2902 }
2903 return null;
2904 }
2905
2906 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2907 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2908
2909 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2910 if (existingRequest != null) { // remove the existing request.
2911 if (DBG) log("Replacing " + existingRequest.request + " with "
2912 + nri.request + " because their intents matched.");
2913 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2914 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002915 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002916 }
2917
Erik Klineda4bfa82015-04-30 12:58:40 +09002918 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002919 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002920 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002921 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002922 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002923 if (nri.request.networkCapabilities.hasSignalStrength() &&
2924 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2925 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002926 }
2927 }
2928 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002929 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002930 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002931 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002932 }
2933 }
2934
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002935 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2936 int callingUid) {
2937 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2938 if (nri != null) {
2939 handleReleaseNetworkRequest(nri.request, callingUid);
2940 }
2941 }
2942
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002943 // Determines whether the network is the best (or could become the best, if it validated), for
2944 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2945 // on the value of reason:
2946 //
2947 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2948 // then it should be torn down.
2949 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2950 // then it should be lingered.
2951 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2952 final int numRequests;
2953 switch (reason) {
2954 case TEARDOWN:
2955 numRequests = nai.numRequestNetworkRequests();
2956 break;
2957 case LINGER:
2958 numRequests = nai.numForegroundNetworkRequests();
2959 break;
2960 default:
2961 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2962 return true;
2963 }
2964
2965 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002966 return false;
2967 }
Paul Jensene0988542015-06-25 15:30:08 -04002968 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002969 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2970 // Background requests don't affect lingering.
2971 continue;
2972 }
2973
Paul Jensene0988542015-06-25 15:30:08 -04002974 // If this Network is already the highest scoring Network for a request, or if
2975 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002976 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002977 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002978 // Note that this catches two important cases:
2979 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2980 // is currently satisfying the request. This is desirable when
2981 // cellular ends up validating but WiFi does not.
2982 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002983 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002984 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002985 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002986 nai.getCurrentScoreAsValidated())) {
2987 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002988 }
2989 }
Paul Jensene0988542015-06-25 15:30:08 -04002990 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002991 }
2992
Erik Klineacdd6392016-07-07 16:50:58 +09002993 private NetworkRequestInfo getNriForAppRequest(
2994 NetworkRequest request, int callingUid, String requestedOperation) {
2995 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2996
Robert Greenwalt9258c642014-03-26 16:47:06 -07002997 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002998 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002999 log(String.format("UID %d attempted to %s for unowned request %s",
3000 callingUid, requestedOperation, nri));
3001 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003002 }
Erik Klineacdd6392016-07-07 16:50:58 +09003003 }
3004
3005 return nri;
3006 }
3007
Erik Kline57faba92015-11-25 12:49:38 +09003008 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003009 if (mNetworkRequests.get(nri.request) == null) {
3010 return;
Erik Kline57faba92015-11-25 12:49:38 +09003011 }
Hugo Benichicd952782017-09-20 11:20:14 +09003012 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003013 return;
3014 }
3015 if (VDBG || (DBG && nri.request.isRequest())) {
3016 log("releasing " + nri.request + " (timeout)");
3017 }
3018 handleRemoveNetworkRequest(nri);
3019 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09003020 }
3021
Erik Klineacdd6392016-07-07 16:50:58 +09003022 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09003023 final NetworkRequestInfo nri =
3024 getNriForAppRequest(request, callingUid, "release NetworkRequest");
3025 if (nri == null) {
3026 return;
Erik Kline57faba92015-11-25 12:49:38 +09003027 }
Hugo Benichidba33db2017-03-23 22:40:44 +09003028 if (VDBG || (DBG && nri.request.isRequest())) {
3029 log("releasing " + nri.request + " (release request)");
3030 }
3031 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09003032 }
Erik Klineacdd6392016-07-07 16:50:58 +09003033
Hugo Benichidba33db2017-03-23 22:40:44 +09003034 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09003035 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09003036 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09003037
Erik Klineacdd6392016-07-07 16:50:58 +09003038 synchronized (mUidToNetworkRequestCount) {
3039 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
3040 if (requests < 1) {
3041 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
3042 nri.mUid);
3043 } else if (requests == 1) {
3044 mUidToNetworkRequestCount.removeAt(
3045 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
3046 } else {
3047 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
3048 }
3049 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09003050
Erik Klineacdd6392016-07-07 16:50:58 +09003051 mNetworkRequestInfoLogs.log("RELEASE " + nri);
3052 if (nri.request.isRequest()) {
3053 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09003054 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09003055 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003056 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09003057 nai.removeRequest(nri.request.requestId);
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003058 if (VDBG || DDBG) {
Erik Klineacdd6392016-07-07 16:50:58 +09003059 log(" Removing from current network " + nai.name() +
3060 ", leaving " + nai.numNetworkRequests() + " requests.");
3061 }
3062 // If there are still lingered requests on this network, don't tear it down,
3063 // but resume lingering instead.
3064 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09003065 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09003066 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
3067 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003068 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09003069 wasKept = true;
3070 }
Hugo Benichicd952782017-09-20 11:20:14 +09003071 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003072 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
3073 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09003074 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09003075 }
Erik Klineacdd6392016-07-07 16:50:58 +09003076 }
3077
Erik Klineacdd6392016-07-07 16:50:58 +09003078 // Maintain the illusion. When this request arrived, we might have pretended
3079 // that a network connected to serve it, even though the network was already
3080 // connected. Now that this request has gone away, we might have to pretend
3081 // that the network disconnected. LegacyTypeTracker will generate that
3082 // phantom disconnect for this type.
3083 if (nri.request.legacyType != TYPE_NONE && nai != null) {
3084 boolean doRemove = true;
3085 if (wasKept) {
3086 // check if any of the remaining requests for this network are for the
3087 // same legacy type - if so, don't remove the nai
3088 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3089 NetworkRequest otherRequest = nai.requestAt(i);
3090 if (otherRequest.legacyType == nri.request.legacyType &&
3091 otherRequest.isRequest()) {
3092 if (DBG) log(" still have other legacy request - leaving");
3093 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08003094 }
3095 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07003096 }
3097
Erik Klineacdd6392016-07-07 16:50:58 +09003098 if (doRemove) {
3099 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003100 }
3101 }
Erik Klineacdd6392016-07-07 16:50:58 +09003102
3103 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3104 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3105 nri.request);
3106 }
3107 } else {
3108 // listens don't have a singular affectedNetwork. Check all networks to see
3109 // if this listen request applies and remove it.
3110 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3111 nai.removeRequest(nri.request.requestId);
3112 if (nri.request.networkCapabilities.hasSignalStrength() &&
3113 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3114 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
3115 }
3116 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003117 }
3118 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003119
Lorenzo Colitti18660282016-07-04 12:55:44 +09003120 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003121 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
3122 enforceConnectivityInternalPermission();
3123 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003124 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003125 }
3126
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003127 @Override
3128 public void setAvoidUnvalidated(Network network) {
3129 enforceConnectivityInternalPermission();
3130 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
3131 }
3132
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003133 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
3134 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
3135 " accept=" + accept + " always=" + always);
3136
3137 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3138 if (nai == null) {
3139 // Nothing to do.
3140 return;
3141 }
3142
3143 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003144 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003145 return;
3146 }
3147
3148 if (!nai.networkMisc.explicitlySelected) {
3149 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
3150 }
3151
3152 if (accept != nai.networkMisc.acceptUnvalidated) {
3153 int oldScore = nai.getCurrentScore();
3154 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04003155 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003156 sendUpdatedScoreToFactories(nai);
3157 }
3158
3159 if (always) {
3160 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003161 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003162 }
3163
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003164 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04003165 // Tell the NetworkAgent to not automatically reconnect to the network.
3166 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
Chalard Jean4d660112018-06-04 16:52:49 +09003167 // Teardown the network.
Paul Jensenf95d2202015-07-13 15:19:51 -04003168 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003169 }
3170
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003171 }
3172
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003173 private void handleSetAvoidUnvalidated(Network network) {
3174 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3175 if (nai == null || nai.lastValidated) {
3176 // Nothing to do. The network either disconnected or revalidated.
3177 return;
3178 }
3179 if (!nai.avoidUnvalidated) {
3180 int oldScore = nai.getCurrentScore();
3181 nai.avoidUnvalidated = true;
3182 rematchAllNetworksAndRequests(nai, oldScore);
3183 sendUpdatedScoreToFactories(nai);
3184 }
3185 }
3186
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003187 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003188 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003189 mHandler.sendMessageDelayed(
3190 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
3191 PROMPT_UNVALIDATED_DELAY_MS);
3192 }
3193
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003194 @Override
3195 public void startCaptivePortalApp(Network network) {
3196 enforceConnectivityInternalPermission();
3197 mHandler.post(() -> {
3198 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3199 if (nai == null) return;
3200 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003201 try {
3202 nai.networkMonitor().launchCaptivePortalApp();
3203 } catch (RemoteException e) {
3204 e.rethrowFromSystemServer();
3205 }
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09003206 });
3207 }
3208
Hugo Benichic8e9e122016-09-14 23:23:08 +00003209 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003210 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09003211 }
3212
Remi NGUYEN VAN97f69c22019-01-20 20:35:06 +09003213 @Override
3214 public boolean getAvoidBadWifi() {
3215 if (!checkNetworkStackPermission()) {
3216 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
3217 }
3218 return avoidBadWifi();
3219 }
3220
3221
Erik Kline065ab6e2016-10-02 18:02:14 +09003222 private void rematchForAvoidBadWifiUpdate() {
3223 rematchAllNetworksAndRequests(null, 0);
3224 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
3225 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
3226 sendUpdatedScoreToFactories(nai);
3227 }
3228 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003229 }
3230
Erik Kline065ab6e2016-10-02 18:02:14 +09003231 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003232 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003233 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003234 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003235 if (!configRestrict) {
3236 pw.println("Bad Wi-Fi avoidance: unrestricted");
3237 return;
3238 }
3239
3240 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
3241 pw.increaseIndent();
3242 pw.println("Config restrict: " + configRestrict);
3243
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003244 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003245 String description;
3246 // Can't use a switch statement because strings are legal case labels, but null is not.
3247 if ("0".equals(value)) {
3248 description = "get stuck";
3249 } else if (value == null) {
3250 description = "prompt";
3251 } else if ("1".equals(value)) {
3252 description = "avoid";
3253 } else {
3254 description = value + " (?)";
3255 }
3256 pw.println("User setting: " + description);
3257 pw.println("Network overrides:");
3258 pw.increaseIndent();
Hugo Benichia2a917c2018-09-03 08:19:02 +09003259 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09003260 if (nai.avoidUnvalidated) {
3261 pw.println(nai.name());
3262 }
3263 }
3264 pw.decreaseIndent();
3265 pw.decreaseIndent();
3266 }
3267
lucaslind2e045e02019-01-24 15:55:30 +08003268 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003269 final String action;
3270 switch (type) {
lucaslind2e045e02019-01-24 15:55:30 +08003271 case LOGGED_IN:
3272 action = Settings.ACTION_WIFI_SETTINGS;
3273 mHandler.removeMessages(EVENT_TIMEOUT_NOTIFICATION);
3274 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NOTIFICATION,
3275 nai.network.netId, 0), TIMEOUT_NOTIFICATION_DELAY_MS);
3276 break;
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003277 case NO_INTERNET:
3278 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
3279 break;
3280 case LOST_INTERNET:
3281 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
3282 break;
3283 default:
3284 Slog.wtf(TAG, "Unknown notification type " + type);
3285 return;
3286 }
3287
3288 Intent intent = new Intent(action);
lucaslind2e045e02019-01-24 15:55:30 +08003289 if (type != NotificationType.LOGGED_IN) {
3290 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
3291 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3292 intent.setClassName("com.android.settings",
3293 "com.android.settings.wifi.WifiNoInternetDialog");
3294 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003295
3296 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
3297 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
3298 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
3299 }
3300
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003301 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09003302 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003303 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3304
3305 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
3306 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09003307 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003308 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003309 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
3310 return;
3311 }
lucaslind2e045e02019-01-24 15:55:30 +08003312 showNetworkNotification(nai, NotificationType.NO_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003313 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003314
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003315 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
3316 NetworkCapabilities nc = nai.networkCapabilities;
3317 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07003318
Erik Kline065ab6e2016-10-02 18:02:14 +09003319 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09003320 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslind2e045e02019-01-24 15:55:30 +08003321 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09003322 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003323 }
3324
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003325 @Override
3326 public int getMultipathPreference(Network network) {
3327 enforceAccessPermission();
3328
3329 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06003330 if (nai != null && nai.networkCapabilities
3331 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003332 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
3333 }
3334
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003335 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
3336 if (networkPreference != null) {
3337 return networkPreference;
3338 }
3339
Lorenzo Colitti2de49252017-01-24 18:08:41 +09003340 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
3341 }
3342
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003343 @Override
3344 public NetworkRequest getDefaultRequest() {
3345 return mDefaultRequest;
3346 }
3347
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003348 private class InternalHandler extends Handler {
3349 public InternalHandler(Looper looper) {
3350 super(looper);
3351 }
3352
3353 @Override
3354 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07003355 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003356 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003357 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003358 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07003359 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003360 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07003361 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jeanb9d45fd2018-06-08 14:24:49 +09003362 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07003363 break;
3364 }
Jason Monkdecd2952013-10-10 14:02:51 -04003365 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04003366 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04003367 break;
3368 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003369 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07003370 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3371 break;
3372 }
3373 case EVENT_UNREGISTER_NETWORK_FACTORY: {
3374 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07003375 break;
3376 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003377 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003378 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
3379 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
3380 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003381 break;
3382 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003383 case EVENT_REGISTER_NETWORK_REQUEST:
3384 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003385 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003386 break;
3387 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003388 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3389 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003390 handleRegisterNetworkRequestWithIntent(msg);
3391 break;
3392 }
Erik Kline57faba92015-11-25 12:49:38 +09003393 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3394 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3395 handleTimedOutNetworkRequest(nri);
3396 break;
3397 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003398 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3399 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3400 break;
3401 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003402 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003403 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003404 break;
3405 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003406 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003407 Network network = (Network) msg.obj;
3408 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003409 break;
3410 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003411 case EVENT_SET_AVOID_UNVALIDATED: {
3412 handleSetAvoidUnvalidated((Network) msg.obj);
3413 break;
3414 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003415 case EVENT_PROMPT_UNVALIDATED: {
3416 handlePromptUnvalidated((Network) msg.obj);
3417 break;
3418 }
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07003419 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
3420 handleConfigureAlwaysOnNetworks();
Erik Klineda4bfa82015-04-30 12:58:40 +09003421 break;
3422 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003423 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3424 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3425 mKeepaliveTracker.handleStartKeepalive(msg);
3426 break;
3427 }
3428 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3429 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3430 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3431 int slot = msg.arg1;
3432 int reason = msg.arg2;
3433 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3434 break;
3435 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003436 case EVENT_SYSTEM_READY: {
3437 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003438 // Might have been called already in handleRegisterNetworkAgent since
3439 // mSystemReady is set before sending EVENT_SYSTEM_READY, but calling
3440 // this several times is fine.
3441 try {
3442 nai.networkMonitor().notifySystemReady();
3443 } catch (RemoteException e) {
3444 e.rethrowFromSystemServer();
3445 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003446 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003447 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003448 break;
3449 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003450 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003451 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003452 break;
3453 }
Erik Klinea24d4592018-01-11 21:07:29 +09003454 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3455 handlePrivateDnsSettingsChanged();
3456 break;
dalyk7301aa42018-03-05 12:42:22 -05003457 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3458 handlePrivateDnsValidationUpdate(
3459 (PrivateDnsValidationUpdate) msg.obj);
3460 break;
junyulai05986c62018-08-07 19:50:45 +08003461 case EVENT_UID_RULES_CHANGED:
3462 handleUidRulesChanged(msg.arg1, msg.arg2);
3463 break;
3464 case EVENT_DATA_SAVER_CHANGED:
3465 handleRestrictBackgroundChanged(toBool(msg.arg1));
3466 break;
lucaslind2e045e02019-01-24 15:55:30 +08003467 case EVENT_TIMEOUT_NOTIFICATION:
3468 mNotifier.clearNotification(msg.arg1, NotificationType.LOGGED_IN);
3469 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 }
3471 }
3472 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003473
3474 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003475 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003476 public int tether(String iface, String callerPkg) {
3477 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003478 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003479 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003480 } else {
3481 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3482 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003483 }
3484
3485 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003486 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003487 public int untether(String iface, String callerPkg) {
3488 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003489
3490 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003491 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003492 } else {
3493 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3494 }
3495 }
3496
3497 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003498 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003499 public int getLastTetherError(String iface) {
3500 enforceTetherAccessPermission();
3501
3502 if (isTetheringSupported()) {
3503 return mTethering.getLastTetherError(iface);
3504 } else {
3505 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3506 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003507 }
3508
3509 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003510 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003511 public String[] getTetherableUsbRegexs() {
3512 enforceTetherAccessPermission();
3513 if (isTetheringSupported()) {
3514 return mTethering.getTetherableUsbRegexs();
3515 } else {
3516 return new String[0];
3517 }
3518 }
3519
Lorenzo Colitti18660282016-07-04 12:55:44 +09003520 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003521 public String[] getTetherableWifiRegexs() {
3522 enforceTetherAccessPermission();
3523 if (isTetheringSupported()) {
3524 return mTethering.getTetherableWifiRegexs();
3525 } else {
3526 return new String[0];
3527 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003528 }
3529
Lorenzo Colitti18660282016-07-04 12:55:44 +09003530 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003531 public String[] getTetherableBluetoothRegexs() {
3532 enforceTetherAccessPermission();
3533 if (isTetheringSupported()) {
3534 return mTethering.getTetherableBluetoothRegexs();
3535 } else {
3536 return new String[0];
3537 }
3538 }
3539
Lorenzo Colitti18660282016-07-04 12:55:44 +09003540 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003541 public int setUsbTethering(boolean enable, String callerPkg) {
3542 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003543 if (isTetheringSupported()) {
3544 return mTethering.setUsbTethering(enable);
3545 } else {
3546 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3547 }
3548 }
3549
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003550 // TODO - move iface listing, queries, etc to new module
3551 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003552 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003553 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003554 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003555 return mTethering.getTetherableIfaces();
3556 }
3557
Lorenzo Colitti18660282016-07-04 12:55:44 +09003558 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003559 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003560 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003561 return mTethering.getTetheredIfaces();
3562 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003563
Lorenzo Colitti18660282016-07-04 12:55:44 +09003564 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003565 public String[] getTetheringErroredIfaces() {
3566 enforceTetherAccessPermission();
3567 return mTethering.getErroredIfaces();
3568 }
3569
Lorenzo Colitti18660282016-07-04 12:55:44 +09003570 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003571 public String[] getTetheredDhcpRanges() {
3572 enforceConnectivityInternalPermission();
3573 return mTethering.getTetheredDhcpRanges();
3574 }
3575
Udam Saini0e94c362017-06-07 12:06:28 -07003576 @Override
3577 public boolean isTetheringSupported(String callerPkg) {
3578 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3579 return isTetheringSupported();
3580 }
3581
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003582 // if ro.tether.denied = true we default to no tethering
3583 // gservices could set the secure setting to 1 though to enable it on a build where it
3584 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003585 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003586 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3587 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3588 Settings.Global.TETHER_SUPPORTED, defaultVal));
3589 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003590 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003591
3592 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3593 boolean adminUser = false;
3594 final long token = Binder.clearCallingIdentity();
3595 try {
3596 adminUser = mUserManager.isAdminUser();
3597 } finally {
3598 Binder.restoreCallingIdentity(token);
3599 }
3600
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003601 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003602 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003603
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003604 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003605 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3606 String callerPkg) {
3607 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003608 if (!isTetheringSupported()) {
3609 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3610 return;
3611 }
3612 mTethering.startTethering(type, receiver, showProvisioningUi);
3613 }
3614
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003615 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003616 public void stopTethering(int type, String callerPkg) {
3617 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003618 mTethering.stopTethering(type);
3619 }
3620
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003621 // Called when we lose the default network and have no replacement yet.
3622 // This will automatically be cleared after X seconds or a new default network
3623 // becomes CONNECTED, whichever happens first. The timer is started by the
3624 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003625 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003626 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003627 if (mNetTransitionWakeLock.isHeld()) {
3628 return;
3629 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003630 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003631 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3632 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003633 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003634 mWakelockLogs.log("ACQUIRE for " + forWhom);
3635 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3636 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003637 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003638
Hugo Benichi4c31b342017-03-30 23:18:10 +09003639 // Called when we gain a new default network to release the network transition wakelock in a
3640 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3641 // message is cancelled.
3642 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003643 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003644 if (!mNetTransitionWakeLock.isHeld()) {
3645 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003646 }
3647 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003648 // Cancel self timeout on wakelock hold.
3649 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3650 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3651 mHandler.sendMessageDelayed(msg, 1000);
3652 }
3653
3654 // Called when either message of ensureNetworkTransitionWakelock or
3655 // scheduleReleaseNetworkTransitionWakelock is processed.
3656 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3657 String event = eventName(eventId);
3658 synchronized (this) {
3659 if (!mNetTransitionWakeLock.isHeld()) {
3660 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3661 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3662 return;
3663 }
3664 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003665 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3666 mTotalWakelockDurationMs += lockDuration;
3667 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3668 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003669 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003670 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003671 }
3672
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003673 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003674 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003675 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003676 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003677 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003678 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003679 }
3680
Lorenzo Colitti18660282016-07-04 12:55:44 +09003681 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003682 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003683 enforceAccessPermission();
3684 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003685 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003686 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003687 mHandler.sendMessage(
3688 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3689 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003690
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003691 private void handleReportNetworkConnectivity(
3692 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003693 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003694 if (network == null) {
3695 nai = getDefaultNetwork();
3696 } else {
3697 nai = getNetworkAgentInfoForNetwork(network);
3698 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003699 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3700 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3701 return;
3702 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003703 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003704 if (hasConnectivity == nai.lastValidated) {
3705 return;
3706 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003707 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003708 int netid = nai.network.netId;
3709 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003710 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003711 // Validating a network that has not yet connected could result in a call to
3712 // rematchNetworkAndRequests() which is not meant to work on such networks.
3713 if (!nai.everConnected) {
3714 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003715 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003716 LinkProperties lp = getLinkProperties(nai);
3717 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3718 return;
3719 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09003720 try {
3721 nai.networkMonitor().forceReevaluation(uid);
3722 } catch (RemoteException e) {
3723 e.rethrowFromSystemServer();
3724 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003725 }
3726
Lorenzo Colitti18660282016-07-04 12:55:44 +09003727 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003728 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean5afbc832018-06-07 18:02:37 +09003729 if (network == null) return mProxyTracker.getDefaultProxy();
3730 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensencee9b512015-05-06 07:32:40 -04003731 if (globalProxy != null) return globalProxy;
3732 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3733 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3734 // caller may not have.
3735 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3736 if (nai == null) return null;
3737 synchronized (nai) {
3738 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3739 if (proxyInfo == null) return null;
3740 return new ProxyInfo(proxyInfo);
3741 }
3742 }
3743
Chalard Jean3c443fc2018-06-07 18:37:59 +09003744 @Override
3745 public void setGlobalProxy(final ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003746 enforceConnectivityInternalPermission();
Chalard Jean3c443fc2018-06-07 18:37:59 +09003747 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003748 }
3749
Chalard Jean5afbc832018-06-07 18:02:37 +09003750 @Override
3751 @Nullable
Jason Monk207900c2014-04-25 15:00:09 -04003752 public ProxyInfo getGlobalProxy() {
Chalard Jean5afbc832018-06-07 18:02:37 +09003753 return mProxyTracker.getGlobalProxy();
Robert Greenwalt434203a2010-10-11 16:00:27 -07003754 }
3755
Jason Monk207900c2014-04-25 15:00:09 -04003756 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003757 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003758 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003759 proxy = null;
3760 }
Chalard Jeandaab8f92018-06-08 12:20:15 +09003761 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003762 }
3763
Paul Jensene0bef712014-12-10 15:12:18 -05003764 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3765 // This method gets called when any network changes proxy, but the broadcast only ever contains
3766 // the default proxy (even if it hasn't changed).
3767 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3768 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003769 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003770 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3771 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3772
Chalard Jean4949dd72018-06-07 17:41:29 +09003773 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jeanb50a2762018-06-08 19:46:44 +09003774 mProxyTracker.sendProxyBroadcast();
Paul Jensene0bef712014-12-10 15:12:18 -05003775 }
3776 }
3777
Robert Greenwalt434203a2010-10-11 16:00:27 -07003778 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003779 final private HashMap<Uri, Integer> mUriEventMap;
3780 final private Context mContext;
3781 final private Handler mHandler;
3782
3783 SettingsObserver(Context context, Handler handler) {
3784 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003785 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003786 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003787 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003788 }
3789
Erik Klineda4bfa82015-04-30 12:58:40 +09003790 void observe(Uri uri, int what) {
3791 mUriEventMap.put(uri, what);
3792 final ContentResolver resolver = mContext.getContentResolver();
3793 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003794 }
3795
3796 @Override
3797 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003798 Slog.wtf(TAG, "Should never be reached.");
3799 }
3800
3801 @Override
3802 public void onChange(boolean selfChange, Uri uri) {
3803 final Integer what = mUriEventMap.get(uri);
3804 if (what != null) {
3805 mHandler.obtainMessage(what.intValue()).sendToTarget();
3806 } else {
3807 loge("No matching event to send for URI=" + uri);
3808 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003809 }
3810 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003811
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003812 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003813 Slog.d(TAG, s);
3814 }
3815
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003816 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003817 Slog.e(TAG, s);
3818 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003819
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003820 private static void loge(String s, Throwable t) {
3821 Slog.e(TAG, s, t);
3822 }
3823
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003824 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003825 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003826 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3827 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3828 *
3829 * @param oldPackage Package name of the application which currently controls VPN, which will
3830 * be replaced. If there is no such application, this should should either be
3831 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3832 * @param newPackage Package name of the application which should gain control of VPN, or
3833 * {@code null} to disable.
3834 * @param userId User for whom to prepare the new VPN.
3835 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003836 * @hide
3837 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003838 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003839 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3840 int userId) {
3841 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003842
Hugo Benichi20035e02017-04-26 14:53:28 +09003843 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003844 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003845 Vpn vpn = mVpns.get(userId);
3846 if (vpn != null) {
3847 return vpn.prepare(oldPackage, newPackage);
3848 } else {
3849 return false;
3850 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003851 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003852 }
3853
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003854 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003855 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3856 * This method is used by system-privileged apps.
3857 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3858 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3859 *
3860 * @param packageName The package for which authorization state should change.
3861 * @param userId User for whom {@code packageName} is installed.
3862 * @param authorized {@code true} if this app should be able to start a VPN connection without
3863 * explicit user approval, {@code false} if not.
3864 *
Jeff Davidson05542602014-08-11 14:07:27 -07003865 * @hide
3866 */
3867 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003868 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3869 enforceCrossUserPermission(userId);
3870
Hugo Benichi20035e02017-04-26 14:53:28 +09003871 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003872 Vpn vpn = mVpns.get(userId);
3873 if (vpn != null) {
3874 vpn.setPackageAuthorization(packageName, authorized);
3875 }
Jeff Davidson05542602014-08-11 14:07:27 -07003876 }
3877 }
3878
3879 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003880 * Configure a TUN interface and return its file descriptor. Parameters
3881 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003882 * and not available in ConnectivityManager. Permissions are checked in
3883 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003884 * @hide
3885 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003886 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003887 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003888 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003889 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003890 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003891 return mVpns.get(user).establish(config);
3892 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003893 }
3894
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003895 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003896 * Start legacy VPN, controlling native daemons as needed. Creates a
3897 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003898 */
3899 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003900 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003901 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003902 final LinkProperties egress = getActiveLinkProperties();
3903 if (egress == null) {
3904 throw new IllegalStateException("Missing active network connection");
3905 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003906 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003907 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003908 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3909 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003910 }
3911
3912 /**
3913 * Return the information of the ongoing legacy VPN. This method is used
3914 * by VpnSettings and not available in ConnectivityManager. Permissions
3915 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003916 */
3917 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003918 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3919 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003920
Hugo Benichi20035e02017-04-26 14:53:28 +09003921 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003922 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003923 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003924 }
3925
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003926 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003927 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3928 * and not available in ConnectivityManager.
3929 */
3930 @Override
3931 public VpnInfo[] getAllVpnInfo() {
3932 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003933 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003934 if (mLockdownEnabled) {
3935 return new VpnInfo[0];
3936 }
3937
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003938 List<VpnInfo> infoList = new ArrayList<>();
3939 for (int i = 0; i < mVpns.size(); i++) {
3940 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3941 if (info != null) {
3942 infoList.add(info);
3943 }
3944 }
3945 return infoList.toArray(new VpnInfo[infoList.size()]);
3946 }
3947 }
3948
3949 /**
3950 * @return VPN information for accounting, or null if we can't retrieve all required
3951 * information, e.g primary underlying iface.
3952 */
3953 @Nullable
3954 private VpnInfo createVpnInfo(Vpn vpn) {
3955 VpnInfo info = vpn.getVpnInfo();
3956 if (info == null) {
3957 return null;
3958 }
3959 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3960 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3961 // the underlyingNetworks list.
3962 if (underlyingNetworks == null) {
3963 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3964 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3965 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3966 }
3967 } else if (underlyingNetworks.length > 0) {
3968 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3969 if (linkProperties != null) {
3970 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3971 }
3972 }
3973 return info.primaryUnderlyingIface == null ? null : info;
3974 }
3975
3976 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003977 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3978 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003979 * Permissions are checked in Vpn class.
3980 * @hide
3981 */
3982 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003983 public VpnConfig getVpnConfig(int userId) {
3984 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003985 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003986 Vpn vpn = mVpns.get(userId);
3987 if (vpn != null) {
3988 return vpn.getVpnConfig();
3989 } else {
3990 return null;
3991 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003992 }
3993 }
3994
Chalard Jean6b65ec72018-05-18 22:02:56 +09003995 /**
3996 * Ask all VPN objects to recompute and update their capabilities.
3997 *
3998 * When underlying networks change, VPNs may have to update capabilities to reflect things
3999 * like the metered bit, their transports, and so on. This asks the VPN objects to update
4000 * their capabilities, and as this will cause them to send messages to the ConnectivityService
4001 * handler thread through their agent, this is asynchronous. When the capabilities objects
4002 * are computed they will be up-to-date as they are computed synchronously from here and
4003 * this is running on the ConnectivityService thread.
4004 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
4005 */
4006 private void updateAllVpnsCapabilities() {
4007 synchronized (mVpns) {
4008 for (int i = 0; i < mVpns.size(); i++) {
4009 final Vpn vpn = mVpns.valueAt(i);
4010 vpn.updateCapabilities();
4011 }
4012 }
4013 }
4014
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004015 @Override
4016 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08004017 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4018 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4019 return false;
4020 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004021
Hugo Benichi69744342017-11-27 10:57:16 +09004022 synchronized (mVpns) {
4023 // Tear down existing lockdown if profile was removed
4024 mLockdownEnabled = LockdownVpnTracker.isEnabled();
4025 if (mLockdownEnabled) {
4026 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
4027 if (profileTag == null) {
4028 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
4029 return false;
4030 }
4031 String profileName = new String(profileTag);
4032 final VpnProfile profile = VpnProfile.decode(
4033 profileName, mKeyStore.get(Credentials.VPN + profileName));
4034 if (profile == null) {
4035 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
4036 setLockdownTracker(null);
4037 return true;
4038 }
4039 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00004040 Vpn vpn = mVpns.get(user);
4041 if (vpn == null) {
4042 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
4043 return false;
4044 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004045 setLockdownTracker(new LockdownVpnTracker(mContext, mNMS, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09004046 } else {
4047 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004048 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004049 }
4050
4051 return true;
4052 }
4053
4054 /**
4055 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4056 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4057 */
Hugo Benichi69744342017-11-27 10:57:16 +09004058 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004059 private void setLockdownTracker(LockdownVpnTracker tracker) {
4060 // Shutdown any existing tracker
4061 final LockdownVpnTracker existing = mLockdownTracker;
junyulai05986c62018-08-07 19:50:45 +08004062 // TODO: Add a trigger when the always-on VPN enable/disable to reevaluate and send the
4063 // necessary onBlockedStatusChanged callbacks.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004064 mLockdownTracker = null;
4065 if (existing != null) {
4066 existing.shutdown();
4067 }
4068
Robin Leec3736bc2017-03-10 16:19:54 +00004069 if (tracker != null) {
4070 mLockdownTracker = tracker;
4071 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004072 }
4073 }
4074
Hugo Benichi69744342017-11-27 10:57:16 +09004075 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07004076 private void throwIfLockdownEnabled() {
4077 if (mLockdownEnabled) {
4078 throw new IllegalStateException("Unavailable in lockdown mode");
4079 }
4080 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07004081
Robin Lee244ce8e2016-01-05 18:03:46 +00004082 /**
Robin Lee17e61832016-05-09 13:46:28 +01004083 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
4084 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00004085 *
Robin Lee17e61832016-05-09 13:46:28 +01004086 * @return {@code true} if the service was started, the service was already connected, or there
4087 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00004088 */
Robin Lee17e61832016-05-09 13:46:28 +01004089 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01004090 synchronized (mVpns) {
4091 Vpn vpn = mVpns.get(userId);
4092 if (vpn == null) {
Chalard Jean4d660112018-06-04 16:52:49 +09004093 // Shouldn't happen as all code paths that point here should have checked the Vpn
Robin Lee17e61832016-05-09 13:46:28 +01004094 // exists already.
4095 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
4096 return false;
4097 }
Robin Lee244ce8e2016-01-05 18:03:46 +00004098
Robin Lee812800c2016-05-13 15:38:08 +01004099 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00004100 }
4101 }
4102
4103 @Override
Charles He36738632017-05-15 17:07:18 +01004104 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
4105 enforceSettingsPermission();
4106 enforceCrossUserPermission(userId);
4107
4108 synchronized (mVpns) {
4109 Vpn vpn = mVpns.get(userId);
4110 if (vpn == null) {
4111 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4112 return false;
4113 }
4114 return vpn.isAlwaysOnPackageSupported(packageName);
4115 }
4116 }
4117
4118 @Override
Robin Leedc679712016-05-03 13:23:03 +01004119 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004120 enforceConnectivityInternalPermission();
4121 enforceCrossUserPermission(userId);
4122
Robin Lee244ce8e2016-01-05 18:03:46 +00004123 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09004124 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
4125 if (LockdownVpnTracker.isEnabled()) {
4126 return false;
4127 }
4128
Robin Lee244ce8e2016-01-05 18:03:46 +00004129 Vpn vpn = mVpns.get(userId);
4130 if (vpn == null) {
4131 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4132 return false;
4133 }
Robin Lee17e61832016-05-09 13:46:28 +01004134 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00004135 return false;
4136 }
Robin Lee17e61832016-05-09 13:46:28 +01004137 if (!startAlwaysOnVpn(userId)) {
4138 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00004139 return false;
4140 }
4141 }
4142 return true;
4143 }
4144
4145 @Override
4146 public String getAlwaysOnVpnPackage(int userId) {
4147 enforceConnectivityInternalPermission();
4148 enforceCrossUserPermission(userId);
4149
4150 synchronized (mVpns) {
4151 Vpn vpn = mVpns.get(userId);
4152 if (vpn == null) {
4153 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
4154 return null;
4155 }
4156 return vpn.getAlwaysOnPackage();
4157 }
4158 }
4159
Wink Savilleab9321d2013-06-29 21:10:57 -07004160 @Override
Wink Saville948282b2013-08-29 08:55:16 -07004161 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04004162 // TODO: Remove? Any reason to trigger a provisioning check?
4163 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07004164 }
4165
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004166 /** Location to an updatable file listing carrier provisioning urls.
4167 * An example:
4168 *
4169 * <?xml version="1.0" encoding="utf-8"?>
4170 * <provisioningUrls>
4171 * <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 -07004172 * </provisioningUrls>
4173 */
4174 private static final String PROVISIONING_URL_PATH =
4175 "/data/misc/radio/provisioning_urls.xml";
4176 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07004177
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004178 /** XML tag for root element. */
4179 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4180 /** XML tag for individual url */
4181 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004182 /** XML attribute for mcc */
4183 private static final String ATTR_MCC = "mcc";
4184 /** XML attribute for mnc */
4185 private static final String ATTR_MNC = "mnc";
4186
Paul Jensen434dde82015-06-11 09:43:30 -04004187 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004188 FileReader fileReader = null;
4189 XmlPullParser parser = null;
4190 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004191
4192 try {
4193 fileReader = new FileReader(mProvisioningUrlFile);
4194 parser = Xml.newPullParser();
4195 parser.setInput(fileReader);
4196 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4197
4198 while (true) {
4199 XmlUtils.nextElement(parser);
4200
4201 String element = parser.getName();
4202 if (element == null) break;
4203
Paul Jensen434dde82015-06-11 09:43:30 -04004204 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004205 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4206 try {
4207 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4208 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4209 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4210 parser.next();
4211 if (parser.getEventType() == XmlPullParser.TEXT) {
4212 return parser.getText();
4213 }
4214 }
4215 }
4216 } catch (NumberFormatException e) {
4217 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4218 }
4219 }
4220 }
4221 return null;
4222 } catch (FileNotFoundException e) {
4223 loge("Carrier Provisioning Urls file not found");
4224 } catch (XmlPullParserException e) {
4225 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4226 } catch (IOException e) {
4227 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4228 } finally {
4229 if (fileReader != null) {
4230 try {
4231 fileReader.close();
4232 } catch (IOException e) {}
4233 }
4234 }
4235 return null;
4236 }
4237
Wink Saville42d4f082013-07-20 20:31:59 -07004238 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004239 public String getMobileProvisioningUrl() {
4240 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04004241 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004242 if (TextUtils.isEmpty(url)) {
4243 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07004244 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004245 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004246 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004247 }
Wink Saville8cf35602013-07-10 23:00:07 -07004248 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004249 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004250 String phoneNumber = mTelephonyManager.getLine1Number();
4251 if (TextUtils.isEmpty(phoneNumber)) {
4252 phoneNumber = "0000000000";
4253 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004254 url = String.format(url,
4255 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4256 mTelephonyManager.getDeviceId() /* IMEI */,
Chalard Jean4d660112018-06-04 16:52:49 +09004257 phoneNumber /* Phone number */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004258 }
4259
Wink Savilleab9321d2013-06-29 21:10:57 -07004260 return url;
4261 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004262
Wink Saville948282b2013-08-29 08:55:16 -07004263 @Override
4264 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004265 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004266 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004267 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4268 return;
4269 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004270 final long ident = Binder.clearCallingIdentity();
4271 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004272 // Concatenate the range of types onto the range of NetIDs.
4273 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4274 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004275 } finally {
4276 Binder.restoreCallingIdentity(ident);
4277 }
Wink Saville948282b2013-08-29 08:55:16 -07004278 }
Wink Saville7788c612013-08-29 14:57:08 -07004279
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004280 @Override
4281 public void setAirplaneMode(boolean enable) {
Lorenzo Colittif5845d12018-10-09 18:55:11 +09004282 enforceNetworkStackSettingsOrSetup();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004283 final long ident = Binder.clearCallingIdentity();
4284 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004285 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004286 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004287 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4288 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004289 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004290 } finally {
4291 Binder.restoreCallingIdentity(ident);
4292 }
4293 }
4294
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004295 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004296 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004297 Vpn userVpn = mVpns.get(userId);
4298 if (userVpn != null) {
4299 loge("Starting user already has a VPN");
4300 return;
4301 }
Luke Huang4e25ec62018-09-27 16:58:23 +08004302 userVpn = new Vpn(mHandler.getLooper(), mContext, mNMS, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004303 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004304 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4305 updateLockdownVpn();
4306 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004307 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004308 }
4309
4310 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004311 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004312 Vpn userVpn = mVpns.get(userId);
4313 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004314 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004315 return;
4316 }
Robin Lee17e61832016-05-09 13:46:28 +01004317 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004318 mVpns.delete(userId);
4319 }
4320 }
4321
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004322 private void onUserAdded(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004323 mPermissionMonitor.onUserAdded(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004324 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004325 final int vpnsSize = mVpns.size();
4326 for (int i = 0; i < vpnsSize; i++) {
4327 Vpn vpn = mVpns.valueAt(i);
4328 vpn.onUserAdded(userId);
4329 }
4330 }
4331 }
4332
4333 private void onUserRemoved(int userId) {
junyulai2454b692018-11-01 17:16:31 +08004334 mPermissionMonitor.onUserRemoved(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09004335 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004336 final int vpnsSize = mVpns.size();
4337 for (int i = 0; i < vpnsSize; i++) {
4338 Vpn vpn = mVpns.valueAt(i);
4339 vpn.onUserRemoved(userId);
4340 }
4341 }
4342 }
4343
junyulai2454b692018-11-01 17:16:31 +08004344 private void onPackageAdded(String packageName, int uid) {
4345 if (TextUtils.isEmpty(packageName) || uid < 0) {
4346 Slog.wtf(TAG, "Invalid package in onPackageAdded: " + packageName + " | " + uid);
4347 return;
4348 }
4349 mPermissionMonitor.onPackageAdded(packageName, uid);
4350 }
4351
junyulaiefb04d32018-11-12 22:39:30 +08004352 private void onPackageReplaced(String packageName, int uid) {
4353 if (TextUtils.isEmpty(packageName) || uid < 0) {
4354 Slog.wtf(TAG, "Invalid package in onPackageReplaced: " + packageName + " | " + uid);
4355 return;
4356 }
4357 final int userId = UserHandle.getUserId(uid);
4358 synchronized (mVpns) {
4359 final Vpn vpn = mVpns.get(userId);
4360 if (vpn == null) {
4361 return;
4362 }
4363 // Legacy always-on VPN won't be affected since the package name is not set.
4364 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName)) {
4365 Slog.d(TAG, "Restarting always-on VPN package " + packageName + " for user "
4366 + userId);
4367 vpn.startAlwaysOnVpn();
4368 }
4369 }
4370 }
4371
4372 private void onPackageRemoved(String packageName, int uid, boolean isReplacing) {
junyulai2454b692018-11-01 17:16:31 +08004373 if (TextUtils.isEmpty(packageName) || uid < 0) {
4374 Slog.wtf(TAG, "Invalid package in onPackageRemoved: " + packageName + " | " + uid);
4375 return;
4376 }
4377 mPermissionMonitor.onPackageRemoved(uid);
junyulaiefb04d32018-11-12 22:39:30 +08004378
4379 final int userId = UserHandle.getUserId(uid);
4380 synchronized (mVpns) {
4381 final Vpn vpn = mVpns.get(userId);
4382 if (vpn == null) {
4383 return;
4384 }
4385 // Legacy always-on VPN won't be affected since the package name is not set.
4386 if (TextUtils.equals(vpn.getAlwaysOnPackage(), packageName) && !isReplacing) {
4387 Slog.d(TAG, "Removing always-on VPN package " + packageName + " for user "
4388 + userId);
4389 vpn.setAlwaysOnPackage(null, false);
4390 }
4391 }
junyulai2454b692018-11-01 17:16:31 +08004392 }
4393
Robin Lee89e7a692016-02-29 14:38:17 +00004394 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004395 synchronized (mVpns) {
4396 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4397 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4398 updateLockdownVpn();
4399 } else {
4400 startAlwaysOnVpn(userId);
4401 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004402 }
4403 }
4404
junyulai2454b692018-11-01 17:16:31 +08004405 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004406 @Override
4407 public void onReceive(Context context, Intent intent) {
4408 final String action = intent.getAction();
4409 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
junyulai2454b692018-11-01 17:16:31 +08004410 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
4411 final Uri packageData = intent.getData();
4412 final String packageName =
4413 packageData != null ? packageData.getSchemeSpecificPart() : null;
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004414 if (userId == UserHandle.USER_NULL) return;
4415
Robin Lee323f29d2016-05-04 16:38:06 +01004416 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004417 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004418 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004419 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004420 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4421 onUserAdded(userId);
4422 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4423 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004424 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4425 onUserUnlocked(userId);
junyulai2454b692018-11-01 17:16:31 +08004426 } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
4427 onPackageAdded(packageName, uid);
junyulaiefb04d32018-11-12 22:39:30 +08004428 } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
4429 onPackageReplaced(packageName, uid);
junyulai2454b692018-11-01 17:16:31 +08004430 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
junyulaiefb04d32018-11-12 22:39:30 +08004431 final boolean isReplacing = intent.getBooleanExtra(
4432 Intent.EXTRA_REPLACING, false);
4433 onPackageRemoved(packageName, uid, isReplacing);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004434 }
4435 }
4436 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004437
Robin Lee95204e02017-01-27 11:59:22 +00004438 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4439 @Override
4440 public void onReceive(Context context, Intent intent) {
4441 // Try creating lockdown tracker, since user present usually means
4442 // unlocked keystore.
4443 updateLockdownVpn();
4444 mContext.unregisterReceiver(this);
4445 }
4446 };
4447
Chalard Jean4133a122018-06-04 13:33:12 +09004448 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4449 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004450
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004451 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4452 // Map from UID to number of NetworkRequests that UID has filed.
4453 @GuardedBy("mUidToNetworkRequestCount")
4454 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4455
Robert Greenwalta67be032014-05-16 15:49:14 -07004456 private static class NetworkFactoryInfo {
4457 public final String name;
4458 public final Messenger messenger;
4459 public final AsyncChannel asyncChannel;
4460
4461 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4462 this.name = name;
4463 this.messenger = messenger;
4464 this.asyncChannel = asyncChannel;
4465 }
4466 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004467
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004468 private void ensureNetworkRequestHasType(NetworkRequest request) {
4469 if (request.type == NetworkRequest.Type.NONE) {
4470 throw new IllegalArgumentException(
4471 "All NetworkRequests in ConnectivityService must have a type");
4472 }
4473 }
4474
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004475 /**
4476 * Tracks info about the requester.
4477 * Also used to notice when the calling process dies so we can self-expire
4478 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004479 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004480 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004481 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004482 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004483 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004484 final int mPid;
4485 final int mUid;
4486 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004487
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004488 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004489 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004490 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004491 mPendingIntent = pi;
4492 messenger = null;
4493 mBinder = null;
4494 mPid = getCallingPid();
4495 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004496 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004497 }
4498
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004499 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004500 super();
4501 messenger = m;
4502 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004503 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004504 mBinder = binder;
4505 mPid = getCallingPid();
4506 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004507 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004508 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004509
4510 try {
4511 mBinder.linkToDeath(this, 0);
4512 } catch (RemoteException e) {
4513 binderDied();
4514 }
4515 }
4516
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004517 private void enforceRequestCountLimit() {
4518 synchronized (mUidToNetworkRequestCount) {
4519 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4520 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004521 throw new ServiceSpecificException(
4522 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004523 }
4524 mUidToNetworkRequestCount.put(mUid, networkRequests);
4525 }
4526 }
4527
Robert Greenwalt9258c642014-03-26 16:47:06 -07004528 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004529 if (mBinder != null) {
4530 mBinder.unlinkToDeath(this, 0);
4531 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004532 }
4533
4534 public void binderDied() {
4535 log("ConnectivityService NetworkRequestInfo binderDied(" +
4536 request + ", " + mBinder + ")");
4537 releaseNetworkRequest(request);
4538 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004539
4540 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004541 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004542 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004543 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004544 }
4545
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004546 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4547 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4548 if (badCapability != null) {
4549 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004550 }
4551 }
4552
Chalard Jeanb03a6222018-04-11 21:09:10 +09004553 // This checks that the passed capabilities either do not request a specific SSID, or the
4554 // calling app has permission to do so.
4555 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4556 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004557 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004558 throw new SecurityException("Insufficient permissions to request a specific SSID");
4559 }
4560 }
4561
Erik Kline9d598e12015-07-13 16:37:51 +09004562 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004563 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004564 synchronized (nai) {
4565 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4566 if (nri.request.networkCapabilities.hasSignalStrength() &&
4567 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4568 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4569 }
4570 }
4571 }
Chalard Jean4133a122018-06-04 13:33:12 +09004572 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004573 }
4574
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004575 private void updateSignalStrengthThresholds(
4576 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4577 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004578 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004579 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4580
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004581 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004582 String detail;
4583 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4584 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4585 } else {
4586 detail = reason;
4587 }
4588 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4589 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4590 }
4591
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004592 nai.asyncChannel.sendMessage(
4593 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004594 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004595 }
4596
Etan Cohen859748f2017-04-03 17:42:34 -07004597 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4598 if (nc == null) {
4599 return;
4600 }
4601 NetworkSpecifier ns = nc.getNetworkSpecifier();
4602 if (ns == null) {
4603 return;
4604 }
4605 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4606 ns.assertValidFromUid(Binder.getCallingUid());
4607 }
4608
Robert Greenwalt9258c642014-03-26 16:47:06 -07004609 @Override
4610 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004611 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004612 final NetworkRequest.Type type = (networkCapabilities == null)
4613 ? NetworkRequest.Type.TRACK_DEFAULT
4614 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004615 // If the requested networkCapabilities is null, take them instead from
4616 // the default network request. This allows callers to keep track of
4617 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004618 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jean26400492018-04-18 20:18:38 +09004619 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004620 enforceAccessPermission();
4621 } else {
4622 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4623 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004624 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4625 // of the app when the request is filed, but we never change the request if the app
4626 // changes network state. http://b/29964605
4627 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004628 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004629 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004630 ensureSufficientPermissionsForRequest(networkCapabilities,
4631 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004632 // Set the UID range for this request to the single UID of the requester, or to an empty
4633 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004634 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4635 // are no visible methods to set the UIDs, an app could use reflection to try and get
4636 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004637 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004638
Etan Cohenba07c8c2017-02-05 10:42:27 -08004639 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004640 throw new IllegalArgumentException("Bad timeout specified");
4641 }
Etan Cohen859748f2017-04-03 17:42:34 -07004642 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004643
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004644 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004645 nextNetworkRequestId(), type);
4646 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004647 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004648
4649 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004650 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004651 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004652 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004653 }
4654 return networkRequest;
4655 }
4656
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004657 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004658 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004659 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004660 } else {
4661 enforceChangePermission();
4662 }
4663 }
4664
fenglub15e72b2015-03-20 11:29:56 -07004665 @Override
fengludb571472015-04-21 17:12:05 -07004666 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004667 enforceAccessPermission();
4668 NetworkAgentInfo nai = null;
4669 if (network == null) {
4670 return false;
4671 }
4672 synchronized (mNetworkForNetId) {
4673 nai = mNetworkForNetId.get(network.netId);
4674 }
4675 if (nai != null) {
4676 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07004677 synchronized (mBandwidthRequests) {
4678 final int uid = Binder.getCallingUid();
4679 Integer uidReqs = mBandwidthRequests.get(uid);
4680 if (uidReqs == null) {
4681 uidReqs = new Integer(0);
4682 }
4683 mBandwidthRequests.put(uid, ++uidReqs);
4684 }
fenglub15e72b2015-03-20 11:29:56 -07004685 return true;
4686 }
4687 return false;
4688 }
4689
Felipe Lemeee27cab2016-06-20 16:36:29 -07004690 private boolean isSystem(int uid) {
4691 return uid < Process.FIRST_APPLICATION_UID;
4692 }
fenglub15e72b2015-03-20 11:29:56 -07004693
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004694 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004695 final int uid = Binder.getCallingUid();
4696 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004697 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004698 return;
4699 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004700 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4701 // Policy already enforced.
4702 return;
4703 }
4704 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4705 // If UID is restricted, don't allow them to bring up metered APNs.
4706 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004707 }
4708 }
4709
Robert Greenwalt9258c642014-03-26 16:47:06 -07004710 @Override
4711 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4712 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004713 checkNotNull(operation, "PendingIntent cannot be null.");
4714 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4715 enforceNetworkRequestPermissions(networkCapabilities);
4716 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004717 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004718 ensureSufficientPermissionsForRequest(networkCapabilities,
4719 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004720 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004721 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004722
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004723 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004724 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4725 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004726 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4728 nri));
4729 return networkRequest;
4730 }
4731
Jeremy Joslin79294842014-12-03 17:15:28 -08004732 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4733 mHandler.sendMessageDelayed(
4734 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4735 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4736 }
4737
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004738 @Override
4739 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004740 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004741 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4742 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004743 }
4744
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004745 // In order to implement the compatibility measure for pre-M apps that call
4746 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4747 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4748 // This ensures it has permission to do so.
4749 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4750 if (nc == null) {
4751 return false;
4752 }
4753 int[] transportTypes = nc.getTransportTypes();
4754 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4755 return false;
4756 }
4757 try {
4758 mContext.enforceCallingOrSelfPermission(
4759 android.Manifest.permission.ACCESS_WIFI_STATE,
4760 "ConnectivityService");
4761 } catch (SecurityException e) {
4762 return false;
4763 }
4764 return true;
4765 }
4766
Robert Greenwalt9258c642014-03-26 16:47:06 -07004767 @Override
4768 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4769 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004770 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4771 enforceAccessPermission();
4772 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004773
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004774 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004775 ensureSufficientPermissionsForRequest(networkCapabilities,
4776 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004777 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004778 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4779 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4780 // onLost and onAvailable callbacks when networks move in and out of the background.
4781 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4782 // can't request networks.
4783 restrictBackgroundRequestForCaller(nc);
4784 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004785
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004786 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004787 NetworkRequest.Type.LISTEN);
4788 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004789 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004790
4791 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4792 return networkRequest;
4793 }
4794
4795 @Override
4796 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4797 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004798 checkNotNull(operation, "PendingIntent cannot be null.");
4799 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4800 enforceAccessPermission();
4801 }
Etan Cohen859748f2017-04-03 17:42:34 -07004802 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004803 ensureSufficientPermissionsForRequest(networkCapabilities,
4804 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004805
Chalard Jeandda156a2018-01-10 21:19:32 +09004806 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004807 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004808
4809 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004810 NetworkRequest.Type.LISTEN);
4811 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004812 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004813
4814 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004815 }
4816
Erik Klineacdd6392016-07-07 16:50:58 +09004817 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004818 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004819 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004820 mHandler.sendMessage(mHandler.obtainMessage(
4821 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004822 }
4823
4824 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004825 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004826 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004827 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4828 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004829 }
4830
Robert Greenwalta67be032014-05-16 15:49:14 -07004831 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004832 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004833 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4834 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4835 }
4836
4837 @Override
4838 public void unregisterNetworkFactory(Messenger messenger) {
4839 enforceConnectivityInternalPermission();
4840 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4841 }
4842
4843 private void handleUnregisterNetworkFactory(Messenger messenger) {
4844 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4845 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004846 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004847 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004848 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004849 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004850 }
4851
Robert Greenwalt7b816022014-04-18 15:25:25 -07004852 /**
4853 * NetworkAgentInfo supporting a request by requestId.
4854 * These have already been vetted (their Capabilities satisfy the request)
4855 * and the are the highest scored network available.
4856 * the are keyed off the Requests requestId.
4857 */
Hugo Benichicd952782017-09-20 11:20:14 +09004858 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4859 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004860 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004861
Paul Jensen31a94f42015-02-13 14:18:39 -05004862 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4863 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004864 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004865 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4866 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4867 // there may not be a strict 1:1 correlation between the two.
4868 @GuardedBy("mNetworkForNetId")
4869 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004870
Robert Greenwalt7b816022014-04-18 15:25:25 -07004871 // NetworkAgentInfo keyed off its connecting messenger
4872 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004873 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004874 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004875
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004876 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004877 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004878
Paul Jensen2c311d62014-11-17 12:34:51 -05004879 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004880 private final NetworkRequest mDefaultRequest;
Chalard Jean6b65ec72018-05-18 22:02:56 +09004881
Erik Klineda4bfa82015-04-30 12:58:40 +09004882 // Request used to optionally keep mobile data active even when higher
4883 // priority networks like Wi-Fi are active.
4884 private final NetworkRequest mDefaultMobileDataRequest;
4885
Leif Hendrik Wildenfd306632018-05-02 12:05:24 -07004886 // Request used to optionally keep wifi data active even when higher
4887 // priority networks like ethernet are active.
4888 private final NetworkRequest mDefaultWifiRequest;
4889
Hugo Benichicd952782017-09-20 11:20:14 +09004890 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4891 synchronized (mNetworkForRequestId) {
4892 return mNetworkForRequestId.get(requestId);
4893 }
4894 }
4895
4896 private void clearNetworkForRequest(int requestId) {
4897 synchronized (mNetworkForRequestId) {
4898 mNetworkForRequestId.remove(requestId);
4899 }
4900 }
4901
4902 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4903 synchronized (mNetworkForRequestId) {
4904 mNetworkForRequestId.put(requestId, nai);
4905 }
4906 }
4907
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004908 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004909 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004910 }
4911
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004912 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004913 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004914 }
4915
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004916 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4917 return nri.request.requestId == mDefaultRequest.requestId;
4918 }
4919
Paul Jensen31a94f42015-02-13 14:18:39 -05004920 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004921 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004922 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004923 enforceConnectivityInternalPermission();
4924
Rubin Xu1bb5c082017-09-05 18:40:49 +01004925 LinkProperties lp = new LinkProperties(linkProperties);
4926 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004927 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4928 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004929 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004930 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004931 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Lorenzo Colitti9307ca22019-01-12 01:54:23 +09004932 mContext, mTrackerHandler, new NetworkMisc(networkMisc), this, mNetd, mNMS);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004933 // Make sure the network capabilities reflect what the agent info says.
4934 nai.networkCapabilities = mixInCapabilities(nai, nc);
Chalard Jeand771aa02018-04-26 16:16:10 +09004935 final String extraInfo = networkInfo.getExtraInfo();
4936 final String name = TextUtils.isEmpty(extraInfo)
4937 ? nai.networkCapabilities.getSSID() : extraInfo;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004938 if (DBG) log("registerNetworkAgent " + nai);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004939 final long token = Binder.clearCallingIdentity();
4940 try {
4941 mContext.getSystemService(NetworkStack.class)
4942 .makeNetworkMonitor(nai.network, name, new NetworkMonitorCallbacks(nai));
4943 } finally {
4944 Binder.restoreCallingIdentity(token);
4945 }
4946 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
4947 // If the network disconnects or sends any other event before that, messages are deferred by
4948 // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
4949 // registration.
Paul Jensen31a94f42015-02-13 14:18:39 -05004950 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004951 }
4952
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004953 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
4954 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004955 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004956 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004957 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004958 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004959 }
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09004960 synchronized (this) {
4961 if (mSystemReady) {
4962 try {
4963 networkMonitor.notifySystemReady();
4964 } catch (RemoteException e) {
4965 e.rethrowFromSystemServer();
4966 }
4967 }
4968 }
4969
4970 try {
4971 networkMonitor.start();
4972 } catch (RemoteException e) {
4973 e.rethrowFromSystemServer();
4974 }
Erik Klinee5dac902018-03-04 21:01:01 +09004975 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4976 NetworkInfo networkInfo = nai.networkInfo;
4977 nai.networkInfo = null;
4978 updateNetworkInfo(nai, networkInfo);
4979 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004980 }
4981
lucaslin25a4ec32018-11-28 12:51:55 +08004982 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties newLp,
4983 LinkProperties oldLp) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004984 int netId = networkAgent.network.netId;
4985
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004986 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4987 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004988 if (networkAgent.clatd != null) {
junyulaia56daad2018-06-05 16:10:04 +08004989 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitti95439462014-10-09 13:44:48 +09004990 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004991
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004992 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004993 updateMtu(newLp, oldLp);
4994 // TODO - figure out what to do for clat
4995// for (LinkProperties lp : newLp.getStackedLinks()) {
4996// updateMtu(lp, null);
4997// }
lucaslin041a1af2018-11-28 19:27:52 +08004998 if (isDefaultNetwork(networkAgent)) {
4999 updateTcpBufferSizes(newLp.getTcpBufferSizes());
5000 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005001
Erik Kline94887872016-04-05 13:30:49 +09005002 updateRoutes(newLp, oldLp, netId);
5003 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05005004 // Make sure LinkProperties represents the latest private DNS status.
5005 // This does not need to be done before updateDnses because the
5006 // LinkProperties are not the source of the private DNS configuration.
5007 // updateDnses will fetch the private DNS configuration from DnsManager.
5008 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09005009
Paul Jensene0bef712014-12-10 15:12:18 -05005010 if (isDefaultNetwork(networkAgent)) {
5011 handleApplyDefaultProxy(newLp.getHttpProxy());
5012 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09005013 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05005014 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005015 // TODO - move this check to cover the whole function
5016 if (!Objects.equals(newLp, oldLp)) {
Chalard Jeanc4f53ba2018-05-23 09:07:51 +09005017 synchronized (networkAgent) {
5018 networkAgent.linkProperties = newLp;
5019 }
lucaslin25a4ec32018-11-28 12:51:55 +08005020 // Start or stop clat accordingly to network state.
5021 networkAgent.updateClat(mNMS);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005022 notifyIfacesChangedForNetworkStats();
lucaslin25a4ec32018-11-28 12:51:55 +08005023 if (networkAgent.everConnected) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005024 try {
5025 networkAgent.networkMonitor().notifyLinkPropertiesChanged();
5026 } catch (RemoteException e) {
5027 e.rethrowFromSystemServer();
5028 }
lucaslin25a4ec32018-11-28 12:51:55 +08005029 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
5030 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005031 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005032
5033 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04005034 }
5035
Joel Scherpelz668370b2017-06-08 15:35:21 +09005036 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean4d660112018-06-04 16:52:49 +09005037 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005038 // marks on unsupported interfaces is harmless.
5039 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5040 return;
5041 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005042
Joel Scherpelz668370b2017-06-08 15:35:21 +09005043 int mark = mContext.getResources().getInteger(
5044 com.android.internal.R.integer.config_networkWakeupPacketMark);
5045 int mask = mContext.getResources().getInteger(
5046 com.android.internal.R.integer.config_networkWakeupPacketMask);
5047
5048 // Mask/mark of zero will not detect anything interesting.
5049 // Don't install rules unless both values are nonzero.
5050 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005051 return;
5052 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09005053
5054 final String prefix = "iface:" + iface;
5055 try {
5056 if (add) {
Luke Huang674660f2018-09-27 19:33:11 +08005057 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005058 } else {
Luke Huang674660f2018-09-27 19:33:11 +08005059 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005060 }
5061 } catch (Exception e) {
5062 loge("Exception modifying wakeup packet monitoring: " + e);
5063 }
5064
Joel Scherpelzb369bf52017-05-22 13:47:41 +09005065 }
5066
5067 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
5068 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09005069 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01005070 oldLp != null ? oldLp.getAllInterfaceNames() : null,
5071 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04005072 for (String iface : interfaceDiff.added) {
5073 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005074 if (DBG) log("Adding iface " + iface + " to network " + netId);
Luke Huang4e25ec62018-09-27 16:58:23 +08005075 mNMS.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005076 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04005077 } catch (Exception e) {
5078 loge("Exception adding interface: " + e);
5079 }
5080 }
5081 for (String iface : interfaceDiff.removed) {
5082 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005083 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09005084 wakeupModifyInterface(iface, caps, false);
Luke Huang4e25ec62018-09-27 16:58:23 +08005085 mNMS.removeInterfaceFromNetwork(iface, netId);
Paul Jensen992f2522014-04-28 10:33:11 -04005086 } catch (Exception e) {
5087 loge("Exception removing interface: " + e);
5088 }
5089 }
5090 }
5091
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005092 /**
5093 * Have netd update routes from oldLp to newLp.
5094 * @return true if routes changed between oldLp and newLp
5095 */
5096 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01005097 // Compare the route diff to determine which routes should be added and removed.
5098 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
5099 oldLp != null ? oldLp.getAllRoutes() : null,
5100 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005101
5102 // add routes before removing old in case it helps with continuous connectivity
5103
Chalard Jean4d660112018-06-04 16:52:49 +09005104 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalt7b816022014-04-18 15:25:25 -07005105 for (RouteInfo route : routeDiff.added) {
5106 if (route.hasGateway()) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005107 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005108 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005109 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005110 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005111 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
5112 loge("Exception in addRoute for non-gateway: " + e);
5113 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005114 }
5115 }
5116 for (RouteInfo route : routeDiff.added) {
5117 if (route.hasGateway() == false) continue;
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005118 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005119 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005120 mNMS.addRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005121 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005122 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
5123 loge("Exception in addRoute for gateway: " + e);
5124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005125 }
5126 }
5127
5128 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005129 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005130 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005131 mNMS.removeRoute(netId, route);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005132 } catch (Exception e) {
5133 loge("Exception in removeRoute: " + e);
5134 }
5135 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04005136 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005137 }
Erik Kline41368502015-06-17 13:19:54 +09005138
Erik Kline94887872016-04-05 13:30:49 +09005139 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5140 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
5141 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07005142 }
Erik Kline94887872016-04-05 13:30:49 +09005143
Erik Kline1742fe12017-12-13 19:40:49 +09005144 final NetworkAgentInfo defaultNai = getDefaultNetwork();
5145 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
5146
Erik Klinea24d4592018-01-11 21:07:29 +09005147 if (DBG) {
5148 final Collection<InetAddress> dnses = newLp.getDnsServers();
5149 log("Setting DNS servers for network " + netId + " to " + dnses);
5150 }
Erik Kline94887872016-04-05 13:30:49 +09005151 try {
Erik Klinea24d4592018-01-11 21:07:29 +09005152 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09005153 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09005154 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09005155 }
Erik Kline4edba012017-04-07 15:29:29 +09005156 }
5157
Luke Huang8a462ec2018-08-24 20:33:16 +08005158 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005159 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005160 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005161 }
5162 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huang8a462ec2018-08-24 20:33:16 +08005163 return INetd.PERMISSION_NETWORK;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005164 }
Luke Huang8a462ec2018-08-24 20:33:16 +08005165 return INetd.PERMISSION_NONE;
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005166 }
5167
Paul Jensen3d194ea2015-06-16 14:27:36 -04005168 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005169 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
5170 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
5171 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04005172 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005173 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005174 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005175 // Don't complain for VPNs since they're not driven by requests and there is no risk of
5176 // causing a connect/teardown loop.
5177 // TODO: remove this altogether and make it the responsibility of the NetworkFactories to
5178 // avoid connect/teardown loops.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005179 if (nai.everConnected &&
Lorenzo Colitti6f192a52018-05-30 16:44:47 +09005180 !nai.isVPN() &&
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005181 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
5182 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005183 // does not cause any request (that is not a listen) currently matching that agent to
5184 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005185 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09005186 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09005187 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09005188 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005189 }
5190
Paul Jensen3d194ea2015-06-16 14:27:36 -04005191 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005192 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04005193 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005194 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005195 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005196 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005197 }
Paul Jensene0988542015-06-25 15:30:08 -04005198 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005199 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005200 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005201 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04005202 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005203 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005204 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005205 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005206 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005207 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005208 if (nai.isSuspended()) {
5209 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
5210 } else {
5211 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
5212 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005213
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005214 return newNc;
5215 }
5216
5217 /**
5218 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
5219 *
5220 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
5221 * capabilities we manage and store in {@code nai}, such as validated status and captive
5222 * portal status)
5223 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
5224 * potentially triggers rematches.
5225 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
5226 * change.)
5227 *
5228 * @param oldScore score of the network before any of the changes that prompted us
5229 * to call this function.
5230 * @param nai the network having its capabilities updated.
5231 * @param nc the new network capabilities.
5232 */
5233 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
5234 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
5235
5236 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005237
Luke Huang8a462ec2018-08-24 20:33:16 +08005238 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
5239 final int newPermission = getNetworkPermission(newNc);
5240 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005241 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005242 mNMS.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005243 } catch (RemoteException e) {
5244 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04005245 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005246 }
5247
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005248 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005249 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005250 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005251 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005252 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005253
Chalard Jeanf213ca12018-01-16 18:43:05 +09005254 updateUids(nai, prevNc, newNc);
5255
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005256 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005257 // If the requestable capabilities haven't changed, and the score hasn't changed, then
5258 // the change we're processing can't affect any requests, it can only affect the listens
5259 // on this network. We might have been called by rematchNetworkAndRequests when a
5260 // network changed foreground state.
5261 processListenRequests(nai, true);
5262 } else {
5263 // If the requestable capabilities have changed or the score changed, we can't have been
5264 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04005265 rematchAllNetworksAndRequests(nai, oldScore);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005266 try {
5267 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5268 } catch (RemoteException e) {
5269 e.rethrowFromSystemServer();
5270 }
Paul Jensene0988542015-06-25 15:30:08 -04005271 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005272 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005273
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005274 if (prevNc != null) {
junyulai05986c62018-08-07 19:50:45 +08005275 final boolean oldMetered = prevNc.isMetered();
5276 final boolean newMetered = newNc.isMetered();
5277 final boolean meteredChanged = oldMetered != newMetered;
5278
5279 if (meteredChanged) {
5280 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
5281 mRestrictBackground);
5282 }
5283
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005284 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005285 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulai05986c62018-08-07 19:50:45 +08005286
5287 // Report changes that are interesting for network statistics tracking.
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005288 if (meteredChanged || roamingChanged) {
5289 notifyIfacesChangedForNetworkStats();
5290 }
5291 }
5292
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09005293 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005294 // Tell VPNs about updated capabilities, since they may need to
5295 // bubble those changes through.
Chalard Jean6b65ec72018-05-18 22:02:56 +09005296 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06005297 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005298 }
5299
Chalard Jeanf213ca12018-01-16 18:43:05 +09005300 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
5301 NetworkCapabilities newNc) {
5302 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
5303 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
5304 if (null == prevRanges) prevRanges = new ArraySet<>();
5305 if (null == newRanges) newRanges = new ArraySet<>();
5306 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
5307
5308 prevRanges.removeAll(newRanges);
5309 newRanges.removeAll(prevRangesCopy);
5310
5311 try {
5312 if (!newRanges.isEmpty()) {
5313 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
5314 newRanges.toArray(addedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005315 mNMS.addVpnUidRanges(nai.network.netId, addedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005316 }
5317 if (!prevRanges.isEmpty()) {
5318 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
5319 prevRanges.toArray(removedRangesArray);
Luke Huang4e25ec62018-09-27 16:58:23 +08005320 mNMS.removeVpnUidRanges(nai.network.netId, removedRangesArray);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005321 }
5322 } catch (Exception e) {
5323 // Never crash!
5324 loge("Exception in updateUids: " + e);
5325 }
5326 }
5327
Hugo Benichief502882017-09-01 01:23:32 +00005328 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07005329 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00005330 // Ignore updates for disconnected networks
5331 return;
5332 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01005333 // newLp is already a defensive copy.
5334 newLp.ensureDirectlyConnectedRoutes();
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005335 if (VDBG || DDBG) {
Hugo Benichief502882017-09-01 01:23:32 +00005336 log("Update of LinkProperties for " + nai.name() +
5337 "; created=" + nai.created +
5338 "; everConnected=" + nai.everConnected);
5339 }
lucaslin25a4ec32018-11-28 12:51:55 +08005340 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichief502882017-09-01 01:23:32 +00005341 }
5342
Paul Jensenc8b9a742014-09-30 15:37:41 -04005343 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005344 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5345 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04005346 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005347 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04005348 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
5349 }
5350 }
5351
Robert Greenwalt7b816022014-04-18 15:25:25 -07005352 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005353 if (VDBG || DDBG){
5354 log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5355 }
Robert Greenwalta67be032014-05-16 15:49:14 -07005356 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07005357 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5358 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005359 }
5360 }
5361
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005362 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5363 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005364 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005365 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005366 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5367 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005368 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005369 sendIntent(nri.mPendingIntent, intent);
5370 }
5371 // else not handled
5372 }
5373
5374 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5375 mPendingIntentWakeLock.acquire();
5376 try {
5377 if (DBG) log("Sending " + pendingIntent);
5378 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5379 } catch (PendingIntent.CanceledException e) {
5380 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5381 mPendingIntentWakeLock.release();
5382 releasePendingNetworkRequest(pendingIntent);
5383 }
5384 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5385 }
5386
5387 @Override
5388 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5389 String resultData, Bundle resultExtras) {
5390 if (DBG) log("Finished sending " + pendingIntent);
5391 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005392 // Release with a delay so the receiving client has an opportunity to put in its
5393 // own request.
5394 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005395 }
5396
Chalard Jeanf19db372018-01-26 19:24:40 +09005397 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005398 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005399 if (nri.messenger == null) {
5400 return; // Default request has no msgr
5401 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005402 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005403 // TODO: check if defensive copies of data is needed.
5404 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005405 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005406 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5407 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005408 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005409 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005410 case ConnectivityManager.CALLBACK_AVAILABLE: {
Etan Cohen836ad572018-12-30 17:59:59 -08005411 putParcelable(bundle, networkCapabilitiesRestrictedForCallerPermissions(
5412 networkAgent.networkCapabilities, nri.mPid, nri.mUid));
Chalard Jean804b8fb2018-01-30 22:41:41 +09005413 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
junyulai05986c62018-08-07 19:50:45 +08005414 // For this notification, arg1 contains the blocked status.
5415 msg.arg1 = arg1;
Chalard Jean804b8fb2018-01-30 22:41:41 +09005416 break;
5417 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005418 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005419 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005420 break;
5421 }
5422 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005423 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005424 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005425 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005426 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005427 break;
5428 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005429 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005430 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005431 break;
5432 }
junyulai05986c62018-08-07 19:50:45 +08005433 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
junyulaie6b36512018-10-24 22:38:06 +08005434 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1 != 0);
junyulai05986c62018-08-07 19:50:45 +08005435 msg.arg1 = arg1;
5436 break;
5437 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005438 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005439 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005440 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005441 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005442 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005443 String notification = ConnectivityManager.getCallbackName(notificationType);
5444 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005445 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005446 nri.messenger.send(msg);
5447 } catch (RemoteException e) {
5448 // may occur naturally in the race of binder death.
5449 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5450 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005451 }
5452
Hugo Benichidba33db2017-03-23 22:40:44 +09005453 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5454 bundle.putParcelable(t.getClass().getSimpleName(), t);
5455 }
5456
Paul Jensenc8b9a742014-09-30 15:37:41 -04005457 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005458 if (nai.numRequestNetworkRequests() != 0) {
5459 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5460 NetworkRequest nr = nai.requestAt(i);
5461 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005462 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005463 loge("Dead network still had at least " + nr);
5464 break;
5465 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005466 }
5467 nai.asyncChannel.disconnect();
5468 }
5469
Robert Greenwalt7b816022014-04-18 15:25:25 -07005470 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5471 if (oldNetwork == null) {
5472 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5473 return;
5474 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005475 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005476
5477 // If we get here it means that the last linger timeout for this network expired. So there
5478 // must be no other active linger timers, and we must stop lingering.
5479 oldNetwork.clearLingerState();
5480
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005481 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005482 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005483 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005484 } else {
5485 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005486 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5487 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005488 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005489 }
5490
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005491 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005492 if (DBG) log("Switching to new default network: " + newNetwork);
Chiachang Wanga6093042018-09-28 22:42:48 +08005493
Paul Jensen27b02b72014-07-14 12:03:33 -04005494 try {
Luke Huang4e25ec62018-09-27 16:58:23 +08005495 mNMS.setDefaultNetId(newNetwork.network.netId);
Paul Jensen27b02b72014-07-14 12:03:33 -04005496 } catch (Exception e) {
5497 loge("Exception setting default network :" + e);
5498 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005499
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005500 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005501 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
lucaslin041a1af2018-11-28 19:27:52 +08005502 updateTcpBufferSizes(newNetwork.linkProperties.getTcpBufferSizes());
Erik Kline1742fe12017-12-13 19:40:49 +09005503 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005504 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005505 }
5506
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005507 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005508 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5509 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5510 NetworkRequest nr = nri.request;
5511 if (!nr.isListen()) continue;
5512 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5513 nai.removeRequest(nri.request.requestId);
5514 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5515 }
5516 }
5517
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005518 if (capabilitiesChanged) {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005519 try {
5520 nai.networkMonitor().notifyNetworkCapabilitiesChanged();
5521 } catch (RemoteException e) {
5522 e.rethrowFromSystemServer();
5523 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005524 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5525 }
5526
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005527 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5528 NetworkRequest nr = nri.request;
5529 if (!nr.isListen()) continue;
5530 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5531 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005532 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005533 }
5534 }
5535 }
5536
Paul Jensen2161a8e2014-09-11 11:00:39 -04005537 // Handles a network appearing or improving its score.
5538 //
5539 // - Evaluates all current NetworkRequests that can be
5540 // satisfied by newNetwork, and reassigns to newNetwork
5541 // any such requests for which newNetwork is the best.
5542 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005543 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005544 // needed. A network is needed if it is the best network for
5545 // one or more NetworkRequests, or if it is a VPN.
5546 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005547 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005548 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005549 //
5550 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5551 // networks that have no chance (i.e. even if validated)
5552 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005553 //
5554 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5555 // it does not remove NetworkRequests that other Networks could better satisfy.
5556 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5557 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5558 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005559 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005560 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005561 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5562 // performed to tear down unvalidated networks that have no chance (i.e. even if
5563 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005564 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005565 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005566 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005567 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005568 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005569 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005570
5571 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5572 final int score = newNetwork.getCurrentScore();
5573
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005574 if (VDBG || DDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005575
Paul Jensen2161a8e2014-09-11 11:00:39 -04005576 // Find and migrate to this Network any NetworkRequests for
5577 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005578 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5579 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005580 NetworkCapabilities nc = newNetwork.networkCapabilities;
5581 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005582 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005583 // Process requests in the first pass and listens in the second pass. This allows us to
5584 // change a network's capabilities depending on which requests it has. This is only
5585 // correct if the change in capabilities doesn't affect whether the network satisfies
5586 // requests or not, and doesn't affect the network's score.
5587 if (nri.request.isListen()) continue;
5588
Hugo Benichicd952782017-09-20 11:20:14 +09005589 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005590 final boolean satisfies = newNetwork.satisfies(nri.request);
5591 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005592 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005593 log("Network " + newNetwork.name() + " was already satisfying" +
5594 " request " + nri.request.requestId + ". No change.");
5595 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005596 keep = true;
5597 continue;
5598 }
5599
5600 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005601 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005602 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005603 // next check if it's better than any current network we're using for
5604 // this request
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005605 if (VDBG || DDBG) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005606 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005607 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005608 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005609 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005610 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005611 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005612 if (currentNetwork != null) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005613 if (VDBG || DDBG){
5614 log(" accepting network in place of " + currentNetwork.name());
5615 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005616 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005617 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005618 affectedNetworks.add(currentNetwork);
5619 } else {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005620 if (VDBG || DDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005621 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005622 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005623 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005624 if (!newNetwork.addRequest(nri.request)) {
5625 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5626 }
5627 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005628 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005629 // Tell NetworkFactories about the new score, so they can stop
5630 // trying to connect if they know they cannot match it.
Chalard Jean4d660112018-06-04 16:52:49 +09005631 // TODO - this could get expensive if we have a lot of requests for this
Robert Greenwalt7b816022014-04-18 15:25:25 -07005632 // network. Think about if there is a way to reduce this. Push
5633 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005634 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005635 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005636 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005637 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005638 if (currentNetwork != null) {
5639 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5640 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005641 }
5642 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005643 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005644 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5645 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005646 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005647 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5648 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5649 // This means this code doesn't have to handle the case where "currentNetwork" no
5650 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5651 if (DBG) {
5652 log("Network " + newNetwork.name() + " stopped satisfying" +
5653 " request " + nri.request.requestId);
5654 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005655 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005656 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005657 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005658 sendUpdatedScoreToFactories(nri.request, 0);
5659 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005660 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5661 newNetwork.name() +
5662 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005663 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005664 // TODO: Technically, sending CALLBACK_LOST here is
5665 // incorrect if there is a replacement network currently
5666 // connected that can satisfy nri, which is a request
5667 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005668 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5669 // so this code is only incorrect for a network that loses
5670 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005671 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005672 }
5673 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005674 if (isNewDefault) {
Chiachang Wanga6093042018-09-28 22:42:48 +08005675 updateDataActivityTracking(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005676 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005677 makeDefault(newNetwork);
5678 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005679 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005680 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005681 // Have a new default network, release the transition wakelock in
5682 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005683 }
5684
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005685 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5686 Slog.wtf(TAG, String.format(
5687 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005688 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005689 }
5690 if (newNetwork.getCurrentScore() != score) {
5691 Slog.wtf(TAG, String.format(
5692 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005693 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005694 }
5695
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005696 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005697 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5698 // If the network went from background to foreground or vice versa, we need to update
5699 // its foreground state. It is safe to do this after rematching the requests because
5700 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5701 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005702 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005703 } else {
5704 processListenRequests(newNetwork, false);
5705 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005706
Paul Jensencf4c2c62015-07-01 14:16:32 -04005707 // do this after the default net is switched, but
5708 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005709 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005710
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005711 // Linger any networks that are no longer needed. This should be done after sending the
5712 // available callback for newNetwork.
5713 for (NetworkAgentInfo nai : affectedNetworks) {
5714 updateLingerState(nai, now);
5715 }
5716 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5717 // does not need to be done in any particular order.
5718 updateLingerState(newNetwork, now);
5719
Paul Jensencf4c2c62015-07-01 14:16:32 -04005720 if (isNewDefault) {
5721 // Maintain the illusion: since the legacy API only
5722 // understands one network at a time, we must pretend
5723 // that the current default network disconnected before
5724 // the new one connected.
5725 if (oldDefaultNetwork != null) {
5726 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5727 oldDefaultNetwork, true);
5728 }
5729 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5730 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5731 notifyLockdownVpn(newNetwork);
5732 }
5733
Robert Greenwalt7b816022014-04-18 15:25:25 -07005734 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005735 // Notify battery stats service about this network, both the normal
5736 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005737 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005738 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005739 final IBatteryStats bs = BatteryStatsService.getService();
5740 final int type = newNetwork.networkInfo.getType();
5741
5742 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5743 bs.noteNetworkInterfaceType(baseIface, type);
5744 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5745 final String stackedIface = stacked.getInterfaceName();
5746 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005747 }
5748 } catch (RemoteException ignored) {
5749 }
5750
Robert Greenwalt152ed372014-12-17 17:19:53 -08005751 // This has to happen after the notifyNetworkCallbacks as that tickles each
5752 // ConnectivityManager instance so that legacy requests correctly bind dns
Chalard Jean4d660112018-06-04 16:52:49 +09005753 // requests to this network. The legacy users are listening for this broadcast
Robert Greenwalt152ed372014-12-17 17:19:53 -08005754 // and will generally do a dns request so they can ensureRouteToHost and if
5755 // they do that before the callbacks happen they'll use the default network.
5756 //
5757 // TODO: Is there still a race here? We send the broadcast
5758 // after sending the callback, but if the app can receive the
5759 // broadcast before the callback, it might still break.
5760 //
5761 // This *does* introduce a race where if the user uses the new api
5762 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5763 // they may get old info. Reverse this after the old startUsing api is removed.
5764 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005765 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5766 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005767 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005768 // legacy type tracker filters out repeat adds
5769 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5770 }
5771 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005772
5773 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5774 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5775 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5776 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5777 if (newNetwork.isVPN()) {
5778 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5779 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005780 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005781 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5782 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005783 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005784 if (nai.getLingerExpiry() > 0) {
5785 // This network has active linger timers and no requests, but is not
5786 // lingering. Linger it.
5787 //
5788 // One way (the only way?) this can happen if this network is unvalidated
5789 // and became unneeded due to another network improving its score to the
5790 // point where this network will no longer be able to satisfy any requests
5791 // even if it validates.
5792 updateLingerState(nai, now);
5793 } else {
5794 if (DBG) log("Reaping " + nai.name());
5795 teardownUnneededNetwork(nai);
5796 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005797 }
5798 }
5799 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005800 }
5801
Paul Jensen1c7ba022015-06-16 14:27:36 -04005802 /**
5803 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5804 * being disconnected.
5805 * @param changed If only one Network's score or capabilities have been modified since the last
5806 * time this function was called, pass this Network in this argument, otherwise pass
5807 * null.
5808 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5809 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5810 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5811 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5812 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005813 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005814 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005815 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5816 // to avoid the slowness. It is not simply enough to process just "changed", for
5817 // example in the case where "changed"'s score decreases and another network should begin
Chalard Jean4d660112018-06-04 16:52:49 +09005818 // satisfying a NetworkRequest that "changed" currently satisfies.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005819
5820 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5821 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5822 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005823 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005824 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005825 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005826 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005827 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5828 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5829 // Rematch higher scoring networks first to prevent requests first matching a lower
5830 // scoring network and then a higher scoring network, which could produce multiple
5831 // callbacks and inadvertently unlinger networks.
5832 Arrays.sort(nais);
5833 for (NetworkAgentInfo nai : nais) {
5834 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005835 // Only reap the last time through the loop. Reaping before all rematching
5836 // is complete could incorrectly teardown a network that hasn't yet been
5837 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005838 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005839 : ReapUnvalidatedNetworks.REAP,
5840 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005841 }
5842 }
5843 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005844
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005845 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005846 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005847 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005848 // For now only update icons for default connection.
5849 // TODO: Update WiFi and cellular icons separately. b/17237507
5850 if (!isDefaultNetwork(nai)) return;
5851
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005852 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005853 // Don't repeat publish.
5854 if (newInetCondition == mDefaultInetConditionPublished) return;
5855
5856 mDefaultInetConditionPublished = newInetCondition;
5857 sendInetConditionBroadcast(nai.networkInfo);
5858 }
5859
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005860 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005861 synchronized (mVpns) {
5862 if (mLockdownTracker != null) {
5863 if (nai != null && nai.isVPN()) {
5864 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5865 } else {
5866 mLockdownTracker.onNetworkInfoChanged();
5867 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005868 }
5869 }
5870 }
5871
Robert Greenwalt7b816022014-04-18 15:25:25 -07005872 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005873 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005874 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005875 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005876 synchronized (networkAgent) {
5877 oldInfo = networkAgent.networkInfo;
5878 networkAgent.networkInfo = newInfo;
5879 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005880 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005881
Robert Greenwalt7b816022014-04-18 15:25:25 -07005882 if (DBG) {
5883 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5884 (oldInfo == null ? "null" : oldInfo.getState()) +
5885 " to " + state);
5886 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005887
Robin Lee585e2482016-05-01 23:00:00 +01005888 if (!networkAgent.created
5889 && (state == NetworkInfo.State.CONNECTED
5890 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005891
5892 // A network that has just connected has zero requests and is thus a foreground network.
5893 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5894
Robert Greenwalt7b816022014-04-18 15:25:25 -07005895 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005896 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005897 if (networkAgent.isVPN()) {
Luke Huang4e25ec62018-09-27 16:58:23 +08005898 mNMS.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005899 (networkAgent.networkMisc == null ||
5900 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005901 } else {
Luke Huang4e25ec62018-09-27 16:58:23 +08005902 mNMS.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005903 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005904 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005905 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005906 loge("Error creating network " + networkAgent.network.netId + ": "
5907 + e.getMessage());
5908 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005909 }
Paul Jenseneec75412014-08-04 12:21:19 -04005910 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005911 }
5912
5913 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5914 networkAgent.everConnected = true;
5915
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005916 if (networkAgent.linkProperties == null) {
5917 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5918 }
5919
Erik Kline736353a2018-03-21 07:18:33 -07005920 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin25a4ec32018-11-28 12:51:55 +08005921 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
5922 null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005923
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09005924 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
5925 // command must be sent after updating LinkProperties to maximize chances of
5926 // NetworkMonitor seeing the correct LinkProperties when starting.
5927 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
5928 try {
5929 networkAgent.networkMonitor().notifyNetworkConnected();
5930 } catch (RemoteException e) {
5931 e.rethrowFromSystemServer();
5932 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005933 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005934
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005935 if (networkAgent.isVPN()) {
5936 // Temporarily disable the default proxy (not global).
Chalard Jean60778f92018-06-08 19:08:25 +09005937 mProxyTracker.setDefaultProxyEnabled(false);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005938 // TODO: support proxy per network.
5939 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005940
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005941 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5942 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5943 // capabilities, so it only needs to be done once on initial connect, not every time the
5944 // network's capabilities change. Note that we do this before rematching the network,
5945 // so we could decide to tear it down immediately afterwards. That's fine though - on
5946 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5947 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005948 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005949
Paul Jensen2161a8e2014-09-11 11:00:39 -04005950 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005951 final long now = SystemClock.elapsedRealtime();
5952 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005953
5954 // This has to happen after matching the requests, because callbacks are just requests.
5955 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005956 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005957 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005958 if (networkAgent.isVPN()) {
Chalard Jean60778f92018-06-08 19:08:25 +09005959 mProxyTracker.setDefaultProxyEnabled(true);
Chalard Jeanf213ca12018-01-16 18:43:05 +09005960 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005961 }
Chalard Jean392971c2018-05-11 20:19:20 +09005962 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005963 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5964 state == NetworkInfo.State.SUSPENDED) {
Chalard Jean4d660112018-06-04 16:52:49 +09005965 // going into or coming out of SUSPEND: re-score and notify
Robert Greenwalt8d482522015-06-24 13:23:42 -07005966 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005967 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005968 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005969 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5970 networkAgent.networkCapabilities);
5971 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5972 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005973 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5974 ConnectivityManager.CALLBACK_SUSPENDED :
5975 ConnectivityManager.CALLBACK_RESUMED));
5976 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005977 }
5978 }
5979
Robert Greenwaltac96c522014-06-03 16:43:57 -07005980 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09005981 if (VDBG || DDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005982 if (score < 0) {
5983 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5984 "). Bumping score to min of 0");
5985 score = 0;
5986 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005987
Paul Jensen2161a8e2014-09-11 11:00:39 -04005988 final int oldScore = nai.getCurrentScore();
5989 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005990
Paul Jensen85cf78e2015-06-25 13:25:07 -04005991 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005992
Paul Jensenc8b9a742014-09-30 15:37:41 -04005993 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005994 }
5995
Erik Klinec75d4fa2017-02-15 19:59:17 +09005996 // Notify only this one new request of the current state. Transfer all the
5997 // current state by calling NetworkCapabilities and LinkProperties callbacks
5998 // so that callers can be guaranteed to have as close to atomicity in state
5999 // transfer as can be supported by this current API.
6000 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07006001 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09006002 if (nri.mPendingIntent != null) {
6003 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
6004 // Attempt no subsequent state pushes where intents are involved.
6005 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006006 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09006007
junyulai05986c62018-08-07 19:50:45 +08006008 final boolean metered = nai.networkCapabilities.isMetered();
6009 final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
6010 metered, mRestrictBackground);
6011 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
6012 }
6013
6014 /**
6015 * Notify of the blocked state apps with a registered callback matching a given NAI.
6016 *
6017 * Unlike other callbacks, blocked status is different between each individual uid. So for
6018 * any given nai, all requests need to be considered according to the uid who filed it.
6019 *
6020 * @param nai The target NetworkAgentInfo.
6021 * @param oldMetered True if the previous network capabilities is metered.
6022 * @param newRestrictBackground True if data saver is enabled.
6023 */
6024 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
6025 boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
6026
6027 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6028 NetworkRequest nr = nai.requestAt(i);
6029 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6030 final int uidRules = mUidRules.get(nri.mUid);
6031 final boolean oldBlocked, newBlocked;
6032 // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
6033 // between these two calls.
6034 synchronized (mVpns) {
6035 oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
6036 oldRestrictBackground);
6037 newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
6038 newRestrictBackground);
6039 }
6040 if (oldBlocked != newBlocked) {
6041 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
6042 encodeBool(newBlocked));
6043 }
6044 }
6045 }
6046
6047 /**
6048 * Notify apps with a given UID of the new blocked state according to new uid rules.
6049 * @param uid The uid for which the rules changed.
6050 * @param newRules The new rules to apply.
6051 */
6052 private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
6053 for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6054 final boolean metered = nai.networkCapabilities.isMetered();
6055 final boolean oldBlocked, newBlocked;
6056 // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
6057 // rules changed event. And this function actually loop through all connected nai and
6058 // its requests. It seems that mVpns lock will be grabbed frequently in this case.
6059 // Reduce the number of locking or optimize the use of lock are likely needed in future.
6060 synchronized (mVpns) {
6061 oldBlocked = isUidNetworkingWithVpnBlocked(
6062 uid, mUidRules.get(uid), metered, mRestrictBackground);
6063 newBlocked = isUidNetworkingWithVpnBlocked(
6064 uid, newRules, metered, mRestrictBackground);
6065 }
6066 if (oldBlocked == newBlocked) {
6067 return;
6068 }
6069 final int arg = encodeBool(newBlocked);
6070 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6071 NetworkRequest nr = nai.requestAt(i);
6072 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6073 if (nri != null && nri.mUid == uid) {
6074 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, arg);
6075 }
6076 }
6077 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07006078 }
6079
Robert Greenwalt8d482522015-06-24 13:23:42 -07006080 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09006081 // The NetworkInfo we actually send out has no bearing on the real
6082 // state of affairs. For example, if the default connection is mobile,
6083 // and a request for HIPRI has just gone away, we need to pretend that
6084 // HIPRI has just disconnected. So we need to set the type to HIPRI and
6085 // the state to DISCONNECTED, even though the network is of type MOBILE
6086 // and is still connected.
6087 NetworkInfo info = new NetworkInfo(nai.networkInfo);
6088 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07006089 if (state != DetailedState.DISCONNECTED) {
6090 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09006091 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006092 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07006093 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006094 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
6095 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
6096 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
6097 if (info.isFailover()) {
6098 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
6099 nai.networkInfo.setFailover(false);
6100 }
6101 if (info.getReason() != null) {
6102 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
6103 }
6104 if (info.getExtraInfo() != null) {
6105 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
6106 }
6107 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006108 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04006109 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006110 if (newDefaultAgent != null) {
6111 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
6112 newDefaultAgent.networkInfo);
6113 } else {
6114 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
6115 }
6116 }
6117 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
6118 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09006119 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006120 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09006121 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07006122 }
6123 }
6124 }
6125
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006126 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaeeeaab92018-10-16 12:50:33 +09006127 if (VDBG || DDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09006128 String notification = ConnectivityManager.getCallbackName(notifyType);
6129 log("notifyType " + notification + " for " + networkAgent.name());
6130 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09006131 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
6132 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07006133 NetworkRequestInfo nri = mNetworkRequests.get(nr);
6134 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09006135 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
6136 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006137 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006138 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08006139 } else {
6140 sendPendingIntentForRequest(nri, networkAgent, notifyType);
6141 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006142 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07006143 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07006144
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006145 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6146 notifyNetworkCallbacks(networkAgent, notifyType, 0);
6147 }
6148
Jeff Sharkey69736342014-12-08 14:50:12 -08006149 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09006150 * Returns the list of all interfaces that could be used by network traffic that does not
6151 * explicitly specify a network. This includes the default network, but also all VPNs that are
6152 * currently connected.
6153 *
6154 * Must be called on the handler thread.
6155 */
6156 private Network[] getDefaultNetworks() {
6157 ArrayList<Network> defaultNetworks = new ArrayList<>();
6158 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
6159 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
6160 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
6161 defaultNetworks.add(nai.network);
6162 }
6163 }
6164 return defaultNetworks.toArray(new Network[0]);
6165 }
6166
6167 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006168 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
6169 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08006170 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08006171 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08006172 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006173 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08006174 } catch (Exception ignored) {
6175 }
6176 }
6177
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006178 @Override
6179 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006180 int user = UserHandle.getUserId(Binder.getCallingUid());
6181 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006182 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006183 return mVpns.get(user).addAddress(address, prefixLength);
6184 }
6185 }
6186
6187 @Override
6188 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006189 int user = UserHandle.getUserId(Binder.getCallingUid());
6190 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006191 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07006192 return mVpns.get(user).removeAddress(address, prefixLength);
6193 }
6194 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006195
6196 @Override
6197 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006198 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09006199 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006200 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09006201 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006202 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006203 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006204 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09006205 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08006206 }
6207 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08006208 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006209
6210 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08006211 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07006212 enforceConnectivityInternalPermission();
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +09006213 return NetworkMonitorUtils.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08006214 }
6215
6216 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006217 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
6218 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
6219 enforceKeepalivePermission();
6220 mKeepaliveTracker.startNattKeepalive(
6221 getNetworkAgentInfoForNetwork(network),
6222 intervalSeconds, messenger, binder,
6223 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
6224 }
6225
6226 @Override
junyulai215b8772019-01-15 11:32:44 +08006227 public void startNattKeepaliveWithFd(Network network, FileDescriptor fd, int resourceId,
6228 int intervalSeconds, Messenger messenger, IBinder binder, String srcAddr,
6229 String dstAddr) {
6230 enforceKeepalivePermission();
6231 mKeepaliveTracker.startNattKeepalive(
6232 getNetworkAgentInfoForNetwork(network), fd, resourceId,
6233 intervalSeconds, messenger, binder,
6234 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
6235 }
6236
6237 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09006238 public void stopKeepalive(Network network, int slot) {
6239 mHandler.sendMessage(mHandler.obtainMessage(
6240 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
6241 }
6242
6243 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07006244 public void factoryReset() {
6245 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006246
6247 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
6248 return;
6249 }
6250
Robin Lee3b3dd942015-05-12 18:14:58 +01006251 final int userId = UserHandle.getCallingUserId();
6252
Stuart Scottf1fb3972015-04-02 18:00:02 -07006253 // Turn airplane mode off
6254 setAirplaneMode(false);
6255
Stuart Scotte3e314d2015-04-20 14:07:45 -07006256 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
6257 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006258 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07006259 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09006260 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07006261 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006262 }
6263
Stuart Scotte3e314d2015-04-20 14:07:45 -07006264 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01006265 // Remove always-on package
6266 synchronized (mVpns) {
6267 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
6268 if (alwaysOnPackage != null) {
6269 setAlwaysOnVpnPackage(userId, null, false);
6270 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
6271 }
Victor Changb04a5ea2016-05-30 20:36:30 +01006272
Hugo Benichi69744342017-11-27 10:57:16 +09006273 // Turn Always-on VPN off
6274 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
6275 final long ident = Binder.clearCallingIdentity();
6276 try {
6277 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
6278 mLockdownEnabled = false;
6279 setLockdownTracker(null);
6280 } finally {
6281 Binder.restoreCallingIdentity(ident);
6282 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006283 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09006284
Hugo Benichi69744342017-11-27 10:57:16 +09006285 // Turn VPN off
6286 VpnConfig vpnConfig = getVpnConfig(userId);
6287 if (vpnConfig != null) {
6288 if (vpnConfig.legacy) {
6289 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
6290 } else {
6291 // Prevent this app (packagename = vpnConfig.user) from initiating
6292 // VPN connections in the future without user intervention.
6293 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006294
Hugo Benichi69744342017-11-27 10:57:16 +09006295 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
6296 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07006297 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07006298 }
6299 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09006300
6301 Settings.Global.putString(mContext.getContentResolver(),
6302 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07006303 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04006304
Ricky Wai44dcbde2018-01-23 04:09:45 +00006305 @Override
6306 public byte[] getNetworkWatchlistConfigHash() {
6307 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
6308 if (nwm == null) {
6309 loge("Unable to get NetworkWatchlistManager");
6310 return null;
6311 }
6312 // Redirect it to network watchlist service to access watchlist file and calculate hash.
6313 return nwm.getWatchlistConfigHash();
6314 }
6315
Paul Jensencf4c2c62015-07-01 14:16:32 -04006316 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09006317 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
6318 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09006319 }
6320
6321 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09006322 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
6323 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
6324 }
6325
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09006326 @VisibleForTesting
6327 public boolean hasService(String name) {
6328 return ServiceManager.checkService(name) != null;
6329 }
6330
Hugo Benichi64901e52017-10-19 14:42:40 +09006331 @VisibleForTesting
6332 protected IpConnectivityMetrics.Logger metricsLogger() {
6333 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
6334 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09006335 }
6336
6337 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09006338 int[] transports = nai.networkCapabilities.getTransportTypes();
6339 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09006340 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09006341
6342 private static boolean toBool(int encodedBoolean) {
6343 return encodedBoolean != 0; // Only 0 means false.
6344 }
6345
6346 private static int encodeBool(boolean b) {
6347 return b ? 1 : 0;
6348 }
mswest46386886f2018-03-12 10:34:34 -07006349
6350 @Override
6351 public void onShellCommand(FileDescriptor in, FileDescriptor out,
6352 FileDescriptor err, String[] args, ShellCallback callback,
6353 ResultReceiver resultReceiver) {
6354 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
6355 }
6356
6357 private class ShellCmd extends ShellCommand {
6358
6359 @Override
6360 public int onCommand(String cmd) {
6361 if (cmd == null) {
6362 return handleDefaultCommands(cmd);
6363 }
6364 final PrintWriter pw = getOutPrintWriter();
6365 try {
6366 switch (cmd) {
6367 case "airplane-mode":
6368 final String action = getNextArg();
6369 if ("enable".equals(action)) {
6370 setAirplaneMode(true);
6371 return 0;
6372 } else if ("disable".equals(action)) {
6373 setAirplaneMode(false);
6374 return 0;
6375 } else if (action == null) {
6376 final ContentResolver cr = mContext.getContentResolver();
6377 final int enabled = Settings.Global.getInt(cr,
6378 Settings.Global.AIRPLANE_MODE_ON);
6379 pw.println(enabled == 0 ? "disabled" : "enabled");
6380 return 0;
6381 } else {
6382 onHelp();
6383 return -1;
6384 }
6385 default:
6386 return handleDefaultCommands(cmd);
6387 }
6388 } catch (Exception e) {
6389 pw.println(e);
6390 }
6391 return -1;
6392 }
6393
6394 @Override
6395 public void onHelp() {
6396 PrintWriter pw = getOutPrintWriter();
6397 pw.println("Connectivity service commands:");
6398 pw.println(" help");
6399 pw.println(" Print this help text.");
6400 pw.println(" airplane-mode [enable|disable]");
6401 pw.println(" Turn airplane mode on or off.");
6402 pw.println(" airplane-mode");
6403 pw.println(" Get airplane mode.");
6404 }
6405 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006406
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006407 @GuardedBy("mVpns")
6408 private Vpn getVpnIfOwner() {
6409 final int uid = Binder.getCallingUid();
6410 final int user = UserHandle.getUserId(uid);
6411
6412 final Vpn vpn = mVpns.get(user);
6413 if (vpn == null) {
6414 return null;
6415 } else {
6416 final VpnInfo info = vpn.getVpnInfo();
6417 return (info == null || info.ownerUid != uid) ? null : vpn;
6418 }
6419 }
6420
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006421 /**
6422 * Caller either needs to be an active VPN, or hold the NETWORK_STACK permission
6423 * for testing.
6424 */
6425 private Vpn enforceActiveVpnOrNetworkStackPermission() {
6426 if (checkNetworkStackPermission()) {
6427 return null;
6428 }
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006429 synchronized (mVpns) {
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006430 Vpn vpn = getVpnIfOwner();
6431 if (vpn != null) {
6432 return vpn;
Jeff Vander Stoep0ac2c092018-07-23 10:57:53 -07006433 }
6434 }
6435 throw new SecurityException("App must either be an active VPN or have the NETWORK_STACK "
6436 + "permission");
6437 }
6438
6439 /**
6440 * @param connectionInfo the connection to resolve.
6441 * @return {@code uid} if the connection is found and the app has permission to observe it
6442 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
6443 * connection is not found.
6444 */
6445 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
6446 final Vpn vpn = enforceActiveVpnOrNetworkStackPermission();
6447 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
6448 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
6449 }
6450
6451 final int uid = InetDiagMessage.getConnectionOwnerUid(connectionInfo.protocol,
6452 connectionInfo.local, connectionInfo.remote);
6453
6454 /* Filter out Uids not associated with the VPN. */
6455 if (vpn != null && !vpn.appliesToUid(uid)) {
6456 return INVALID_UID;
6457 }
6458
6459 return uid;
6460 }
Pavel Grafovcb3b8952018-12-14 13:51:07 +00006461
6462 @Override
6463 public boolean isCallerCurrentAlwaysOnVpnApp() {
6464 synchronized (mVpns) {
6465 Vpn vpn = getVpnIfOwner();
6466 return vpn != null && vpn.getAlwaysOn();
6467 }
6468 }
6469
6470 @Override
6471 public boolean isCallerCurrentAlwaysOnVpnLockdownApp() {
6472 synchronized (mVpns) {
6473 Vpn vpn = getVpnIfOwner();
6474 return vpn != null && vpn.getLockdown();
6475 }
6476 }
Nathan Haroldfd45e5f2018-07-30 13:38:01 -07006477}